Changed preferences to use JSON for v3

pull/91/head
Luc Charland 2015-04-28 11:02:43 -04:00 committed by Francis Lachapelle
parent f49610f058
commit 243726f096
4 changed files with 173 additions and 149 deletions

View File

@ -7,6 +7,9 @@ import simplejson
import sogoLogin import sogoLogin
DEBUG=False
#DEBUG=True
# must be kept in sync with SoObjects/SOGo/SOGoDefaults.plist # must be kept in sync with SoObjects/SOGo/SOGoDefaults.plist
# this should probably be fetched magically... # this should probably be fetched magically...
@ -18,122 +21,128 @@ SOGoSupportedLanguages = [ "Arabic", "Basque", "Catalan", "Czech", "Dutch", "Dan
daysBetweenResponseList=[1,2,3,5,7,14,21,30] daysBetweenResponseList=[1,2,3,5,7,14,21,30]
class HTTPPreferencesPOST (webdavlib.HTTPPOST): class HTTPPreferencesPOST (webdavlib.HTTPPOST):
cookie = None cookie = None
def prepare_headers (self): def prepare_headers (self):
headers = webdavlib.HTTPPOST.prepare_headers(self) headers = webdavlib.HTTPPOST.prepare_headers(self)
if self.cookie: if self.cookie:
headers["Cookie"] = self.cookie headers["Cookie"] = self.cookie
return headers return headers
class HTTPPreferencesGET (webdavlib.HTTPGET): class HTTPPreferencesGET (webdavlib.HTTPGET):
cookie = None cookie = None
def prepare_headers (self): def prepare_headers (self):
headers = webdavlib.HTTPGET.prepare_headers(self) headers = webdavlib.HTTPGET.prepare_headers(self)
if self.cookie: if self.cookie:
headers["Cookie"] = self.cookie headers["Cookie"] = self.cookie
return headers return headers
class preferences: class preferences:
login = username login = username
passw = password passw = password
def __init__(self, otherLogin = None, otherPassword = None): def __init__(self, otherLogin = None, otherPassword = None):
if otherLogin and otherPassword: if otherLogin and otherPassword:
self.login = otherLogin self.login = otherLogin
self.passw = otherPassword self.passw = otherPassword
self.client = webdavlib.WebDAVClient(hostname, port) self.client = webdavlib.WebDAVClient(hostname, port)
authCookie = sogoLogin.getAuthCookie(hostname, port, self.login, self.passw) authCookie = sogoLogin.getAuthCookie(hostname, port, self.login, self.passw)
self.cookie = authCookie self.cookie = authCookie
# map between preferences/jsonDefaults and the webUI names #- If this is not set, we CAN'T save preferences
# should probably be unified... self.preferences = None
self.preferencesMap = {
"SOGoLanguage": "language",
"SOGoTimeZone": "timezone",
"SOGoSieveFilters": "sieveFilters",
# Vacation stuff def find_key(self, d, key):
"Vacation": "enableVacation", # to disable, don't specify it if key in d:
"autoReplyText": "autoReplyText", # string return d
"autoReplyEmailAddresses": "autoReplyEmailAddresses", # LIST subdicts = [a[1] for a in d.iteritems() if type(a[1]) == dict]
"daysBetweenResponse": "daysBetweenResponsesList", for subd in subdicts:
"ignoreLists": "ignoreLists", #bool ret = self.find_key(subd, key)
if ret:
return ret
return None
# forward stuff def load_preferences(self):
"Forward": "enableForward", # to disable, don't specify it defaults = self.get_defaults()
"forwardAddress": "forwardAddress", settings = self.get_settings()
"keepCopy": "forwardKeepCopy", self.preferences = {'defaults': defaults, 'settings': settings}
#print "LOAD PREFS:", self.preferences
# Calendar stuff def get(self, preference=None):
"enablePreventInvitations": "preventInvitations", if not self.preferences:
"PreventInvitations": "PreventInvitations", self.load_preferences()
"whiteList": "whiteList", #- Want the whole thing
} if not preference:
return self.preferences
else:
tmpdict = self.find_key(self.preferences, preference)
return tmpdict[preference]
def _get(self, subtype='jsonDefault', preference=None):
url = "/SOGo/so/%s/%s" % (self.login, subtype)
get = HTTPPreferencesGET(url)
get.cookie = self.cookie
self.client.execute(get)
if DEBUG: print "LUC (url):", url
if DEBUG: print "LUC (status):", get.response["status"]
if DEBUG: print "LUC (body):", get.response['body']
content = simplejson.loads(get.response['body'])
result = None
try:
if preference:
result = content[preference]
else:
result = content
except:
pass
return result
def set(self, preference, value=None): def get_defaults(self, preference=None):
# if preference is a dict, set all prefs found in the dict return self._get('jsonDefaults', preference)
content=""
if isinstance(preference, dict):
for k,v in preference.items():
content+="%s=%s&" % (self.preferencesMap[k], urllib.quote(v))
else:
# assume it is a str
formKey = self.preferencesMap[preference]
content = "%s=%s&hasChanged=1" % (formKey, urllib.quote(value))
def get_settings(self, preference=None):
return self._get('jsonSettings', preference)
url = "/SOGo/so/%s/preferences" % self.login def set_nosave(self, preference, value=None):
# First check if we did a get, if not, must get first
if not self.preferences:
self.load_preferences()
post = HTTPPreferencesPOST (url, content) # Get the right sub-dict and change the key/value
post.content_type = "application/x-www-form-urlencoded" subdict = self.find_key(self.preferences, preference)
post.cookie = self.cookie if not subdict:
print "LUC(nosubdict):", preference, self.preferences
subdict[preference] = value
self.client.execute (post) def set(self, preference, value=None):
self.set_nosave(preference, value)
self.save()
# Raise an exception if the pref wasn't properly set def set_multiple(self, preferences={}):
if post.response["status"] != 200: for key, value in preferences.iteritems():
raise Exception ("failure setting prefs, (code = %d)" \ self.set_nosave(key, value)
self.save()
def save(self):
url = "/SOGo/so/%s/Preferences/save" % self.login
post = HTTPPreferencesPOST(url, simplejson.dumps(self.preferences))
post.content_type = "application/json"
post.cookie = self.cookie
self.client.execute(post)
# Raise an exception if the pref wasn't properly set
if post.response["status"] != 200:
raise Exception ("failure setting prefs, (code = %d)" \
% post.response["status"]) % post.response["status"])
def get(self, preference=None):
url = "/SOGo/so/%s/preferences/jsonDefaults" % self.login
get = HTTPPreferencesGET (url)
get.cookie = self.cookie
self.client.execute (get)
content = simplejson.loads(get.response['body'])
result = None
try:
if preference:
result = content[preference]
else:
result = content
except:
pass
return result
def get_settings(self, preference=None):
url = "/SOGo/so/%s/preferences/jsonSettings" % self.login
get = HTTPPreferencesGET (url)
get.cookie = self.cookie
self.client.execute (get)
content = simplejson.loads(get.response['body'])
result = None
try:
if preference:
result = content[preference]
else:
result = content
except:
pass
return result
# Simple main to test this class # Simple main to test this class
if __name__ == "__main__": if __name__ == "__main__":
p = preferences () p = preferences ()
print p.get ("SOGoLanguage") print p.get ("SOGoLanguage")
p.set ("SOGoLanguage", SOGoSupportedLanguages.index("French")) p.set ("SOGoLanguage", SOGoSupportedLanguages.index("French"))
print p.get ("SOGoLanguage") print p.get ("SOGoLanguage")

View File

@ -9,6 +9,12 @@ import utilities
class preferencesTest(unittest.TestCase): class preferencesTest(unittest.TestCase):
def setUp(self):
self.prefs = preferences.preferences()
def tearDown(self):
self.prefs.set("autoReplyText", "")
def _setTextPref(self, prefText = None ): def _setTextPref(self, prefText = None ):
""" set a text preference to a known value """ """ set a text preference to a known value """
self.prefs.set("autoReplyText", prefText) self.prefs.set("autoReplyText", prefText)
@ -19,15 +25,8 @@ class preferencesTest(unittest.TestCase):
self.assertEqual(prefData["autoReplyText"], prefText, self.assertEqual(prefData["autoReplyText"], prefText,
"%s != %s" % (prefData["autoReplyText"], prefText)) "%s != %s" % (prefData["autoReplyText"], prefText))
def setUp(self):
self.prefs = preferences.preferences()
def tearDown(self):
self.prefs.set("autoReplyText", "")
def testSetTextPreferences(self): def testSetTextPreferences(self):
""" Set/get a text preference - normal characters""" """ Set/get a text preference - normal characters"""
self._setTextPref("defaultText") self._setTextPref("defaultText")
def testSetTextPreferencesWeirdChars(self): def testSetTextPreferencesWeirdChars(self):
@ -37,17 +36,17 @@ class preferencesTest(unittest.TestCase):
def testSetPreventInvitation(self): def testSetPreventInvitation(self):
""" Set/get the PreventInvitation pref""" """ Set/get the PreventInvitation pref"""
self.prefs.set('PreventInvitations', '0') self.prefs.set('PreventInvitations', 0)
notset = self.prefs.get_settings('')['Calendar']['PreventInvitations'] notset = self.prefs.get('Calendar')['PreventInvitations']
self.assertEqual(notset, 0) self.assertEqual(notset, 0)
self.prefs.set('enablePreventInvitations', '0') self.prefs.set('PreventInvitations', 1)
isset = self.prefs.get_settings('')['Calendar']['PreventInvitations'] isset = self.prefs.get('Calendar')['PreventInvitations']
self.assertEqual(isset, 1) self.assertEqual(isset, 1)
def testPreventInvitationsWhiteList(self): def testPreventInvitationsWhiteList(self):
"""Add to the PreventInvitations Whitelist""" """Add to the PreventInvitations Whitelist"""
self.prefs.set("whiteList", simplejson.dumps(white_listed_attendee)) self.prefs.set("PreventInvitationsWhitelist", white_listed_attendee)
whitelist = self.prefs.get_settings('Calendar')['PreventInvitationsWhitelist'] whitelist = self.prefs.get('Calendar')['PreventInvitationsWhitelist']
self.assertEqual(whitelist, white_listed_attendee) self.assertEqual(whitelist, white_listed_attendee)

View File

@ -26,18 +26,26 @@ class preventInvitationsTest(unittest.TestCase):
def setUp(self): def setUp(self):
self.prefs = preferences.preferences(attendee1, attendee1_password) self.prefs = preferences.preferences(attendee1, attendee1_password)
self.caldav = CalDAVSchedulingTest(self) self.caldav = CalDAVSchedulingTest(self)
cal = self.prefs.get("Calendar")
if "PreventInvitationsWhitelist" not in cal:
#print "LUC (cal):", cal
cal["PreventInvitationsWhitelist"] = None
self.prefs.set("PreventInvitationsWhitelist", None)
def tearDown(self): def tearDown(self):
self.prefs.set("autoReplyText", "") self.prefs.set("autoReplyText", "")
self.prefs.set('PreventInvitations', '0') self.prefs.set('PreventInvitations', 0)
self.prefs.set("whiteList", "") self.prefs.set("PreventInvitationsWhitelist", None)
#- Manual Cleanup, not called because classs is not derived from unittest #- Manual Cleanup, not called because classs is not derived from unittest
self.caldav.tearDown() self.caldav.tearDown()
def not_test_empty_string_instead_of_null(self):
self.prefs.set('PreventInvitationsWhitelist', "")
def testDontPreventInvitation(self): def testDontPreventInvitation(self):
""" Set/get the PreventInvitation pref""" """ Set/get the PreventInvitation pref"""
#- First accept the invitation #- First accept the invitation
self.prefs.set('PreventInvitations', '0') self.prefs.set('PreventInvitations', 0)
notset = self.prefs.get_settings('')['Calendar']['PreventInvitations'] notset = self.prefs.get_settings('')['Calendar']['PreventInvitations']
self.assertEqual(notset, 0) self.assertEqual(notset, 0)
self.caldav.AddAttendee() self.caldav.AddAttendee()
@ -46,7 +54,7 @@ class preventInvitationsTest(unittest.TestCase):
def testPreventInvitation(self): def testPreventInvitation(self):
""" Set PreventInvitation and don't accept the Invitation""" """ Set PreventInvitation and don't accept the Invitation"""
#- Second, enable PreventInviation and refuse it #- Second, enable PreventInviation and refuse it
self.prefs.set('enablePreventInvitations', '0') self.prefs.set('PreventInvitations', 1)
isset = self.prefs.get_settings('')['Calendar']['PreventInvitations'] isset = self.prefs.get_settings('')['Calendar']['PreventInvitations']
self.assertEqual(isset, 1) self.assertEqual(isset, 1)
self.caldav.AddAttendee(409) self.caldav.AddAttendee(409)
@ -55,13 +63,13 @@ class preventInvitationsTest(unittest.TestCase):
def testPreventInvitationWhiteList(self): def testPreventInvitationWhiteList(self):
""" Set PreventInvitation add to WhiteList and accept the Invitation""" """ Set PreventInvitation add to WhiteList and accept the Invitation"""
#- First, add the Organiser to the Attendee's whitelist #- First, add the Organiser to the Attendee's whitelist
self.prefs.set('enablePreventInvitations', '0') self.prefs.set('PreventInvitations', 1)
self.prefs.set("whiteList", simplejson.dumps(white_listed_attendee)) self.prefs.set("PreventInvitationsWhitelist", simplejson.dumps(white_listed_attendee))
whitelist = self.prefs.get_settings('Calendar')['PreventInvitationsWhitelist'] whitelist = self.prefs.get_settings('Calendar')['PreventInvitationsWhitelist']
self.assertEqual(whitelist, white_listed_attendee) self.assertEqual(whitelist, white_listed_attendee)
#- Second, try again to invite, it should work #- Second, try again to invite, it should work
self.prefs.set('enablePreventInvitations', '0') self.prefs.set('PreventInvitations', 1)
isset = self.prefs.get_settings('')['Calendar']['PreventInvitations'] isset = self.prefs.get_settings('')['Calendar']['PreventInvitations']
self.assertEqual(isset, 1) self.assertEqual(isset, 1)
self.caldav.AddAttendee() self.caldav.AddAttendee()

74
Tests/Integration/test-sieve.py 100644 → 100755
View File

@ -16,17 +16,14 @@ sieve_simple_filter="""require ["fileinto"];\r\nif anyof (header :contains "subj
class sieveTest(unittest.TestCase): class sieveTest(unittest.TestCase):
def _killFilters(self): def _killFilters(self):
filtersKill={}
# kill existing filters
filtersKill["SOGoSieveFilters"]= "[]"
# vacation filters
filtersKill["autoReplyText"] = ""
filtersKill["autoReplyEmailAddresses"] = ""
# forwarding filters
filtersKill["forwardAddress"] = ""
self.prefs=preferences.preferences() self.prefs=preferences.preferences()
self.prefs.set(filtersKill) # kill existing filters
self.prefs.set("SOGoSieveFilters", [{}])
# vacation filters
self.prefs.set("autoReplyText", "")
self.prefs.set("autoReplyEmailAddresses", "")
# forwarding filters
self.prefs.set("forwardAddress", "")
def setUp(self): def setUp(self):
ret = "" ret = ""
@ -73,13 +70,16 @@ class sieveTest(unittest.TestCase):
"days": preferences.daysBetweenResponseList[daysSelect], "days": preferences.daysBetweenResponseList[daysSelect],
} }
filterAdd = {"Vacation":"1", # Enabling Vacation now is an 'enabled' setting in the subdict Vacation
"autoReplyText": vacation_msg, # We need to get that subdict first -- next save/set will also save this
"daysBetweenResponse": "%d" % daysSelect, vacation = self.prefs.get("Vacation")
"autoReplyEmailAddresses": self.user_email, vacation['enabled'] = 1
}
self.prefs.set_nosave("autoReplyText", vacation_msg)
self.prefs.set_nosave("daysBetweenResponse", "%d" % daysSelect)
self.prefs.set_nosave("autoReplyEmailAddresses", self.user_email)
self.prefs.save()
self.prefs.set(filterAdd)
createdSieveScript=self._getSogoSieveScript() createdSieveScript=self._getSogoSieveScript()
self.assertEqual(sieveScript, createdSieveScript) self.assertEqual(sieveScript, createdSieveScript)
@ -94,14 +94,17 @@ class sieveTest(unittest.TestCase):
"days": preferences.daysBetweenResponseList[daysSelect], "days": preferences.daysBetweenResponseList[daysSelect],
} }
filterAdd = {"Vacation":"1", # Enabling Vacation now is an 'enabled' setting in the subdict Vacation
"autoReplyText": vacation_msg, # We need to get that subdict first -- next save/set will also save this
"daysBetweenResponse": "%d" % daysSelect, vacation = self.prefs.get("Vacation")
"autoReplyEmailAddresses": self.user_email, vacation['enabled'] = 1
"ignoreLists": "1",
} self.prefs.set_nosave("autoReplyText", vacation_msg)
self.prefs.set_nosave("daysBetweenResponse", "%d" % daysSelect)
self.prefs.set_nosave("autoReplyEmailAddresses", self.user_email)
self.prefs.set_nosave("ignoreLists", 1)
self.prefs.save()
self.prefs.set(filterAdd)
createdSieveScript=self._getSogoSieveScript() createdSieveScript=self._getSogoSieveScript()
self.assertEqual(sieveScript, createdSieveScript) self.assertEqual(sieveScript, createdSieveScript)
@ -112,11 +115,13 @@ class sieveTest(unittest.TestCase):
sieveScript = sieve_simple_forward % { "redirect_mailaddr": redirect_mailaddr } sieveScript = sieve_simple_forward % { "redirect_mailaddr": redirect_mailaddr }
filterAdd = { "Forward": "1", # Enabling Forward now is an 'enabled' setting in the subdict Forward
"forwardAddress": redirect_mailaddr, # We need to get that subdict first -- next save/set will also save this
} forward = self.prefs.get("Forward")
forward['enabled'] = 1
self.prefs.set("forwardAddress", redirect_mailaddr)
self.prefs.set(filterAdd)
createdSieveScript = self._getSogoSieveScript() createdSieveScript = self._getSogoSieveScript()
self.assertEqual(sieveScript, createdSieveScript) self.assertEqual(sieveScript, createdSieveScript)
@ -126,12 +131,15 @@ class sieveTest(unittest.TestCase):
sieveScript = sieve_forward_keep % { "redirect_mailaddr": redirect_mailaddr } sieveScript = sieve_forward_keep % { "redirect_mailaddr": redirect_mailaddr }
filterAdd = { "Forward": "1", # Enabling Forward now is an 'enabled' setting in the subdict Forward
"forwardAddress": redirect_mailaddr, # We need to get that subdict first -- next save/set will also save this
"keepCopy": "1", forward = self.prefs.get("Forward")
} forward['enabled'] = 1
self.prefs.set_nosave("forwardAddress", redirect_mailaddr)
self.prefs.set_nosave("keepCopy", 1)
self.prefs.save()
self.prefs.set(filterAdd)
createdSieveScript = self._getSogoSieveScript() createdSieveScript = self._getSogoSieveScript()
self.assertEqual(sieveScript, createdSieveScript) self.assertEqual(sieveScript, createdSieveScript)
@ -145,7 +153,7 @@ class sieveTest(unittest.TestCase):
filterAdd = { "SOGoSieveFilters": """[{"active": true, "actions": [{"method": "fileinto", "argument": "Sent"}], "rules": [{"operator": "contains", "field": "subject", "value": "%s"}], "match": "any", "name": "%s"}]""" % (subject, folderName) filterAdd = { "SOGoSieveFilters": """[{"active": true, "actions": [{"method": "fileinto", "argument": "Sent"}], "rules": [{"operator": "contains", "field": "subject", "value": "%s"}], "match": "any", "name": "%s"}]""" % (subject, folderName)
} }
self.prefs.set(filterAdd) self.prefs.set_multiple(filterAdd)
createdSieveScript = self._getSogoSieveScript() createdSieveScript = self._getSogoSieveScript()
self.assertEqual(sieveScript, createdSieveScript) self.assertEqual(sieveScript, createdSieveScript)