1
|
|
|
from plugin.api.core.base import Service, expose |
2
|
|
|
from plugin.managers.client import ClientManager |
3
|
|
|
from plugin.managers.client_rule import ClientRuleManager |
4
|
|
|
|
5
|
|
|
import logging |
6
|
|
|
|
7
|
|
|
log = logging.getLogger(__name__) |
8
|
|
|
|
9
|
|
|
|
10
|
|
|
class ClientService(Service): |
11
|
|
|
__key__ = 'session.client' |
12
|
|
|
|
13
|
|
|
@expose |
14
|
|
|
def list(self, full=False): |
|
|
|
|
15
|
|
|
return [ |
16
|
|
|
client.to_json(full=full) |
17
|
|
|
for client in ClientManager.get.all() |
18
|
|
|
] |
19
|
|
|
|
20
|
|
|
|
21
|
|
View Code Duplication |
class ClientRuleService(Service): |
|
|
|
|
22
|
|
|
__key__ = 'session.client.rule' |
23
|
|
|
|
24
|
|
|
@expose |
25
|
|
|
def list(self, full=False): |
|
|
|
|
26
|
|
|
return [ |
27
|
|
|
rule.to_json(full=full) |
28
|
|
|
for rule in ClientRuleManager.get.all() |
29
|
|
|
] |
30
|
|
|
|
31
|
|
|
@expose |
32
|
|
|
def update(self, current, full=False): |
|
|
|
|
33
|
|
|
result = [] |
34
|
|
|
|
35
|
|
|
# Build array of current ids |
36
|
|
|
current_ids = [ |
37
|
|
|
r.get('id') |
38
|
|
|
for r in current |
39
|
|
|
if r.get('id') is not None |
40
|
|
|
] |
41
|
|
|
|
42
|
|
|
# Delete rules |
43
|
|
|
deleted_rules = [ |
44
|
|
|
rule |
45
|
|
|
for rule in ClientRuleManager.get.all() |
46
|
|
|
if rule.id not in current_ids |
47
|
|
|
] |
48
|
|
|
|
49
|
|
|
for rule in deleted_rules: |
50
|
|
|
rule.delete_instance() |
51
|
|
|
|
52
|
|
|
log.debug('Deleted %r', rule) |
53
|
|
|
|
54
|
|
|
# Create/Update client rules |
55
|
|
|
for r in current: |
56
|
|
|
id = r.pop('id', None) |
|
|
|
|
57
|
|
|
|
58
|
|
|
if id is None: |
59
|
|
|
# Create new rule |
60
|
|
|
rule = ClientRuleManager.create(**r) |
61
|
|
|
|
62
|
|
|
log.debug('Created %r', rule) |
63
|
|
|
result.append(rule) |
64
|
|
|
continue |
65
|
|
|
|
66
|
|
|
# Retrieve existing rule |
67
|
|
|
rule = ClientRuleManager.get(id=id) |
68
|
|
|
|
69
|
|
|
# Update rule |
70
|
|
|
ClientRuleManager.update(rule, r) |
71
|
|
|
|
72
|
|
|
log.debug('Updated %r', rule) |
73
|
|
|
result.append(rule) |
74
|
|
|
|
75
|
|
|
# Ensure result is sorted by priority |
76
|
|
|
result = sorted(result, key=lambda item: item.priority) |
77
|
|
|
|
78
|
|
|
# Convert rules to serializable dictionaries |
79
|
|
|
return [ |
80
|
|
|
r.to_json(full=full) |
81
|
|
|
for r in result |
82
|
|
|
] |
83
|
|
|
|
If a method does not access any attributes of the class, it could also be implemented as a function or static method. This can help improve readability. For example
could be written as