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 commands as s_commands
14
15
16class CommandsClient(common_client.CommonClient):
17    """Client library for commands method."""
18
19    def __init__(self, *args, **kwargs):
20        common_client.CommonClient.__init__(
21                self, s_commands.COMMANDS_PATH, *args, **kwargs)
22
23
24    def get_command(self, command_id):
25        """Returns info about the given command using |command_id|.
26
27        @param command_id: valid id for a command.
28        """
29        request = urllib2.Request(self.get_url([command_id]),
30                                  headers=self.add_auth_headers())
31        url_h = urllib2.urlopen(request)
32        return json.loads(url_h.read())
33
34
35    def list_commands(self, device_id):
36        """Returns the list of commands for the given |device_id|.
37
38        @param command_id: valid id for a command.
39        """
40        request = urllib2.Request(self.get_url(params={'deviceId':device_id}),
41                                  headers=self.add_auth_headers())
42        url_h = urllib2.urlopen(request)
43        return json.loads(url_h.read())
44
45
46    def update_command(self, command_id, data, replace=False):
47        """Updates the command with |data|.
48
49        @param command_id: id of the command to update.
50        @param data: data to update command with.
51        @param replace: If True, replace all data with the given data using the
52                PUT operation.
53        """
54        if not data:
55            return
56
57        headers = self.add_auth_headers({'Content-Type': 'application/json'})
58        request = urllib2.Request(self.get_url([command_id]), json.dumps(data),
59                                  headers=headers)
60        if replace:
61            request.get_method = lambda: 'PUT'
62        else:
63            request.get_method = lambda: 'PATCH'
64
65        url_h = urllib2.urlopen(request)
66        return json.loads(url_h.read())
67
68
69    def create_command(self, device_id, data):
70        """Creates a new command.
71
72        @device_id: ID of device to send command to.
73        @param data: command.
74        """
75        headers = self.add_auth_headers({'Content-Type': 'application/json'})
76        data['deviceId'] = device_id
77        request = urllib2.Request(self.get_url(),
78                                  json.dumps(data),
79                                  headers=headers)
80        url_h = urllib2.urlopen(request)
81        return json.loads(url_h.read())
82