forked from neomilium/ovh-redirections
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathovh-redirections
executable file
·219 lines (185 loc) · 6.83 KB
/
ovh-redirections
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
'''
First, install the latest release of Python wrapper: $ pip install ovh
'''
import sys
import os.path
import shutil
import ovh
import yaml
import json
config_file = '~/.config/ovh-redirections.yaml'
domain_db_suffix = '_ovh-redirections.yaml'
def help():
print('Usage: {} <command>\n\nCommands:'.format(sys.argv[0]))
for f in sorted(globals().keys()):
if not f.startswith('_') and callable(globals()[f]):
print(' {}'.format(f))
sys.exit(1)
try:
f_config = open(os.path.expanduser(config_file), 'r')
except:
print('No config file found {}\n'.format(config_file))
config = { 'example.com': { 'endpoint': 'ovh-eu', 'application_key': 'YourApplicationKey', 'application_secret': 'YourApplicationSecret', 'consumer_key': 'YourConsumerKey' } }
print('Configuration sample:\n')
print(yaml.dump(config, indent=4, default_flow_style=False))
sys.exit(1)
configs = yaml.load(f_config)
if len(configs.keys()) == 1:
domain = list(configs.keys())[0]
print('Using "{}" domain configuration…'.format(domain))
config = configs[domain]
client = ovh.Client(
endpoint=config['endpoint'],
application_key=config['application_key'],
application_secret=config['application_secret'],
consumer_key=config['consumer_key'],
)
else:
print('Multi-domain support are not yet implemented…')
sys.exit(1)
remote_db = '.{}{}'.format(domain, domain_db_suffix)
local_db = '{}{}'.format(domain, domain_db_suffix)
url_base = '/email/domain/{}/redirection'.format(domain)
def _group_redirections(redirections):
# Build a dict
redirections_dict = {}
for r in redirections:
r_from = r['from']
if r_from not in redirections_dict:
redirections_dict[r_from] = []
r.pop('from')
redirections_dict[r_from].append(r)
return redirections_dict
def fetch():
redirections_id_list = client.get(url_base)
print('{} redirections found, fetching details…'.format(len(redirections_id_list)))
redirections = []
for r_id in redirections_id_list:
redirection = client.get(url_base + '/{}'.format(r_id))
redirections.append(redirection)
redirections_dict = _group_redirections(redirections)
with open(remote_db, 'w') as f_r:
yaml.dump(redirections_dict, f_r, indent=2, default_flow_style=False)
print('Redirections written to "{}"'.format(remote_db))
# Try to update local IDs if the local database exists
if os.path.isfile(local_db):
_update_local_ids()
def _update_local_ids():
f_l = _open_local_db()
# Local redirections
l_redirections_dict = yaml.load(f_l)
l_redirections = _flat_redirections(l_redirections_dict)
# Remote redirections
f_r = open(remote_db, 'r')
r_redirections = _flat_redirections(yaml.load(f_r))
# Compute differences between local and remote redirections
r_l = set(r_redirections) - set(l_redirections)
l_r = set(l_redirections) - set(r_redirections)
for a in r_l:
for b in l_r:
if a[1] == b[1] and a[2] == b[2]:
for r in l_redirections_dict[a[1]]:
if r['to'] == a[2]:
r['id'] = a[0]
break
f_l = _open_local_db('w')
yaml.dump(l_redirections_dict, f_l, indent=2, default_flow_style=False)
def checkout():
shutil.copyfile(remote_db, local_db)
def _open_local_db(flag='r'):
try:
f = open(local_db, flag)
except Exception as e:
print(str(e))
print("Maybe you missed to run '{} checkout' before ?".format(sys.argv[0]))
sys.exit(1)
return f
def list():
f = _open_local_db()
r_redirections = yaml.load(f)
_print_redirections(r_redirections)
def _print_redirections(redirections):
# Print redirections (grouped)
for r_from in sorted(redirections.keys()):
if redirections[r_from]:
print(r_from)
for redirection in redirections[r_from]:
print(' %s (%s)' % (redirection['to'], redirection['id']))
print()
def _print_flat_redirections(redirections, fmt='{}'):
for r in redirections:
if r[0]:
out = '{} -> {} ({})'.format(r[1], r[2], r[0])
else:
out = '{} -> {}'.format(r[1], r[2])
print(fmt.format(out))
def _flat_redirections(redirections):
flat_redirections = []
for r_from in sorted(redirections.keys()):
if redirections[r_from]:
for redirection in redirections[r_from]:
try:
r_id = redirection['id']
except:
r_id = None
flat_redirections.append( (r_id, r_from, redirection['to']) )
return flat_redirections
def diff():
f_l = _open_local_db()
l_redirections = _flat_redirections(yaml.load(f_l))
f_r = open(remote_db, 'r')
r_redirections = _flat_redirections(yaml.load(f_r))
removed = set(r_redirections) - set(l_redirections)
added = set(l_redirections) - set(r_redirections)
if(len(removed) or len(added)):
if len(removed):
print()
_print_flat_redirections(removed, fmt='\t\033[91mdeleted: \t{}\033[00m')
if(len(added)):
print()
_print_flat_redirections(added, fmt='\t\033[92madded: \t\t{}\033[00m')
else:
print('No changes.')
def _add_redirection(r_from, r_to):
print('Adding redirection: {} -> {}'.format(r_from, r_to), end='')
try:
result = client.post(url_base,
_from=r_from, # Required: Name of redirection (type: string)
localCopy=False, # Required: If true keep a local copy (type: boolean)
to=r_to, # Required: Target of account (type: string)
)
#print(json.dumps(result, indent=4))
print('\t\033[92m{}\033[00m'.format('OK'))
return result['id']
except Exception as e:
print(' \t\033[91m{}\033[00m'.format('ERR: '+str(e)))
return None
def _del_redirection(r_id):
print('Deleting redirection: {}'.format(r_id), end='')
try:
result = client.delete(url_base+'/{}'.format(r_id))
#print(json.dumps(result, indent=4))
print('\t\033[92m{}\033[00m'.format('OK'))
except Exception as e:
print(' \t\033[91m{}\033[00m'.format('ERR: '+str(e)))
def commit():
f_l = _open_local_db()
l_redirections = _flat_redirections(yaml.load(f_l))
f_r = open(remote_db, 'r')
r_redirections = _flat_redirections(yaml.load(f_r))
deleted = set(r_redirections) - set(l_redirections)
added = set(l_redirections) - set(r_redirections)
for r in deleted:
_del_redirection(r[0])
for r in added:
_add_redirection(r[1], r[2])
fetch()
if len(sys.argv) == 1:
help()
else:
if sys.argv[1] in locals():
locals()[sys.argv[1]]()
else:
help()