Commit dfddf562 authored by Nicolas Delaby's avatar Nicolas Delaby

Parse Coordinates only when asText is called

raw input is available with getData.
Backward compatibility is supported.
parent 64874edb
No related merge requests found
......@@ -66,16 +66,39 @@ class GeographicAddress(Coordinate, Base):
)
def _splitCoordinateText(self, coordinate_text):
"""return street_address, zip_code, city tuple parsed from string
"""
line_list = coordinate_text.splitlines()
street_address = zip_code = city = ''
zip_city = None
if len(line_list) > 1:
street_address = ''.join(line_list[0:-1])
zip_city = line_list[-1].split()
elif len(line_list):
street_address = ''
zip_city = line_list[-1].split()
if zip_city:
zip_code = zip_city[0]
if len(zip_city) > 1:
city = ''.join(zip_city[1:])
return street_address, zip_code, city
security.declareProtected(Permissions.AccessContentsInformation, 'asText')
def asText(self):
"""
Returns the address as a complete formatted string
with street address, zip, city and region
with street address, zip, and city
"""
result = Coordinate.asText(self)
if result is None:
result = ('%s\n%s %s') % (self.getStreetAddress() or '',
self.getCity() or '', self.getZipCode() or '')
if self.hasData():
street_address, city, zip_code = self._splitCoordinateText(self.getData(''))
else:
street_address = self.getStreetAddress('')
city = self.getCity('')
zip_code = self.getZipCode('')
result = '%s\n%s %s' % (street_address, city, zip_code,)
if not result.strip():
return ''
return result
......@@ -83,29 +106,14 @@ class GeographicAddress(Coordinate, Base):
security.declareProtected(Permissions.ModifyPortalContent, 'fromText')
@deprecated
def fromText(self, coordinate_text):
"""Save given data then continue parsing
(deprecated because computed values are stored)
"""
Tries to recognize the coordinate_text to update
this address
XXX fromText will be removed.
Instead, store text value as user filled in text attribute,
then display text value through a configurable output filter, suitable
for all addresses patterns.
"""
lines = string.split(coordinate_text, '\n')
self.setStreetAddress('')
self.setZipCode('')
self.setCity('')
zip_city = None
if len(lines ) > 1:
self.setStreetAddress(lines[0:-1])
zip_city = string.split(lines[-1])
elif len(lines ) > 0:
self.setStreetAddress('')
zip_city = string.split(lines[-1])
if zip_city:
self.setZipCode(zip_city[0])
if len(zip_city) > 1:
self.setCity(string.join(zip_city[1:]))
self._setData(coordinate_text)
street_address, city, zip_code = self._splitCoordinateText(coordinate_text)
self.setStreetAddress(street_address)
self.setZipCode(zip_code)
self.setCity(city)
security.declareProtected(Permissions.AccessContentsInformation,
'standardTextFormat')
......
......@@ -56,6 +56,16 @@ class InternetProtocolAddress(Base, Coordinate):
, PropertySheet.InternetProtocolAddress
)
def _splitCoordinateText(self, coordinate_text):
property_id_list = [i['id'] for i in PropertySheet.InternetProtocolAddress._properties]
kw_dict = {}
for line in coordinate_text.split('\n'):
if not ':' in line:
continue
name, value = line.split(':', 1)
if name in property_id_list:
kw_dict[name] = value
return kw_dict
security.declareProtected(Permissions.AccessContentsInformation, 'asText')
def asText(self):
......@@ -64,32 +74,33 @@ class InternetProtocolAddress(Base, Coordinate):
"""
result = Coordinate.asText(self)
if result is None:
tmp = []
for prop in PropertySheet.InternetProtocolAddress._properties:
property_id = prop['id']
getter_name = 'get%s' % convertToUpperCase(property_id)
getter_method = getattr(self, getter_name)
value = getter_method() or ''
tmp.append('%s:%s' % (property_id, value))
result = '\n'.join(tmp)
if self.hasData():
result = '\n'.join(('%s:%s' % (k, v) for k, v in\
self._splitCoordinateText(self.getData())))
else:
tmp = []
for prop in PropertySheet.InternetProtocolAddress._properties:
property_id = prop['id']
getter_name = 'get%s' % convertToUpperCase(property_id)
getter_method = getattr(self, getter_name)
value = getter_method() or ''
tmp.append('%s:%s' % (property_id, value))
result = '\n'.join(tmp)
return result
security.declareProtected(Permissions.ModifyPortalContent, 'fromText')
@deprecated
def fromText(self, coordinate_text):
"""Save given data then continue parsing
(deprecated because computed values are stored)
"""
Try to import data from text.
"""
property_id_list = [i['id'] for i in PropertySheet.InternetProtocolAddress._properties]
self._setData(coordinate_text)
kw_dict = self._splitCoordinateText(coordinate_text)
for line in coordinate_text.split('\n'):
if not ':' in line:
continue
name, value = line.split(':', 1)
if name in property_id_list:
setter_name = 'set%s' % convertToUpperCase(name)
setter_method = getattr(self, setter_name)
setter_method(value)
for name, value in kw_dict.iteritems():
setter_name = 'set%s' % convertToUpperCase(name)
setter_method = getattr(self, setter_name)
setter_method(value)
def standardTextFormat(self):
"""
......
......@@ -232,16 +232,12 @@ class Telephone(Coordinate, Base):
# + (111) 111-111/111 or + (111) 111-111/ or + (111) 111-111
"\+(?P<spaces>[\ ]*)\((?P<country>\d+)\)\ (?P<number>[\d\ \-\.]*)(?:\/)?(?P<ext>\d+|)"
]
compiled_regex_list = [re.compile(pattern) for pattern in regex_list]
compiled_input_regex_without_markup = re.compile('[0-9A-Za-z]')
security.declareProtected(Permissions.ModifyPortalContent, 'fromText')
def fromText(self, coordinate_text):
""" See ICoordinate.fromText """
method = self._getTypeBasedMethod('fromText')
if method is not None:
return method(text=coordinate_text)
def _splitCoordinateText(self, coordinate_text):
if coordinate_text is None:
coordinate_text = ''
......@@ -266,30 +262,24 @@ class Telephone(Coordinate, Base):
msg = "Doesn't exist a regex to handle this telephone: ", \
coordinate_text
LOG('Telephone.fromText', WARNING, msg)
number_dict = {'number' : input_without_markup}
else:
number_dict = {'number' : coordinate_text}
country = number_dict.get('country','')
area = number_dict.get('area','')
city = number_dict.get('city','')
number = number_dict.get('number','')
extension = number_dict.get('ext','')
if ((country in ['', None]) and \
(area in ['', None]) and \
(city in ['', None]) and \
(number in ['', None]) and \
(extension in ['', None])):
country = area = city = number = extension = ''
number_dict = {'number': input_without_markup}
else:
number_dict = {'number': coordinate_text}
country = number_dict.get('country') or ''
area = number_dict.get('area') or ''
city = number_dict.get('city') or ''
number = number_dict.get('number') or ''
extension = number_dict.get('ext') or ''
if (country or area or city or number or extension):
# Trying to get the country and area from dict,
# but if it fails must be get from preference
preference_tool = self.portal_preferences
if country in ['', None]:
preference_tool = self.getPortalObject().portal_preferences
if not country:
country = preference_tool.getPreferredTelephoneDefaultCountryNumber('')
if area in ['', None]:
if not area:
area = preference_tool.getPreferredTelephoneDefaultAreaNumber('')
if city in ['', None]:
if not city:
city = preference_tool.getPreferredTelephoneDefaultCityNumber('')
country = country.strip()
......@@ -300,15 +290,30 @@ class Telephone(Coordinate, Base):
# Formating the number.
# Removing any ")", "(", "-", "." and " "
for token in [")", "(", "-" ,"." ," "]:
for token in ')(-. ':
country = country.replace(token, '')
number = number.replace(token, '')
return country, area, city, number, extension
self.edit(telephone_country = country,
telephone_area = area,
telephone_city = city,
telephone_number = number,
telephone_extension = extension)
security.declareProtected(Permissions.ModifyPortalContent, 'fromText')
@deprecated
def fromText(self, coordinate_text):
"""Save given data then continue parsing
(deprecated because computed values are stored)
"""
self._setData(coordinate_text)
method = self._getTypeBasedMethod('fromText')
if method is not None:
return method(text=coordinate_text)
country, area, city, number, extension =\
self._splitCoordinateText(coordinate_text)
self.edit(telephone_country=country,
telephone_area=area,
telephone_city=city,
telephone_number=number,
telephone_extension=extension)
security.declareProtected(Permissions.ModifyPortalContent, '_setText')
_setText = fromText
......@@ -322,37 +327,37 @@ class Telephone(Coordinate, Base):
if script is not None:
return script()
country = self.getTelephoneCountry('')
area = self.getTelephoneArea('')
city = self.getTelephoneCity('')
number = self.getTelephoneNumber('')
extension = self.getTelephoneExtension('')
# If country, area, number, extension are blank
# the method should to return blank.
if ((country == '') and \
(area == '') and \
(city == '') and \
(number == '') and \
(extension == '')):
return ''
# Define the notation
notation = self._getNotation()
if notation not in [None, '']:
notation = notation.replace('<country>',country)
notation = notation.replace('<area>',area)
if city == "":
notation = notation.replace('<city>-', '')
else:
notation = notation.replace('<city>',city)
notation = notation.replace('<number>',number)
notation = notation.replace('<ext>',extension)
if extension == '':
notation = notation.replace('/','')
return notation
if self.hasData():
coordinate_text = self.getData()
country, area, city, number, extension =\
self._splitCoordinateText(coordinate_text)
else:
# BBB if one of old slice is stored on current document
# then use old API in order to recompute coordinate string
country = self.getTelephoneCountry('')
area = self.getTelephoneArea('')
city = self.getTelephoneCity('')
number = self.getTelephoneNumber('')
extension = self.getTelephoneExtension('')
if (country or area or city or number or extension):
# Define the notation
notation = self._getNotation()
if notation:
notation = notation.replace('<country>', country)
notation = notation.replace('<area>', area)
if city == "":
notation = notation.replace('<city>-', '')
else:
notation = notation.replace('<city>', city)
notation = notation.replace('<number>', number)
notation = notation.replace('<ext>', extension)
if extension == '':
notation = notation.replace('/', '')
return notation
return ''
security.declareProtected(Permissions.AccessContentsInformation,
'asURL')
......
......@@ -37,6 +37,8 @@ from Products.ERP5.mixin.url import UrlMixin, no_crawl_protocol_list,\
no_host_protocol_list, default_protocol_dict
from zLOG import LOG
_marker = object()
class Url(Coordinate, Base, UrlMixin):
"""
A Url is allows to represent in a standard way coordinates
......@@ -69,7 +71,9 @@ class Url(Coordinate, Base, UrlMixin):
users just enter www.erp5.com or info@erp5.com rather than
http://www.erp5.com or mailto:info@erp5.com
"""
return self.getUrlString()
if self.hasData():
return self.getData('')
return self.getUrlString('')
security.declareProtected(Permissions.ModifyPortalContent, 'fromText')
@deprecated
......@@ -77,6 +81,7 @@ class Url(Coordinate, Base, UrlMixin):
"""
Sets url_string a.k.a. scheme-specific-part of a URL
"""
self._setData(text)
self.setUrlString(text)
security.declareProtected(Permissions.AccessContentsInformation,
......@@ -88,6 +93,21 @@ class Url(Coordinate, Base, UrlMixin):
"""
return ("http://www.erp5.org", "mailto:info@erp5.org")
def getUrlString(self, default=_marker):
if not self.hasUrlString():
if default is _marker:
return self.getData()
else:
return self.getData(default)
else:
if default is _marker:
return self._baseGetUrlString()
else:
return self._baseGetUrlString(default)
security.declareProtected(Permissions.UseMailhostServices, 'send')
def send(self, from_url=None, to_url=None, msg=None,
subject=None, attachment_list=None, extra_headers=None):
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment