allow filters to be specified in most Get() calls
[plcapi.git] / PLC / Methods / GetPCUs.py
1 from PLC.Faults import *
2 from PLC.Method import Method
3 from PLC.Parameter import Parameter, Mixed
4 from PLC.Filter import Filter
5 from PLC.PCUs import PCU, PCUs
6 from PLC.Auth import Auth
7
8 class GetPCUs(Method):
9     """
10     Returns an array of structs containing details about power control
11     units (PCUs). If pcu_filter is specified and is an array of PCU
12     identifiers, or a struct of PCU attributes, only PCUs matching the
13     filter will be returned.
14
15     Admin may query all PCUs. Non-admins may only query the PCUs at
16     their sites.
17     """
18
19     roles = ['admin', 'pi', 'tech']
20
21     accepts = [
22         Auth(),
23         Mixed([PCU.fields['pcu_id']],
24               Filter(PCU.fields))
25         ]
26
27     returns = [PCU.fields]
28
29     def call(self, auth, pcu_filter = None):
30         # If we are not admin, make sure to only return our own PCUs
31         if 'admin' not in self.caller['roles']:
32             # Get list of PCUs that we are able to view
33             valid_pcu_ids = []
34             if self.caller['site_ids']:
35                 sites = Sites(self.api, self.caller['site_ids']).values()
36                 for site in sites:
37                     valid_pcu_ids += site['pcu_ids']
38
39             if not valid_pcu_ids:
40                 return []
41
42             if pcu_filter is None:
43                 pcu_filter = valid_pcu_ids
44
45         pcus = PCUs(self.api, pcu_filter).values()
46
47         # Filter out PCUs that are not viewable
48         if 'admin' not in self.caller['roles']:
49             pcus = filter(lambda pcu: pcu['pcu_id'] in valid_pcu_ids, pcus)
50
51         return pcus