registration.py revision feedba871f9ea080e3562f7d9875f09e63468c55
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 registration RPC."""
6
7import json
8import logging
9import urllib2
10
11import common
12from fake_device_server.client_lib import common_client
13from fake_device_server import registration_tickets
14
15
16class RegistrationClient(common_client.CommonClient):
17    """Client library for registrationTickets method."""
18
19    def __init__(self, *args, **kwargs):
20        common_client.CommonClient.__init__(
21                self, registration_tickets.REGISTRATION_PATH, *args, **kwargs)
22
23
24    def get_registration_ticket(self, ticket_id):
25        """Returns info about the given |ticket_id|.
26
27        @param ticket_id: valid id for a ticket.
28        """
29        url_h = urllib2.urlopen(self.get_url([ticket_id]))
30        return json.loads(url_h.read())
31
32
33    def update_registration_ticket(self, ticket_id, data,
34                                   additional_headers=None, replace=False):
35        """Updates the given registration ticket with the new data.
36
37        @param ticket_id: id of the ticket to update.
38        @param data: data to update.
39        @param additional_headers: additional HTTP headers to pass (expects a
40                list of tuples).
41        @param replace: If True, replace all data with the given data using the
42                PUT operation.
43        """
44        if not data:
45            return
46
47        headers = {'Content-Type': 'application/json'}
48        if additional_headers:
49            headers.update(additional_headers)
50
51        request = urllib2.Request(self.get_url([ticket_id]), json.dumps(data),
52                                  headers=headers)
53        if replace:
54            request.get_method = lambda: 'PUT'
55        else:
56            request.get_method = lambda: 'PATCH'
57
58        url_h = urllib2.urlopen(request)
59        return json.loads(url_h.read())
60
61
62    def create_registration_ticket(self, initial_data=None):
63        """Creates a new registration ticket.
64
65        @param initial_data: optional dictionary of data to pass for ticket.
66        """
67        data = initial_data or {}
68        request = urllib2.Request(self.get_url(), json.dumps(data),
69                                  {'Content-Type': 'application/json'})
70        url_h = urllib2.urlopen(request)
71        return json.loads(url_h.read())
72
73
74    def finalize_registration_ticket(self, ticket_id):
75        """Finalizes a registration ticket by creating a new device.
76
77        @param ticket_id: id of ticket to finalize.
78        """
79        request = urllib2.Request(self.get_url([ticket_id, 'finalize']),
80                                  data='')
81        url_h = urllib2.urlopen(request)
82        return json.loads(url_h.read())
83
84
85    def register_device(self, system_name, device_kind, channel,
86                        oauth_client_id, **kwargs):
87        """Goes through the entire registration process using the device args.
88
89        @param system_name: name to give the system.
90        @param device_kind: type of device.
91        @param channel: supported communication channel.
92        @param oauth_client_id: see oauth docs.
93        @param kwargs: additional dictionary of args to put in config.
94        """
95        ticket = self.create_registration_ticket()
96        logging.info('Initial Ticket: %s', ticket)
97        ticket_id = ticket['id']
98
99        device_draft = dict(systemName=system_name,
100                            deviceKind=device_kind,
101                            channel=dict(supportedType=channel),
102                            **kwargs)
103        headers = self.add_auth_headers()
104        if not headers:
105            # Insert test auth.
106            headers = [
107                    ['Authorization',
108                    'Bearer ' +
109                    registration_tickets.RegistrationTickets.TEST_ACCESS_TOKEN
110                    ]]
111
112        ticket = self.update_registration_ticket(
113                ticket_id,
114                {'deviceDraft': device_draft,
115                 'userEmail': 'me',
116                 'oauthClientId': oauth_client_id},
117                additional_headers=headers)
118
119        logging.info('Updated Ticket After Claiming: %s', ticket)
120        return self.finalize_registration_ticket(ticket_id)
121