2012-12-12 14:23:00 -05:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
|
2014-02-04 14:15:02 -05:00
|
|
|
# Copyright © 2012-2014 Zulip, Inc.
|
2012-11-26 10:55:22 -05:00
|
|
|
#
|
2012-12-12 14:23:00 -05:00
|
|
|
# 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:
|
2012-11-26 10:55:22 -05:00
|
|
|
#
|
2012-12-12 14:23:00 -05:00
|
|
|
# The above copyright notice and this permission notice shall be included in
|
|
|
|
# all copies or substantial portions of the Software.
|
2012-11-26 10:55:22 -05:00
|
|
|
#
|
2012-12-12 14:23:00 -05:00
|
|
|
# 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-11-26 10:55:22 -05:00
|
|
|
|
2015-11-01 11:11:06 -05:00
|
|
|
from __future__ import print_function
|
2015-11-01 11:15:17 -05:00
|
|
|
from __future__ import absolute_import
|
2016-01-23 21:56:05 -05:00
|
|
|
from __future__ import division
|
2017-09-14 05:18:39 -04:00
|
|
|
import json
|
2012-10-04 16:13:47 -04:00
|
|
|
import requests
|
2012-10-01 15:36:44 -04:00
|
|
|
import time
|
2012-10-02 15:47:59 -04:00
|
|
|
import traceback
|
2012-10-22 14:31:21 -04:00
|
|
|
import sys
|
2012-11-26 10:45:11 -05:00
|
|
|
import os
|
2012-12-10 14:42:20 -05:00
|
|
|
import optparse
|
2017-07-26 20:52:52 -04:00
|
|
|
import argparse
|
2013-12-06 16:37:01 -05:00
|
|
|
import platform
|
2014-03-11 14:09:15 -04:00
|
|
|
import random
|
2017-08-25 10:27:52 -04:00
|
|
|
import types
|
2013-03-06 13:48:24 -05:00
|
|
|
from distutils.version import LooseVersion
|
2012-12-10 14:42:20 -05:00
|
|
|
|
2015-11-01 11:14:36 -05:00
|
|
|
from six.moves.configparser import SafeConfigParser
|
2016-01-23 21:39:44 -05:00
|
|
|
from six.moves import urllib
|
2013-10-30 15:56:43 -04:00
|
|
|
import logging
|
2015-11-01 11:15:17 -05:00
|
|
|
import six
|
2017-03-03 13:01:52 -05:00
|
|
|
from typing import Any, Callable, Dict, Iterable, IO, List, Mapping, Optional, Text, Tuple, Union
|
2013-01-31 15:09:59 -05:00
|
|
|
|
2017-10-20 23:40:25 -04:00
|
|
|
__version__ = "0.3.7"
|
2013-01-31 15:09:59 -05:00
|
|
|
|
2014-04-28 19:51:04 -04:00
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
2012-10-04 18:06:54 -04:00
|
|
|
# Check that we have a recent enough version
|
2012-11-01 17:50:38 -04:00
|
|
|
# Older versions don't provide the 'json' attribute on responses.
|
2016-12-02 21:26:47 -05:00
|
|
|
assert(LooseVersion(requests.__version__) >= LooseVersion('0.12.1'))
|
2013-02-05 15:08:48 -05:00
|
|
|
# In newer versions, the 'json' attribute is a function, not a property
|
2013-03-29 11:08:24 -04:00
|
|
|
requests_json_is_function = callable(requests.Response.json)
|
2013-02-05 15:08:48 -05:00
|
|
|
|
2013-06-27 12:09:41 -04:00
|
|
|
API_VERSTRING = "v1/"
|
2012-10-04 18:06:54 -04:00
|
|
|
|
2014-03-11 14:09:15 -04:00
|
|
|
class CountingBackoff(object):
|
2014-03-12 17:06:00 -04:00
|
|
|
def __init__(self, maximum_retries=10, timeout_success_equivalent=None):
|
2016-12-02 21:26:47 -05:00
|
|
|
# type: (int, Optional[float]) -> None
|
2014-03-11 14:09:15 -04:00
|
|
|
self.number_of_retries = 0
|
|
|
|
self.maximum_retries = maximum_retries
|
2014-03-12 17:06:00 -04:00
|
|
|
self.timeout_success_equivalent = timeout_success_equivalent
|
2016-12-02 21:26:47 -05:00
|
|
|
self.last_attempt_time = 0.0
|
2014-03-11 14:09:15 -04:00
|
|
|
|
|
|
|
def keep_going(self):
|
2016-12-02 21:26:47 -05:00
|
|
|
# type: () -> bool
|
2014-03-12 17:06:00 -04:00
|
|
|
self._check_success_timeout()
|
2014-03-11 14:09:15 -04:00
|
|
|
return self.number_of_retries < self.maximum_retries
|
|
|
|
|
|
|
|
def succeed(self):
|
2016-12-02 21:26:47 -05:00
|
|
|
# type: () -> None
|
2014-03-11 14:09:15 -04:00
|
|
|
self.number_of_retries = 0
|
2014-03-12 17:06:00 -04:00
|
|
|
self.last_attempt_time = time.time()
|
2014-03-11 14:09:15 -04:00
|
|
|
|
|
|
|
def fail(self):
|
2016-12-02 21:26:47 -05:00
|
|
|
# type: () -> None
|
2014-03-12 17:06:00 -04:00
|
|
|
self._check_success_timeout()
|
2014-03-11 14:09:15 -04:00
|
|
|
self.number_of_retries = min(self.number_of_retries + 1,
|
|
|
|
self.maximum_retries)
|
2014-03-12 17:06:00 -04:00
|
|
|
self.last_attempt_time = time.time()
|
|
|
|
|
|
|
|
def _check_success_timeout(self):
|
2016-12-02 21:26:47 -05:00
|
|
|
# type: () -> None
|
2017-01-23 23:50:04 -05:00
|
|
|
if (self.timeout_success_equivalent is not None and
|
|
|
|
self.last_attempt_time != 0 and
|
|
|
|
time.time() - self.last_attempt_time > self.timeout_success_equivalent):
|
2014-03-12 17:06:00 -04:00
|
|
|
self.number_of_retries = 0
|
2014-03-11 14:09:15 -04:00
|
|
|
|
|
|
|
class RandomExponentialBackoff(CountingBackoff):
|
|
|
|
def fail(self):
|
2016-12-02 21:26:47 -05:00
|
|
|
# type: () -> None
|
2014-03-12 17:06:00 -04:00
|
|
|
super(RandomExponentialBackoff, self).fail()
|
2014-03-11 14:09:15 -04:00
|
|
|
# Exponential growth with ratio sqrt(2); compute random delay
|
|
|
|
# between x and 2x where x is growing exponentially
|
|
|
|
delay_scale = int(2 ** (self.number_of_retries / 2.0 - 1)) + 1
|
|
|
|
delay = delay_scale + random.randint(1, delay_scale)
|
|
|
|
message = "Sleeping for %ss [max %s] before retrying." % (delay, delay_scale * 2)
|
|
|
|
try:
|
|
|
|
logger.warning(message)
|
|
|
|
except NameError:
|
2015-11-01 11:11:06 -05:00
|
|
|
print(message)
|
2014-03-11 14:09:15 -04:00
|
|
|
time.sleep(delay)
|
|
|
|
|
2013-12-06 17:33:09 -05:00
|
|
|
def _default_client():
|
2016-12-02 21:26:47 -05:00
|
|
|
# type: () -> str
|
2013-12-06 17:33:09 -05:00
|
|
|
return "ZulipPython/" + __version__
|
|
|
|
|
2017-09-01 09:47:10 -04:00
|
|
|
def add_default_arguments(parser, patch_error_handling=True, allow_provisioning=False):
|
2017-09-15 07:24:09 -04:00
|
|
|
# type: (argparse.ArgumentParser, bool, bool) -> argparse.ArgumentParser
|
2017-08-25 10:27:52 -04:00
|
|
|
|
|
|
|
if patch_error_handling:
|
|
|
|
def custom_error_handling(self, message):
|
2017-09-15 07:24:09 -04:00
|
|
|
# type: (Any, str) -> None
|
2017-08-25 10:27:52 -04:00
|
|
|
self.print_help(sys.stderr)
|
|
|
|
self.exit(2, '{}: error: {}\n'.format(self.prog, message))
|
2017-09-15 07:24:09 -04:00
|
|
|
parser.error = types.MethodType(custom_error_handling, parser) # type: ignore
|
2017-08-25 10:27:52 -04:00
|
|
|
|
2017-09-01 09:47:10 -04:00
|
|
|
if allow_provisioning:
|
|
|
|
parser.add_argument('--provision',
|
|
|
|
action='store_true',
|
|
|
|
dest="provision",
|
|
|
|
help="install dependencies for this script (found in requirements.txt)")
|
|
|
|
|
2017-07-26 20:52:52 -04:00
|
|
|
group = parser.add_argument_group('Zulip API configuration')
|
|
|
|
group.add_argument('--site',
|
|
|
|
dest="zulip_site",
|
|
|
|
help="Zulip server URI",
|
|
|
|
default=None)
|
|
|
|
group.add_argument('--api-key',
|
|
|
|
dest="zulip_api_key",
|
|
|
|
action='store')
|
|
|
|
group.add_argument('--user',
|
|
|
|
dest='zulip_email',
|
|
|
|
help='Email address of the calling bot or user.')
|
|
|
|
group.add_argument('--config-file',
|
|
|
|
action='store',
|
|
|
|
dest="zulip_config_file",
|
|
|
|
help='''Location of an ini file containing the above
|
|
|
|
information. (default ~/.zuliprc)''')
|
|
|
|
group.add_argument('-v', '--verbose',
|
|
|
|
action='store_true',
|
|
|
|
help='Provide detailed output.')
|
|
|
|
group.add_argument('--client',
|
|
|
|
action='store',
|
|
|
|
default=None,
|
|
|
|
dest="zulip_client",
|
|
|
|
help=argparse.SUPPRESS)
|
|
|
|
group.add_argument('--insecure',
|
|
|
|
action='store_true',
|
|
|
|
dest='insecure',
|
|
|
|
help='''Do not verify the server certificate.
|
|
|
|
The https connection will not be secure.''')
|
|
|
|
group.add_argument('--cert-bundle',
|
|
|
|
action='store',
|
|
|
|
dest='cert_bundle',
|
|
|
|
help='''Specify a file containing either the
|
|
|
|
server certificate, or a set of trusted
|
|
|
|
CA certificates. This will be used to
|
|
|
|
verify the server's identity. All
|
|
|
|
certificates should be PEM encoded.''')
|
|
|
|
group.add_argument('--client-cert',
|
|
|
|
action='store',
|
|
|
|
dest='client_cert',
|
|
|
|
help='''Specify a file containing a client
|
|
|
|
certificate (not needed for most deployments).''')
|
|
|
|
group.add_argument('--client-cert-key',
|
|
|
|
action='store',
|
|
|
|
dest='client_cert_key',
|
|
|
|
help='''Specify a file containing the client
|
|
|
|
certificate's key (if it is in a separate
|
|
|
|
file).''')
|
|
|
|
return parser
|
|
|
|
|
2017-09-14 05:37:03 -04:00
|
|
|
# This method might seem redundant with `add_default_arguments()`,
|
|
|
|
# except for the fact that is uses the deprecated `optparse` module.
|
|
|
|
# We still keep it for legacy support of out-of-tree bots and integrations
|
|
|
|
# depending on it.
|
2014-02-21 13:49:35 -05:00
|
|
|
def generate_option_group(parser, prefix=''):
|
2016-12-02 21:26:47 -05:00
|
|
|
# type: (optparse.OptionParser, str) -> optparse.OptionGroup
|
2017-07-26 20:52:52 -04:00
|
|
|
logging.warning("""zulip.generate_option_group is based on optparse, which
|
|
|
|
is now deprecated. We recommend migrating to argparse and
|
|
|
|
using zulip.add_default_arguments instead.""")
|
|
|
|
|
2017-11-15 12:02:07 -05:00
|
|
|
group = optparse.OptionGroup(parser, 'Zulip API configuration')
|
2014-02-21 13:49:35 -05:00
|
|
|
group.add_option('--%ssite' % (prefix,),
|
2014-02-21 14:11:29 -05:00
|
|
|
dest="zulip_site",
|
2015-08-21 12:34:54 -04:00
|
|
|
help="Zulip server URI",
|
2013-12-04 15:17:18 -05:00
|
|
|
default=None)
|
2014-02-21 13:49:35 -05:00
|
|
|
group.add_option('--%sapi-key' % (prefix,),
|
2014-02-21 14:11:29 -05:00
|
|
|
dest="zulip_api_key",
|
2012-12-10 14:42:20 -05:00
|
|
|
action='store')
|
2014-02-21 13:49:35 -05:00
|
|
|
group.add_option('--%suser' % (prefix,),
|
2014-02-21 14:11:29 -05:00
|
|
|
dest='zulip_email',
|
2013-05-29 14:00:27 -04:00
|
|
|
help='Email address of the calling bot or user.')
|
2014-02-21 13:49:35 -05:00
|
|
|
group.add_option('--%sconfig-file' % (prefix,),
|
2012-12-10 14:42:20 -05:00
|
|
|
action='store',
|
2014-02-21 14:11:29 -05:00
|
|
|
dest="zulip_config_file",
|
2013-08-07 11:36:46 -04:00
|
|
|
help='Location of an ini file containing the\nabove information. (default ~/.zuliprc)')
|
2012-12-10 14:42:20 -05:00
|
|
|
group.add_option('-v', '--verbose',
|
|
|
|
action='store_true',
|
|
|
|
help='Provide detailed output.')
|
2014-02-21 13:49:35 -05:00
|
|
|
group.add_option('--%sclient' % (prefix,),
|
2013-10-16 16:51:17 -04:00
|
|
|
action='store',
|
2013-12-06 17:34:20 -05:00
|
|
|
default=None,
|
2014-02-21 14:11:29 -05:00
|
|
|
dest="zulip_client",
|
2013-10-16 16:51:17 -04:00
|
|
|
help=optparse.SUPPRESS_HELP)
|
2015-10-20 14:28:03 -04:00
|
|
|
group.add_option('--insecure',
|
|
|
|
action='store_true',
|
|
|
|
dest='insecure',
|
|
|
|
help='''Do not verify the server certificate.
|
|
|
|
The https connection will not be secure.''')
|
|
|
|
group.add_option('--cert-bundle',
|
|
|
|
action='store',
|
|
|
|
dest='cert_bundle',
|
|
|
|
help='''Specify a file containing either the
|
|
|
|
server certificate, or a set of trusted
|
|
|
|
CA certificates. This will be used to
|
|
|
|
verify the server's identity. All
|
|
|
|
certificates should be PEM encoded.''')
|
2016-06-14 21:00:59 -04:00
|
|
|
group.add_option('--client-cert',
|
|
|
|
action='store',
|
|
|
|
dest='client_cert',
|
|
|
|
help='''Specify a file containing a client
|
|
|
|
certificate (not needed for most deployments).''')
|
|
|
|
group.add_option('--client-cert-key',
|
|
|
|
action='store',
|
|
|
|
dest='client_cert_key',
|
|
|
|
help='''Specify a file containing the client
|
|
|
|
certificate's key (if it is in a separate
|
|
|
|
file).''')
|
2012-12-10 14:42:20 -05:00
|
|
|
return group
|
|
|
|
|
2013-12-06 17:34:20 -05:00
|
|
|
def init_from_options(options, client=None):
|
2016-12-02 21:26:47 -05:00
|
|
|
# type: (Any, Optional[str]) -> Client
|
2017-09-01 09:47:10 -04:00
|
|
|
|
2017-09-12 05:02:29 -04:00
|
|
|
if getattr(options, 'provision', False):
|
2017-09-01 09:47:10 -04:00
|
|
|
requirements_path = os.path.abspath(os.path.join(sys.path[0], 'requirements.txt'))
|
|
|
|
try:
|
|
|
|
import pip
|
|
|
|
except ImportError:
|
|
|
|
traceback.print_exc()
|
|
|
|
print("Module `pip` is not installed. To install `pip`, follow the instructions here: "
|
|
|
|
"https://pip.pypa.io/en/stable/installing/")
|
|
|
|
sys.exit(1)
|
|
|
|
if not pip.main(['install', '--upgrade', '--requirement', requirements_path]):
|
2017-09-15 05:45:10 -04:00
|
|
|
print("{color_green}You successfully provisioned the dependencies for {script}.{end_color}".format(
|
|
|
|
color_green='\033[92m', end_color='\033[0m',
|
|
|
|
script=os.path.splitext(os.path.basename(sys.argv[0]))[0]))
|
|
|
|
sys.exit(0)
|
2017-09-01 09:47:10 -04:00
|
|
|
|
2014-02-21 14:11:29 -05:00
|
|
|
if options.zulip_client is not None:
|
|
|
|
client = options.zulip_client
|
2013-12-06 17:34:20 -05:00
|
|
|
elif client is None:
|
|
|
|
client = _default_client()
|
2014-02-21 14:11:29 -05:00
|
|
|
return Client(email=options.zulip_email, api_key=options.zulip_api_key,
|
|
|
|
config_file=options.zulip_config_file, verbose=options.verbose,
|
2015-10-20 14:28:03 -04:00
|
|
|
site=options.zulip_site, client=client,
|
2016-06-14 21:00:59 -04:00
|
|
|
cert_bundle=options.cert_bundle, insecure=options.insecure,
|
|
|
|
client_cert=options.client_cert,
|
|
|
|
client_cert_key=options.client_cert_key)
|
2012-12-10 14:42:20 -05:00
|
|
|
|
2014-03-03 00:51:33 -05:00
|
|
|
def get_default_config_filename():
|
2017-05-29 21:19:59 -04:00
|
|
|
# type: () -> Optional[str]
|
|
|
|
if os.environ.get("HOME") is None:
|
|
|
|
return None
|
|
|
|
|
2014-03-03 00:51:33 -05:00
|
|
|
config_file = os.path.join(os.environ["HOME"], ".zuliprc")
|
|
|
|
if (not os.path.exists(config_file) and
|
2016-12-03 12:19:09 -05:00
|
|
|
os.path.exists(os.path.join(os.environ["HOME"], ".humbugrc"))):
|
2016-07-02 13:53:19 -04:00
|
|
|
raise RuntimeError("The Zulip API configuration file is now ~/.zuliprc; please run:\n\n"
|
|
|
|
" mv ~/.humbugrc ~/.zuliprc\n")
|
2014-03-03 00:51:33 -05:00
|
|
|
return config_file
|
|
|
|
|
2012-12-03 12:24:49 -05:00
|
|
|
class Client(object):
|
2012-12-10 14:42:20 -05:00
|
|
|
def __init__(self, email=None, api_key=None, config_file=None,
|
2012-11-26 10:45:11 -05:00
|
|
|
verbose=False, retry_on_errors=True,
|
2015-10-20 14:28:03 -04:00
|
|
|
site=None, client=None,
|
2016-06-14 21:00:59 -04:00
|
|
|
cert_bundle=None, insecure=None,
|
|
|
|
client_cert=None, client_cert_key=None):
|
2016-12-02 21:26:47 -05:00
|
|
|
# type: (Optional[str], Optional[str], Optional[str], bool, bool, Optional[str], Optional[str], Optional[str], bool, Optional[str], Optional[str]) -> None
|
2013-12-06 17:33:09 -05:00
|
|
|
if client is None:
|
|
|
|
client = _default_client()
|
2015-10-20 14:28:03 -04:00
|
|
|
|
2017-08-28 10:01:05 -04:00
|
|
|
# Normalize user-specified path
|
|
|
|
if config_file is not None:
|
|
|
|
config_file = os.path.abspath(os.path.expanduser(config_file))
|
2017-01-26 17:00:29 -05:00
|
|
|
# Fill values from Environment Variables if not available in Constructor
|
|
|
|
if config_file is None:
|
|
|
|
config_file = os.environ.get("ZULIP_CONFIG")
|
|
|
|
if api_key is None:
|
|
|
|
api_key = os.environ.get("ZULIP_API_KEY")
|
|
|
|
if email is None:
|
|
|
|
email = os.environ.get("ZULIP_EMAIL")
|
|
|
|
if site is None:
|
|
|
|
site = os.environ.get("ZULIP_SITE")
|
|
|
|
if client_cert is None:
|
|
|
|
client_cert = os.environ.get("ZULIP_CERT")
|
|
|
|
if client_cert_key is None:
|
|
|
|
client_cert_key = os.environ.get("ZULIP_CERT_KEY")
|
|
|
|
if cert_bundle is None:
|
|
|
|
cert_bundle = os.environ.get("ZULIP_CERT_BUNDLE")
|
|
|
|
|
2015-10-20 14:28:03 -04:00
|
|
|
if config_file is None:
|
|
|
|
config_file = get_default_config_filename()
|
2017-01-26 17:00:29 -05:00
|
|
|
|
2017-05-29 21:19:59 -04:00
|
|
|
if config_file is not None and os.path.exists(config_file):
|
2012-12-10 14:42:20 -05:00
|
|
|
config = SafeConfigParser()
|
2015-10-14 16:31:08 -04:00
|
|
|
with open(config_file, 'r') as f:
|
2012-12-10 14:42:20 -05:00
|
|
|
config.readfp(f, config_file)
|
|
|
|
if api_key is None:
|
|
|
|
api_key = config.get("api", "key")
|
|
|
|
if email is None:
|
|
|
|
email = config.get("api", "email")
|
2013-02-19 14:04:20 -05:00
|
|
|
if site is None and config.has_option("api", "site"):
|
|
|
|
site = config.get("api", "site")
|
2016-06-14 21:00:59 -04:00
|
|
|
if client_cert is None and config.has_option("api", "client_cert"):
|
|
|
|
client_cert = config.get("api", "client_cert")
|
|
|
|
if client_cert_key is None and config.has_option("api", "client_cert_key"):
|
|
|
|
client_cert_key = config.get("api", "client_cert_key")
|
2015-10-20 14:28:03 -04:00
|
|
|
if cert_bundle is None and config.has_option("api", "cert_bundle"):
|
|
|
|
cert_bundle = config.get("api", "cert_bundle")
|
|
|
|
if insecure is None and config.has_option("api", "insecure"):
|
|
|
|
# Be quite strict about what is accepted so that users don't
|
|
|
|
# disable security unintentionally.
|
|
|
|
insecure_setting = config.get("api", "insecure").lower()
|
|
|
|
if insecure_setting == "true":
|
|
|
|
insecure = True
|
|
|
|
elif insecure_setting == "false":
|
|
|
|
insecure = False
|
|
|
|
else:
|
|
|
|
raise RuntimeError("insecure is set to '%s', it must be 'true' or 'false' if it is used in %s"
|
|
|
|
% (insecure_setting, config_file))
|
|
|
|
elif None in (api_key, email):
|
2017-08-28 10:01:05 -04:00
|
|
|
raise RuntimeError("api_key or email not specified and file %s does not exist"
|
2015-10-20 14:28:03 -04:00
|
|
|
% (config_file,))
|
2012-11-26 10:45:11 -05:00
|
|
|
|
2012-10-01 15:36:44 -04:00
|
|
|
self.api_key = api_key
|
|
|
|
self.email = email
|
|
|
|
self.verbose = verbose
|
2013-02-14 13:16:45 -05:00
|
|
|
if site is not None:
|
2016-11-03 20:05:50 -04:00
|
|
|
if site.startswith("localhost"):
|
|
|
|
site = "http://" + site
|
|
|
|
elif not site.startswith("http"):
|
2013-06-17 17:06:28 -04:00
|
|
|
site = "https://" + site
|
2013-11-15 10:44:09 -05:00
|
|
|
# Remove trailing "/"s from site to simplify the below logic for adding "/api"
|
|
|
|
site = site.rstrip("/")
|
2013-02-14 13:16:45 -05:00
|
|
|
self.base_url = site
|
|
|
|
else:
|
2016-12-01 00:20:27 -05:00
|
|
|
raise RuntimeError("Missing Zulip server URL; specify via --site or ~/.zuliprc.")
|
2013-11-15 10:44:09 -05:00
|
|
|
|
2016-10-18 15:12:15 -04:00
|
|
|
if not self.base_url.endswith("/api"):
|
2013-06-24 15:48:32 -04:00
|
|
|
self.base_url += "/api"
|
2013-11-15 10:44:09 -05:00
|
|
|
self.base_url += "/"
|
2012-10-22 14:31:21 -04:00
|
|
|
self.retry_on_errors = retry_on_errors
|
2012-10-23 10:59:42 -04:00
|
|
|
self.client_name = client
|
2012-10-01 15:36:44 -04:00
|
|
|
|
2015-10-20 14:28:03 -04:00
|
|
|
if insecure:
|
2017-05-07 10:39:20 -04:00
|
|
|
self.tls_verification = False # type: Union[bool, str]
|
2015-10-20 14:28:03 -04:00
|
|
|
elif cert_bundle is not None:
|
|
|
|
if not os.path.isfile(cert_bundle):
|
|
|
|
raise RuntimeError("tls bundle '%s' does not exist"
|
2016-11-28 17:29:01 -05:00
|
|
|
% (cert_bundle,))
|
|
|
|
self.tls_verification = cert_bundle
|
2015-10-20 14:28:03 -04:00
|
|
|
else:
|
|
|
|
# Default behavior: verify against system CA certificates
|
2016-11-28 17:29:01 -05:00
|
|
|
self.tls_verification = True
|
2015-10-20 14:28:03 -04:00
|
|
|
|
2016-06-14 21:00:59 -04:00
|
|
|
if client_cert is None:
|
|
|
|
if client_cert_key is not None:
|
|
|
|
raise RuntimeError("client cert key '%s' specified, but no client cert public part provided"
|
2016-11-28 17:29:01 -05:00
|
|
|
% (client_cert_key,))
|
2017-05-07 10:39:20 -04:00
|
|
|
else: # we have a client cert
|
2016-06-14 21:00:59 -04:00
|
|
|
if not os.path.isfile(client_cert):
|
|
|
|
raise RuntimeError("client cert '%s' does not exist"
|
2016-11-28 17:29:01 -05:00
|
|
|
% (client_cert,))
|
2016-06-14 21:00:59 -04:00
|
|
|
if client_cert_key is not None:
|
|
|
|
if not os.path.isfile(client_cert_key):
|
|
|
|
raise RuntimeError("client cert key '%s' does not exist"
|
2016-11-28 17:29:01 -05:00
|
|
|
% (client_cert_key,))
|
2016-06-14 21:00:59 -04:00
|
|
|
self.client_cert = client_cert
|
|
|
|
self.client_cert_key = client_cert_key
|
|
|
|
|
2017-07-18 03:36:07 -04:00
|
|
|
self.session = None # type: Union[None, requests.Session]
|
|
|
|
|
|
|
|
def ensure_session(self):
|
|
|
|
# type: () -> None
|
|
|
|
|
|
|
|
# Check if the session has been created already, and return
|
|
|
|
# immediately if so.
|
|
|
|
if self.session:
|
|
|
|
return
|
|
|
|
|
|
|
|
# Build a client cert object for requests
|
|
|
|
if self.client_cert_key is not None:
|
|
|
|
client_cert = (self.client_cert, self.client_cert_key) # type: Union[str, Tuple[str, str]]
|
|
|
|
else:
|
|
|
|
client_cert = self.client_cert
|
|
|
|
|
|
|
|
# Actually construct the session
|
|
|
|
session = requests.Session()
|
|
|
|
session.auth = requests.auth.HTTPBasicAuth(self.email, self.api_key) # type: ignore # https://github.com/python/typeshed/pull/1504
|
|
|
|
session.verify = self.tls_verification # type: ignore # https://github.com/python/typeshed/pull/1504
|
|
|
|
session.cert = client_cert
|
|
|
|
session.headers = {"User-agent": self.get_user_agent()}
|
|
|
|
self.session = session
|
|
|
|
|
2013-12-06 16:37:01 -05:00
|
|
|
def get_user_agent(self):
|
2016-12-02 21:26:47 -05:00
|
|
|
# type: () -> str
|
2014-05-20 19:47:41 -04:00
|
|
|
vendor = ''
|
|
|
|
vendor_version = ''
|
|
|
|
try:
|
|
|
|
vendor = platform.system()
|
|
|
|
vendor_version = platform.release()
|
|
|
|
except IOError:
|
|
|
|
# If the calling process is handling SIGCHLD, platform.system() can
|
|
|
|
# fail with an IOError. See http://bugs.python.org/issue9127
|
|
|
|
pass
|
2013-12-06 16:37:01 -05:00
|
|
|
|
|
|
|
if vendor == "Linux":
|
|
|
|
vendor, vendor_version, dummy = platform.linux_distribution()
|
|
|
|
elif vendor == "Windows":
|
|
|
|
vendor_version = platform.win32_ver()[1]
|
|
|
|
elif vendor == "Darwin":
|
|
|
|
vendor_version = platform.mac_ver()[0]
|
|
|
|
|
|
|
|
return "{client_name} ({vendor}; {vendor_version})".format(
|
2017-01-24 01:06:13 -05:00
|
|
|
client_name=self.client_name,
|
|
|
|
vendor=vendor,
|
|
|
|
vendor_version=vendor_version,
|
2017-01-24 00:34:26 -05:00
|
|
|
)
|
2013-12-06 16:37:01 -05:00
|
|
|
|
2016-12-28 21:47:22 -05:00
|
|
|
def do_api_query(self, orig_request, url, method="POST", longpolling=False, files=None):
|
|
|
|
# type: (Mapping[str, Any], str, str, bool, List[IO]) -> Dict[str, Any]
|
|
|
|
if files is None:
|
|
|
|
files = []
|
|
|
|
|
2017-10-06 11:00:41 -04:00
|
|
|
if longpolling:
|
|
|
|
# When long-polling, set timeout to 90 sec as a balance
|
|
|
|
# between a low traffic rate and a still reasonable latency
|
|
|
|
# time in case of a connection failure.
|
|
|
|
request_timeout = 90
|
|
|
|
else:
|
|
|
|
# Otherwise, 15s should be plenty of time.
|
|
|
|
request_timeout = 15
|
|
|
|
|
2012-11-29 09:35:30 -05:00
|
|
|
request = {}
|
2016-12-28 21:47:22 -05:00
|
|
|
req_files = []
|
2012-11-07 17:22:19 -05:00
|
|
|
|
2016-03-11 04:57:29 -05:00
|
|
|
for (key, val) in six.iteritems(orig_request):
|
2016-12-26 17:33:36 -05:00
|
|
|
if isinstance(val, str) or isinstance(val, Text):
|
2012-11-29 09:35:30 -05:00
|
|
|
request[key] = val
|
2016-06-27 11:26:13 -04:00
|
|
|
else:
|
2017-09-14 05:18:39 -04:00
|
|
|
request[key] = json.dumps(val)
|
2012-11-07 17:22:19 -05:00
|
|
|
|
2016-12-28 21:47:22 -05:00
|
|
|
for f in files:
|
|
|
|
req_files.append((f.name, f))
|
|
|
|
|
2017-07-18 03:36:07 -04:00
|
|
|
self.ensure_session()
|
|
|
|
|
2012-11-29 09:17:09 -05:00
|
|
|
query_state = {
|
|
|
|
'had_error_retry': False,
|
|
|
|
'request': request,
|
|
|
|
'failures': 0,
|
2017-05-07 10:39:20 -04:00
|
|
|
} # type: Dict[str, Any]
|
2012-11-29 09:17:09 -05:00
|
|
|
|
|
|
|
def error_retry(error_string):
|
2016-12-02 21:26:47 -05:00
|
|
|
# type: (str) -> bool
|
2012-11-29 09:17:09 -05:00
|
|
|
if not self.retry_on_errors or query_state["failures"] >= 10:
|
|
|
|
return False
|
|
|
|
if self.verbose:
|
|
|
|
if not query_state["had_error_retry"]:
|
2016-12-03 12:07:49 -05:00
|
|
|
sys.stdout.write("zulip API(%s): connection error%s -- retrying." %
|
2016-12-11 08:30:45 -05:00
|
|
|
(url.split(API_VERSTRING, 2)[0], error_string,))
|
2012-11-29 09:17:09 -05:00
|
|
|
query_state["had_error_retry"] = True
|
|
|
|
else:
|
|
|
|
sys.stdout.write(".")
|
|
|
|
sys.stdout.flush()
|
2017-09-14 05:18:39 -04:00
|
|
|
query_state["request"]["dont_block"] = json.dumps(True)
|
2012-11-29 09:17:09 -05:00
|
|
|
time.sleep(1)
|
|
|
|
query_state["failures"] += 1
|
|
|
|
return True
|
|
|
|
|
|
|
|
def end_error_retry(succeeded):
|
2016-12-02 21:26:47 -05:00
|
|
|
# type: (bool) -> None
|
2012-11-29 09:17:09 -05:00
|
|
|
if query_state["had_error_retry"] and self.verbose:
|
|
|
|
if succeeded:
|
2015-11-01 11:11:06 -05:00
|
|
|
print("Success!")
|
2012-11-29 09:17:09 -05:00
|
|
|
else:
|
2015-11-01 11:11:06 -05:00
|
|
|
print("Failed!")
|
2012-11-29 09:17:09 -05:00
|
|
|
|
2012-10-04 18:06:54 -04:00
|
|
|
while True:
|
|
|
|
try:
|
2013-03-28 15:47:26 -04:00
|
|
|
if method == "GET":
|
|
|
|
kwarg = "params"
|
|
|
|
else:
|
|
|
|
kwarg = "data"
|
2016-12-28 21:47:22 -05:00
|
|
|
|
2013-03-28 15:47:26 -04:00
|
|
|
kwargs = {kwarg: query_state["request"]}
|
2016-06-14 21:00:59 -04:00
|
|
|
|
2016-12-28 21:47:22 -05:00
|
|
|
if files:
|
|
|
|
kwargs['files'] = req_files
|
|
|
|
|
2017-10-06 11:00:41 -04:00
|
|
|
# Actually make the request!
|
2017-07-18 03:36:07 -04:00
|
|
|
res = self.session.request(
|
2017-01-24 01:06:13 -05:00
|
|
|
method,
|
|
|
|
urllib.parse.urljoin(self.base_url, url),
|
2017-10-06 11:00:41 -04:00
|
|
|
timeout=request_timeout,
|
2017-01-24 01:06:13 -05:00
|
|
|
**kwargs)
|
2012-10-22 14:31:21 -04:00
|
|
|
|
|
|
|
# On 50x errors, try again after a short sleep
|
2012-11-29 09:17:09 -05: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 15:38:34 -05: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
|
2016-12-03 12:19:09 -05:00
|
|
|
str(e) != "The read operation timed out"):
|
2012-11-09 15:38:34 -05:00
|
|
|
raise
|
2012-11-09 14:16:22 -05:00
|
|
|
if longpolling:
|
|
|
|
# When longpolling, we expect the timeout to fire,
|
|
|
|
# and the correct response is to just retry
|
|
|
|
continue
|
|
|
|
else:
|
2012-11-29 09:17:09 -05:00
|
|
|
end_error_retry(False)
|
2012-11-09 14:16:22 -05:00
|
|
|
return {'msg': "Connection error:\n%s" % traceback.format_exc(),
|
|
|
|
"result": "connection-error"}
|
2012-10-04 18:06:54 -04:00
|
|
|
except requests.exceptions.ConnectionError:
|
2012-11-29 09:17:09 -05:00
|
|
|
if error_retry(""):
|
2012-10-22 14:31:21 -04:00
|
|
|
continue
|
2012-11-29 09:17:09 -05:00
|
|
|
end_error_retry(False)
|
2012-10-04 18:06:54 -04:00
|
|
|
return {'msg': "Connection error:\n%s" % traceback.format_exc(),
|
|
|
|
"result": "connection-error"}
|
|
|
|
except Exception:
|
2012-10-22 14:31:21 -04:00
|
|
|
# We'll split this out into more cases as we encounter new bugs.
|
2012-10-04 18:06:54 -04:00
|
|
|
return {'msg': "Unexpected error:\n%s" % traceback.format_exc(),
|
|
|
|
"result": "unexpected-error"}
|
|
|
|
|
2013-07-29 18:02:28 -04:00
|
|
|
try:
|
|
|
|
if requests_json_is_function:
|
|
|
|
json_result = res.json()
|
|
|
|
else:
|
|
|
|
json_result = res.json
|
|
|
|
except Exception:
|
|
|
|
json_result = None
|
|
|
|
|
2013-02-05 15:08:48 -05:00
|
|
|
if json_result is not None:
|
2012-11-29 09:17:09 -05:00
|
|
|
end_error_retry(True)
|
2013-02-05 15:08:48 -05:00
|
|
|
return json_result
|
2012-11-29 09:17:09 -05:00
|
|
|
end_error_retry(False)
|
2013-07-29 18:02:28 -04:00
|
|
|
return {'msg': "Unexpected error from the server", "result": "http-error",
|
2012-10-04 18:06:54 -04:00
|
|
|
"status_code": res.status_code}
|
|
|
|
|
2016-12-28 21:47:22 -05:00
|
|
|
def call_endpoint(self, url=None, method="POST", request=None, longpolling=False, files=None):
|
|
|
|
# type: (str, str, Dict[str, Any], bool, List[IO]) -> Dict[str, Any]
|
2016-12-17 15:19:15 -05:00
|
|
|
if request is None:
|
|
|
|
request = dict()
|
2017-10-06 11:00:41 -04:00
|
|
|
return self.do_api_query(request, API_VERSTRING + url, method=method,
|
|
|
|
longpolling=longpolling, files=files)
|
2012-11-16 14:15:03 -05:00
|
|
|
|
2016-06-02 18:53:09 -04:00
|
|
|
def call_on_each_event(self, callback, event_types=None, narrow=None):
|
2016-12-02 21:26:47 -05:00
|
|
|
# type: (Callable, Optional[List[str]], Any) -> None
|
2016-06-02 18:53:09 -04:00
|
|
|
if narrow is None:
|
|
|
|
narrow = []
|
2017-01-24 00:04:49 -05:00
|
|
|
|
2013-03-21 18:14:13 -04:00
|
|
|
def do_register():
|
2016-12-02 21:26:47 -05:00
|
|
|
# type: () -> Tuple[str, int]
|
2013-03-22 17:44:58 -04:00
|
|
|
while True:
|
|
|
|
if event_types is None:
|
2017-02-18 20:01:01 -05:00
|
|
|
res = self.register()
|
2013-03-22 17:44:58 -04:00
|
|
|
else:
|
2017-02-18 20:01:01 -05:00
|
|
|
res = self.register(event_types=event_types, narrow=narrow)
|
2013-03-22 17:44:58 -04:00
|
|
|
|
|
|
|
if 'error' in res.get('result'):
|
|
|
|
if self.verbose:
|
2015-11-01 11:11:06 -05:00
|
|
|
print("Server returned error:\n%s" % res['msg'])
|
2013-03-22 17:44:58 -04:00
|
|
|
time.sleep(1)
|
|
|
|
else:
|
|
|
|
return (res['queue_id'], res['last_event_id'])
|
2013-03-21 18:14:13 -04:00
|
|
|
|
|
|
|
queue_id = None
|
2017-10-06 11:05:12 -04:00
|
|
|
# Make long-polling requests with `get_events`. Once a request
|
|
|
|
# has received an answer, pass it to the callback and before
|
|
|
|
# making a new long-polling request.
|
2012-10-01 15:36:44 -04:00
|
|
|
while True:
|
2013-03-21 18:14:13 -04:00
|
|
|
if queue_id is None:
|
|
|
|
(queue_id, last_event_id) = do_register()
|
|
|
|
|
2017-02-18 20:01:01 -05:00
|
|
|
res = self.get_events(queue_id=queue_id, last_event_id=last_event_id)
|
2012-10-04 16:13:47 -04:00
|
|
|
if 'error' in res.get('result'):
|
2013-02-12 13:59:28 -05:00
|
|
|
if res["result"] == "http-error":
|
|
|
|
if self.verbose:
|
2015-11-01 11:11:06 -05:00
|
|
|
print("HTTP error fetching events -- probably a server restart")
|
2013-02-12 13:59:28 -05:00
|
|
|
elif res["result"] == "connection-error":
|
|
|
|
if self.verbose:
|
2015-11-01 11:11:06 -05:00
|
|
|
print("Connection error fetching events -- probably server is temporarily down?")
|
2013-02-12 13:59:28 -05:00
|
|
|
else:
|
|
|
|
if self.verbose:
|
2015-11-01 11:11:06 -05:00
|
|
|
print("Server returned error:\n%s" % res["msg"])
|
2013-03-21 18:14:13 -04:00
|
|
|
if res["msg"].startswith("Bad event queue id:"):
|
|
|
|
# Our event queue went away, probably because
|
|
|
|
# we were asleep or the server restarted
|
|
|
|
# abnormally. We may have missed some
|
2013-03-22 17:44:58 -04:00
|
|
|
# events while the network was down or
|
2013-03-21 18:14:13 -04:00
|
|
|
# something, but there's not really anything
|
|
|
|
# we can do about it other than resuming
|
|
|
|
# getting new ones.
|
2013-02-12 13:59:28 -05:00
|
|
|
#
|
2013-03-21 18:14:13 -04:00
|
|
|
# Reset queue_id to register a new event queue.
|
|
|
|
queue_id = None
|
2017-10-06 11:05:12 -04:00
|
|
|
# Add a pause here to cover against potential bugs in this library
|
|
|
|
# causing a DoS attack against a server when getting errors.
|
|
|
|
# TODO: Make this back off exponentially.
|
2012-10-01 15:36:44 -04:00
|
|
|
time.sleep(1)
|
2012-10-02 15:47:59 -04:00
|
|
|
continue
|
2013-03-21 18:14:13 -04:00
|
|
|
|
|
|
|
for event in res['events']:
|
|
|
|
last_event_id = max(last_event_id, int(event['id']))
|
2013-03-22 17:44:58 -04:00
|
|
|
callback(event)
|
|
|
|
|
|
|
|
def call_on_each_message(self, callback):
|
2016-12-02 21:26:47 -05:00
|
|
|
# type: (Callable) -> None
|
2013-03-22 17:44:58 -04:00
|
|
|
def event_callback(event):
|
2016-12-02 21:26:47 -05:00
|
|
|
# type: (Dict[str, str]) -> None
|
2013-03-22 17:44:58 -04:00
|
|
|
if event['type'] == 'message':
|
|
|
|
callback(event['message'])
|
|
|
|
self.call_on_each_event(event_callback, ['message'])
|
2012-11-07 15:48:37 -05:00
|
|
|
|
2016-12-17 15:19:15 -05:00
|
|
|
def send_message(self, message_data):
|
|
|
|
# type: (Dict[str, Any]) -> Dict[str, Any]
|
|
|
|
'''
|
2017-09-12 12:08:35 -04:00
|
|
|
See examples/send-message for example usage.
|
2016-12-17 15:19:15 -05:00
|
|
|
'''
|
|
|
|
return self.call_endpoint(
|
|
|
|
url='messages',
|
|
|
|
request=message_data,
|
|
|
|
)
|
|
|
|
|
2016-12-28 21:47:22 -05:00
|
|
|
def upload_file(self, file):
|
|
|
|
# type: (IO) -> Dict[str, Any]
|
|
|
|
'''
|
2017-09-12 12:08:35 -04:00
|
|
|
See examples/upload-file for example usage.
|
2016-12-28 21:47:22 -05:00
|
|
|
'''
|
|
|
|
return self.call_endpoint(
|
|
|
|
url='user_uploads',
|
|
|
|
files=[file]
|
|
|
|
)
|
|
|
|
|
2016-12-17 15:19:15 -05:00
|
|
|
def update_message(self, message_data):
|
|
|
|
# type: (Dict[str, Any]) -> Dict[str, Any]
|
|
|
|
'''
|
2017-09-12 12:08:35 -04:00
|
|
|
See examples/edit-message for example usage.
|
2016-12-17 15:19:15 -05:00
|
|
|
'''
|
|
|
|
return self.call_endpoint(
|
2017-01-25 11:36:20 -05:00
|
|
|
url='messages/%d' % (message_data['message_id'],),
|
2016-12-17 15:19:15 -05:00
|
|
|
method='PATCH',
|
|
|
|
request=message_data,
|
|
|
|
)
|
|
|
|
|
|
|
|
def get_events(self, **request):
|
|
|
|
# type: (**Any) -> Dict[str, Any]
|
|
|
|
'''
|
|
|
|
See the register() method for example usage.
|
|
|
|
'''
|
|
|
|
return self.call_endpoint(
|
|
|
|
url='events',
|
|
|
|
method='GET',
|
|
|
|
longpolling=True,
|
|
|
|
request=request,
|
|
|
|
)
|
|
|
|
|
|
|
|
def register(self, event_types=None, narrow=None, **kwargs):
|
|
|
|
# type: (Iterable[str], Any, **Any) -> Dict[str, Any]
|
|
|
|
'''
|
|
|
|
Example usage:
|
|
|
|
|
|
|
|
>>> client.register(['message'])
|
|
|
|
{u'msg': u'', u'max_message_id': 112, u'last_event_id': -1, u'result': u'success', u'queue_id': u'1482093786:2'}
|
|
|
|
>>> client.get_events(queue_id='1482093786:2', last_event_id=0)
|
|
|
|
{...}
|
|
|
|
'''
|
2013-11-19 17:51:06 -05:00
|
|
|
|
2016-12-17 15:19:15 -05:00
|
|
|
if narrow is None:
|
|
|
|
narrow = []
|
2013-03-22 17:44:58 -04:00
|
|
|
|
2017-08-22 19:33:10 -04:00
|
|
|
if event_types is None:
|
|
|
|
event_types = []
|
|
|
|
|
2016-12-17 15:19:15 -05:00
|
|
|
request = dict(
|
|
|
|
event_types=event_types,
|
|
|
|
narrow=narrow,
|
|
|
|
**kwargs
|
|
|
|
)
|
|
|
|
|
|
|
|
return self.call_endpoint(
|
|
|
|
url='register',
|
|
|
|
request=request,
|
|
|
|
)
|
|
|
|
|
|
|
|
def deregister(self, queue_id):
|
|
|
|
# type: (str) -> Dict[str, Any]
|
|
|
|
'''
|
|
|
|
Example usage:
|
|
|
|
|
|
|
|
>>> client.register(['message'])
|
|
|
|
{u'msg': u'', u'max_message_id': 113, u'last_event_id': -1, u'result': u'success', u'queue_id': u'1482093786:3'}
|
|
|
|
>>> client.deregister('1482093786:3')
|
|
|
|
{u'msg': u'', u'result': u'success'}
|
|
|
|
'''
|
|
|
|
request = dict(queue_id=queue_id)
|
|
|
|
|
|
|
|
return self.call_endpoint(
|
|
|
|
url="events",
|
|
|
|
method="DELETE",
|
|
|
|
request=request,
|
|
|
|
)
|
|
|
|
|
|
|
|
def get_profile(self, request=None):
|
|
|
|
# type: (Dict[str, Any]) -> Dict[str, Any]
|
|
|
|
'''
|
|
|
|
Example usage:
|
|
|
|
|
|
|
|
>>> client.get_profile()
|
|
|
|
{u'user_id': 5, u'full_name': u'Iago', u'short_name': u'iago', ...}
|
|
|
|
'''
|
|
|
|
return self.call_endpoint(
|
|
|
|
url='users/me',
|
|
|
|
method='GET',
|
|
|
|
request=request,
|
|
|
|
)
|
|
|
|
|
2017-02-11 02:46:38 -05:00
|
|
|
def get_presence(self, email):
|
|
|
|
# type: (Dict[str, Any]) -> Dict[str, Any]
|
|
|
|
'''
|
|
|
|
Example usage:
|
|
|
|
|
|
|
|
>>> client.get_presence()
|
|
|
|
{'presence': {'website': {'timestamp': 1486799122, 'status': 'active'}}, 'result': 'success', 'msg': ''}
|
|
|
|
'''
|
|
|
|
return self.call_endpoint(
|
|
|
|
url='users/%s/presence' % (email,),
|
|
|
|
method='GET',
|
|
|
|
)
|
|
|
|
|
2016-12-17 15:19:15 -05:00
|
|
|
def get_streams(self, **request):
|
|
|
|
# type: (**Any) -> Dict[str, Any]
|
|
|
|
'''
|
2017-09-12 12:08:35 -04:00
|
|
|
See examples/get-public-streams for example usage.
|
2016-12-17 15:19:15 -05:00
|
|
|
'''
|
|
|
|
return self.call_endpoint(
|
|
|
|
url='streams',
|
|
|
|
method='GET',
|
|
|
|
request=request,
|
|
|
|
)
|
|
|
|
|
|
|
|
def get_members(self, request=None):
|
|
|
|
# type: (Dict[str, Any]) -> Dict[str, Any]
|
|
|
|
'''
|
2017-09-12 12:08:35 -04:00
|
|
|
See examples/list-members for example usage.
|
2016-12-17 15:19:15 -05:00
|
|
|
'''
|
|
|
|
return self.call_endpoint(
|
|
|
|
url='users',
|
|
|
|
method='GET',
|
|
|
|
request=request,
|
|
|
|
)
|
|
|
|
|
|
|
|
def list_subscriptions(self, request=None):
|
|
|
|
# type: (Dict[str, Any]) -> Dict[str, Any]
|
|
|
|
'''
|
2017-09-12 12:08:35 -04:00
|
|
|
See examples/list-subscriptions for example usage.
|
2016-12-17 15:19:15 -05:00
|
|
|
'''
|
|
|
|
return self.call_endpoint(
|
|
|
|
url='users/me/subscriptions',
|
|
|
|
method='GET',
|
|
|
|
request=request,
|
|
|
|
)
|
|
|
|
|
|
|
|
def add_subscriptions(self, streams, **kwargs):
|
|
|
|
# type: (Iterable[Dict[str, Any]], **Any) -> Dict[str, Any]
|
|
|
|
'''
|
2017-09-12 12:08:35 -04:00
|
|
|
See examples/subscribe for example usage.
|
2016-12-17 15:19:15 -05:00
|
|
|
'''
|
|
|
|
request = dict(
|
|
|
|
subscriptions=streams,
|
|
|
|
**kwargs
|
|
|
|
)
|
|
|
|
|
|
|
|
return self.call_endpoint(
|
|
|
|
url='users/me/subscriptions',
|
|
|
|
request=request,
|
|
|
|
)
|
|
|
|
|
|
|
|
def remove_subscriptions(self, streams):
|
|
|
|
# type: (Iterable[str]) -> Dict[str, Any]
|
|
|
|
'''
|
2017-09-12 12:08:35 -04:00
|
|
|
See examples/unsubscribe for example usage.
|
2016-12-17 15:19:15 -05:00
|
|
|
'''
|
|
|
|
request = dict(delete=streams)
|
|
|
|
return self.call_endpoint(
|
|
|
|
url='users/me/subscriptions',
|
|
|
|
method='PATCH',
|
|
|
|
request=request,
|
|
|
|
)
|
|
|
|
|
2016-12-30 05:42:59 -05:00
|
|
|
def get_stream_id(self, stream):
|
|
|
|
# type: (str) -> Dict[str, Any]
|
|
|
|
'''
|
|
|
|
Example usage: client.get_stream_id('devel')
|
|
|
|
'''
|
|
|
|
stream_encoded = urllib.parse.quote(stream, safe='')
|
|
|
|
url = 'get_stream_id?stream=%s' % (stream_encoded,)
|
|
|
|
return self.call_endpoint(
|
|
|
|
url=url,
|
|
|
|
method='GET',
|
|
|
|
request=None,
|
|
|
|
)
|
|
|
|
|
2016-12-17 15:19:15 -05:00
|
|
|
def get_subscribers(self, **request):
|
|
|
|
# type: (**Any) -> Dict[str, Any]
|
|
|
|
'''
|
|
|
|
Example usage: client.get_subscribers(stream='devel')
|
|
|
|
'''
|
2017-01-13 06:49:06 -05:00
|
|
|
response = self.get_stream_id(request['stream'])
|
|
|
|
if response['result'] == 'error':
|
|
|
|
return response
|
|
|
|
|
|
|
|
stream_id = response['stream_id']
|
2016-12-30 05:42:59 -05:00
|
|
|
url = 'streams/%d/members' % (stream_id,)
|
2016-12-17 15:19:15 -05:00
|
|
|
return self.call_endpoint(
|
|
|
|
url=url,
|
|
|
|
method='GET',
|
|
|
|
request=request,
|
|
|
|
)
|
|
|
|
|
|
|
|
def render_message(self, request=None):
|
|
|
|
# type: (Dict[str, Any]) -> Dict[str, Any]
|
|
|
|
'''
|
|
|
|
Example usage:
|
|
|
|
|
|
|
|
>>> client.render_message(request=dict(content='foo **bar**'))
|
|
|
|
{u'msg': u'', u'rendered': u'<p>foo <strong>bar</strong></p>', u'result': u'success'}
|
|
|
|
'''
|
|
|
|
return self.call_endpoint(
|
|
|
|
url='messages/render',
|
2017-01-12 19:10:19 -05:00
|
|
|
method='POST',
|
2016-12-17 15:19:15 -05:00
|
|
|
request=request,
|
|
|
|
)
|
|
|
|
|
|
|
|
def create_user(self, request=None):
|
|
|
|
# type: (Dict[str, Any]) -> Dict[str, Any]
|
|
|
|
'''
|
2017-09-12 12:08:35 -04:00
|
|
|
See examples/create-user for example usage.
|
2016-12-17 15:19:15 -05:00
|
|
|
'''
|
|
|
|
return self.call_endpoint(
|
2016-12-31 02:07:22 -05:00
|
|
|
method='POST',
|
2016-12-17 15:19:15 -05:00
|
|
|
url='users',
|
|
|
|
request=request,
|
|
|
|
)
|
2013-08-22 11:37:02 -04:00
|
|
|
|
2013-10-30 15:56:43 -04:00
|
|
|
class ZulipStream(object):
|
|
|
|
"""
|
|
|
|
A Zulip stream-like object
|
|
|
|
"""
|
|
|
|
|
|
|
|
def __init__(self, type, to, subject, **kwargs):
|
2016-12-02 21:26:47 -05:00
|
|
|
# type: (str, str, str, **Any) -> None
|
2013-10-30 15:56:43 -04:00
|
|
|
self.client = Client(**kwargs)
|
|
|
|
self.type = type
|
|
|
|
self.to = to
|
|
|
|
self.subject = subject
|
|
|
|
|
|
|
|
def write(self, content):
|
2016-12-02 21:26:47 -05:00
|
|
|
# type: (str) -> None
|
2013-10-30 15:56:43 -04:00
|
|
|
message = {"type": self.type,
|
|
|
|
"to": self.to,
|
|
|
|
"subject": self.subject,
|
|
|
|
"content": content}
|
2017-02-18 20:01:01 -05:00
|
|
|
self.client.send_message(message)
|
2013-10-30 15:56:43 -04:00
|
|
|
|
|
|
|
def flush(self):
|
2016-12-02 21:26:47 -05:00
|
|
|
# type: () -> None
|
2013-10-30 15:56:43 -04:00
|
|
|
pass
|