1# Copyright 2014 The Chromium OS Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5"""Module contains a simple client lib to the commands RPC."""
6
7import logging
8import urllib2
9
10
11class CommonClient(object):
12    """Common client class."""
13
14    _DEFAULT_SERVER_URL = 'http://localhost:9876'
15    _URL = '%(server_url)s/%(method)s'
16
17
18    def __init__(self, method, server_url=_DEFAULT_SERVER_URL, api_key=None,
19                 access_token=None,):
20        """
21        @param method: REST method to call e.g. my_method/call
22        @param server_url: Base url for the server e.g. http://localhost:8080
23        @param api_key: API key to use with remote server.
24        @param access_token: Access token to use to interact with server.
25        """
26        self._method = method
27        self.server_url = server_url
28        self.api_key = api_key
29        self.access_token = access_token
30
31
32    def add_auth_headers(self, additional_headers=None):
33        """Returns combined auth headers with any additional headers.
34
35        @param additional_headers: Additional headers to use.
36        """
37        if not self.access_token:
38            return additional_headers if additional_headers else {}
39        else:
40            headers = {'Authorization': self.access_token}
41            if additional_headers:
42                headers.update(additional_headers)
43
44            return headers
45
46
47    def get_url(self, paths=[], params={}):
48        """Returns url to use to talk to the server method.
49
50        @param paths: Parts of a path to append to base url.
51        @param params: Dictionary of url parameters.
52        """
53        if not self._method:
54            raise NotImplementedError('method not defined.')
55
56        # Create the method string.
57        paths_str = ''
58        if paths:
59            paths_str = '/' + '/'.join([str(p) for p in paths])
60
61        # Create the query string.
62        params_str = ''
63        if not params:
64            params = {}
65
66        if self.api_key:
67            params.setdefault('key', self.api_key)
68
69        params_list = []
70        for kw, arg in params.iteritems():
71            params_list.append('='.join([urllib2.quote(kw),
72                                         urllib2.quote(arg)]))
73
74        if params_list:
75            params_str = '?' + '&'.join(params_list)
76
77        url = self._URL % dict(
78                server_url=self.server_url,
79                method=self._method) + paths_str + params_str
80
81        logging.info("Returning url: %s to use.", url)
82        return url
83