use propper json now and decode values

This commit is contained in:
Robin van Genderen 2019-03-04 14:48:42 +01:00
parent e76ae88edc
commit d64ca716e9

View File

@ -1,9 +1,11 @@
#!/usr/bin/env python #!/usr/bin/env python3
import subprocess import subprocess
from configobj import ConfigObj from configobj import ConfigObj
import uuid import uuid
from MAPI.Util import * from MAPI.Util import *
import kopano import kopano
# Try simplejson if json is not available # Try simplejson if json is not available
try: try:
import json import json
@ -12,120 +14,123 @@ except ImportError:
def encode(value): def encode(value):
proc = subprocess.Popen(["php", "deencode.php", "encode", value], stdout=subprocess.PIPE) output = subprocess.check_output(["php", "deencode.php", "encode", value])
return proc.communicate()[0] return output.strip()
def opt_args(): def opt_args():
parser = kopano.parser('skpcfmUP') parser = kopano.parser('skpcfm')
parser.add_option("--user", dest="user", action="store", help="username") parser.add_option("--user", dest="user", action="store", help="username")
parser.add_option("--ssl", dest="ssl", action="store_true", help="Use localhost on port 443")
parser.add_option("--hostname", dest="hostname", action="store", help="hostname")
parser.add_option("--file", dest="file", default=[], action="store", help="config file(s) separate by ',' ") parser.add_option("--file", dest="file", default=[], action="store", help="config file(s) separate by ',' ")
parser.add_option("--overwrite", dest="overwrite", action="store_true", help="overwrite files settings")
parser.add_option("--default", dest="default", action="store_true", parser.add_option("--default", dest="default", action="store_true",
help="use default user and password in the configfile") help="use default user and password in the configfile")
return parser.parse_args() return parser.parse_args()
def read_settings(options): def read_settings(user):
try: try:
user = kopano.Server(options).user(options.user) mapisettings = user.store.prop(PR_EC_WEBACCESS_SETTINGS_JSON).value.decode('utf-8')
except MAPIErrorLogonFailed as e: settings = json.loads(mapisettings)
print('User \'{}\' not found ({})'.format(options.user, e)) except Exception as e:
sys.exit(1)
if not user.store:
print('User \'{}\' has no user store ({})'.format(options.user, e))
sys.exit(1)
try:
mapisettings = user.store.prop(PR_EC_WEBACCESS_SETTINGS_JSON).value
return mapisettings
except Exception:
print('{}: Has no or no valid WebApp settings creating empty config tree'.format(user.name)) print('{}: Has no or no valid WebApp settings creating empty config tree'.format(user.name))
return '{"settings": {"zarafa": {"v1": {"contexts": {"mail": {}}}}}}' settings = json.loads('{"settings": {"zarafa": {"v1": {"contexts": {"mail": {}}}}}}')
return settings
def write_settings(data, options): def write_settings(user, setting):
user = kopano.Server(options).user(options.user) try:
user.store.create_prop(PR_EC_WEBACCESS_SETTINGS_JSON, data.encode('utf-8')) user.store.create_prop(PR_EC_WEBACCESS_SETTINGS_JSON, setting.encode('utf-8'))
print('Writing settings for user \'{}\''.format(user.fullname)) except Exception as e:
print('{}: Error Writing WebApp settings for user: {}'.format(e, user.name))
def files(options): def files(options):
filesjson = '{' filesjson = {'accounts': {}}
if options.overwrite:
filesjson = '{"accounts": {'
num = 0
files = options.file.split(',') files = options.file.split(',')
for file in files: for file in files:
configfile = ConfigObj(file) configfile = ConfigObj(file)
if options.default: if configfile['setting']['use_zarafa_credentials']:
username = configfile['setting']['default_user'] username = configfile['setting']['default_user']
else: else:
username = options.user username = options.user
if num != 0: password = encode(configfile['setting']['default_password'])
filesjson += ',' backendoptions = {
id = uuid.uuid4() 'ftp': {"backend_features": {
filesjson += ''' "Streaming": "true", }},
"%s": { 'webdav': {"backend_features": {
"Quota": "true",
"VersionInfo": "true"}},
'owncloud': {"backend_features": {
"Quota": "true",
"Sharing": "true",
"VersionInfo": "true"}},
'smb': {"backend_features": {
"Quota": "true",
"Streaming": "true",
"VersionInfo": "true"}},
}
if file == 'seafile.cfg':
password = encode(options.user)
username = kopano.Server(options).user(options.user).email
if 'local' in file:
if options.ssl:
port = '443'
address = options.hostname
ssl = 'true'
else:
port = configfile['setting']['server_port']
address = configfile['setting']['server_address']
ssl = configfile['setting']['server_ssl']
else:
port = configfile['setting']['server_port']
address = configfile['setting']['server_address']
ssl = configfile['setting']['server_ssl']
id = str(uuid.uuid4())
filesjson['accounts'][id] = {
"status": "ok", "status": "ok",
"backend_config": { "backend_config": {
"server_path": "%s", "server_path": encode(configfile['setting']['server_path']).decode('utf-8'),
"workgroup": "%s", "workgroup": encode(configfile['setting']['workgroup']).decode('utf-8'),
"server_address": "%s", "server_address": encode(address).decode('utf-8'),
"server_ssl": %s, "server_ssl": ssl,
"current_account_id": "%s", "current_account_id": encode('d4cacda458a2a26c301f2b7d75ada530').decode('utf-8'),
"use_zarafa_credentials": %s, "use_zarafa_credentials": configfile['setting']['use_zarafa_credentials'],
"user": "%s", "user": encode(username).decode('utf-8'),
"password": "%s", "password": password.decode('utf-8'),
"server_port": "%s" "server_port": encode(port).decode('utf-8')
}, },
"cannot_change": false, "cannot_change": False,
"name": "%s", "name": configfile['setting']['name'],
"status_description": "Account is ready to use.", "status_description": "Account is ready to use.",
"id": "%s", "id": id,
"backend_features": { "backend_features": backendoptions[configfile['setting']['type'].lower()]['backend_features'],
"Sharing": true, "backend": configfile['setting']['type']
"VersionInfo": true, }
"Quota": true
}, if configfile['setting']['type'].lower() == 'ftp':
"backend": "%s" filesjson['accounts'][id]['backend_config']['server_pasv'] = configfile['setting']['server_pasv']
}''' % (id, encode(configfile['setting']['server_path']), encode(configfile['setting']['workgroup']),
encode(configfile['setting']['server_address']), configfile['setting']['server_ssl'],
encode('d4cacda458a2a26c301f2b7d75ada530'), configfile['setting']['use_zarafa_credentials'],
encode(username), encode(configfile['setting']['default_password']),
encode(configfile['setting']['server_port']), configfile['setting']['name'], id, configfile['setting']['type'])
num += 1
if options.overwrite:
filesjson += '}}'
else:
filesjson += '}'
return filesjson return filesjson
def main(): def main():
options, args = opt_args() options, args = opt_args()
data = read_settings(options) server = kopano.Server(options)
webappsettings = json.loads(data) user = server.user(options.user)
webappsettings = read_settings(user)
if not webappsettings['settings']['zarafa']['v1'].get('plugins'): if not webappsettings['settings']['zarafa']['v1'].get('plugins'):
webappsettings['settings']['zarafa']['v1']['plugins'] = {} webappsettings['settings']['zarafa']['v1']['plugins'] = {}
webappsettings['settings']['zarafa']['v1']['plugins']['files'] = files(options)
if options.overwrite: write_settings(user, json.dumps(webappsettings))
webappsettings['settings']['zarafa']['v1']['plugins']['files'] = json.loads(files(options))
else:
if not webappsettings['settings']['zarafa']['v1']['plugins'].get('files'):
webappsettings['settings']['zarafa']['v1']['plugins']['files'] = {}
if not webappsettings['settings']['zarafa']['v1']['plugins']['files'].get('accounts'):
webappsettings['settings']['zarafa']['v1']['plugins']['files']['accounts'] = {}
webappsettings['settings']['zarafa']['v1']['plugins']['files']['accounts'].update(json.loads(files(options)))
write_settings(json.dumps(webappsettings), options)
if __name__ == '__main__': if __name__ == '__main__':
main() main()