blind 2to3
[plcapi.git] / PLC / Methods / AddSiteTag.py
1 #
2 # Thierry Parmentelat - INRIA
3 #
4 from PLC.Faults import *
5 from PLC.Method import Method
6 from PLC.Parameter import Parameter, Mixed
7 from PLC.Auth import Auth
8
9 from PLC.Sites import Site, Sites
10 from PLC.Nodes import Nodes
11 from PLC.TagTypes import TagType, TagTypes
12 from PLC.SiteTags import SiteTag, SiteTags
13
14 # need to import so the core classes get decorated with caller_may_write_tag
15 from PLC.AuthorizeHelpers import AuthorizeHelpers
16
17 class AddSiteTag(Method):
18     """
19     Sets the specified setting for the specified site
20     to the specified value.
21
22     Admins have full access.  Non-admins need to 
23     (1) have at least one of the roles attached to the tagtype, 
24     and (2) belong in the same site as the tagged subject.
25
26     Returns the new site_tag_id (> 0) if successful, faults
27     otherwise.
28     """
29
30     roles = ['admin', 'pi', 'tech', 'user']
31
32     accepts = [
33         Auth(),
34         # no other way to refer to a site
35         SiteTag.fields['site_id'],
36         Mixed(TagType.fields['tag_type_id'],
37               TagType.fields['tagname']),
38         SiteTag.fields['value'],
39         ]
40
41     returns = Parameter(int, 'New site_tag_id (> 0) if successful')
42
43     def call(self, auth, site_id, tag_type_id_or_name, value):
44         sites = Sites(self.api, [site_id])
45         if not sites:
46             raise PLCInvalidArgument("No such site %r"%site_id)
47         site = sites[0]
48
49         tag_types = TagTypes(self.api, [tag_type_id_or_name])
50         if not tag_types:
51             raise PLCInvalidArgument("No such tag type %r"%tag_type_id_or_name)
52         tag_type = tag_types[0]
53
54         # checks for existence - does not allow several different settings
55         conflicts = SiteTags(self.api,
56                              {'site_id':site['site_id'],
57                               'tag_type_id':tag_type['tag_type_id']})
58
59         if len(conflicts) :
60             raise PLCInvalidArgument("Site %d already has setting %d"%(site['site_id'],
61                                                                         tag_type['tag_type_id']))
62
63         # check authorizations
64         site.caller_may_write_tag(self.api,self.caller,tag_type)
65             
66         site_tag = SiteTag(self.api)
67         site_tag['site_id'] = site['site_id']
68         site_tag['tag_type_id'] = tag_type['tag_type_id']
69         site_tag['value'] = value
70
71         site_tag.sync()
72         self.object_ids = [site_tag['site_tag_id']]
73
74         return site_tag['site_tag_id']