- implement AddressType and Address manipulation
[plcapi.git] / PLC / Methods / AddAddress.py
1 from PLC.Faults import *
2 from PLC.Method import Method
3 from PLC.Parameter import Parameter, Mixed
4 from PLC.Addresses import Address, Addresses
5 from PLC.Auth import PasswordAuth
6 from PLC.Sites import Site, Sites
7
8 class AddAddress(Method):
9     """
10     Adds a new address to a site. Fields specified in
11     address_fields are used; some are not optional.
12
13     PIs may only add addresses to their own sites.
14
15     Returns the new address_id (> 0) if successful, faults otherwise.
16     """
17
18     roles = ['admin', 'pi']
19
20     can_update = lambda (field, value): field in \
21                  ['line1', 'line2', 'line3',
22                   'city', 'state', 'postalcode', 'country']
23     update_fields = dict(filter(can_update, Address.fields.items()))
24
25     accepts = [
26         PasswordAuth(),
27         Mixed(Site.fields['site_id'],
28               Site.fields['login_base']),
29         update_fields
30         ]
31
32     returns = Parameter(int, 'New address_id (> 0) if successful')
33
34     def call(self, auth, site_id_or_login_base, address_fields = {}):
35         if filter(lambda field: field not in self.update_fields, address_fields):
36             raise PLCInvalidArgument, "Invalid field specified"
37
38         # Get associated site details
39         sites = Sites(self.api, [site_id_or_login_base]).values()
40         if not sites:
41             raise PLCInvalidArgument, "No such site"
42         site = sites[0]
43
44         if 'admin' not in self.caller['roles']:
45             if site['site_id'] not in self.caller['site_ids']:
46                 raise PLCPermissionDenied, "Address must be associated with one of your sites"
47
48         address = Address(self.api, address_fields)
49         address['site_id'] = site['site_id']
50         address.sync()
51
52         return address['address_id']