diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..d523e55 --- /dev/null +++ b/.gitignore @@ -0,0 +1,16 @@ + +__pycache__ + +vobject.egg-info/PKG-INFO + +vobject.egg-info/SOURCES.txt + +vobject.egg-info/dependency_links.txt + +vobject.egg-info/entry_points.txt + +vobject.egg-info/requires.txt + +vobject.egg-info/top_level.txt + +vobject.egg-info/zip-safe diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..29f0eda --- /dev/null +++ b/.travis.yml @@ -0,0 +1,8 @@ +language: python +python: + - "2.7" + - "3.4" +install: pip install -e . +script: + - python tests.py +sudo: false diff --git a/MANIFEST.in b/MANIFEST.in new file mode 100644 index 0000000..0615dd1 --- /dev/null +++ b/MANIFEST.in @@ -0,0 +1,2 @@ +include README.md +recursive-include test_files *.ics diff --git a/README.md b/README.md new file mode 100644 index 0000000..98c51e4 --- /dev/null +++ b/README.md @@ -0,0 +1,6 @@ +VObject +======= + +### I am no longer maintaining this fork of vobject. + +### All development efforts have moved to [Python-Card-Me](https://github.com/tBaxter/python-card-me), which picks up exactly where this left off. Thank you for your support. diff --git a/README.txt b/README.txt deleted file mode 100644 index b2ae0d4..0000000 --- a/README.txt +++ /dev/null @@ -1,227 +0,0 @@ -======= -VObject -======= - -VObject simplifies the process of parsing and creating iCalendar and -vCard objects. - --------------- - Installation --------------- - -To install vobject, run:: - - python setup.py install - -vobject requires the dateutil package, which can be installed via -easy_install or downloaded from http://labix.org/python-dateutil - ---------------- - Running tests ---------------- - -Unit tests live in doctests throughout the source code, to run all tests, use:: - - python tests/tests.py - -------- - Usage -------- - -Creating iCalendar objects -.......................... - -vobject has a basic datastructure for working with iCalendar-like -syntaxes. Additionally, it defines specialized behaviors for many of -the commonly used iCalendar objects. - -To create an object that already has a behavior defined, run: - ->>> import vobject ->>> cal = vobject.newFromBehavior('vcalendar') ->>> cal.behavior - - -Convenience functions exist to create iCalendar and vCard objects: - ->>> cal = vobject.iCalendar() ->>> cal.behavior - ->>> card = vobject.vCard() ->>> card.behavior - - -Once you have an object, you can use the add method to create -children: - ->>> cal.add('vevent') - ->>> cal.vevent.add('summary').value = "This is a note" ->>> cal.prettyPrint() - VCALENDAR - VEVENT - SUMMARY: This is a note - -Note that summary is a little different from vevent, it's a -ContentLine, not a Component. It can't have children, and it has a -special value attribute. - -ContentLines can also have parameters. They can be accessed with -regular attribute names with _param appended: - ->>> cal.vevent.summary.x_random_param = 'Random parameter' ->>> cal.prettyPrint() - VCALENDAR - VEVENT - SUMMARY: This is a note - params for SUMMARY: - X-RANDOM ['Random parameter'] - -There are a few things to note about this example - - * The underscore in x_random is converted to a dash (dashes are - legal in iCalendar, underscores legal in Python) - * X-RANDOM's value is a list. - -If you want to access the full list of parameters, not just the first, -use _paramlist: - ->>> cal.vevent.summary.x_random_paramlist -['Random parameter'] ->>> cal.vevent.summary.x_random_paramlist.append('Other param') ->>> cal.vevent.summary - - -Similar to parameters, If you want to access more than just the first -child of a Component, you can access the full list of children of a -given name by appending _list to the attribute name: - ->>> cal.add('vevent').add('summary').value = "Second VEVENT" ->>> for ev in cal.vevent_list: -... print ev.summary.value -This is a note -Second VEVENT - -The interaction between the del operator and the hiding of the -underlying list is a little tricky, del cal.vevent and del -cal.vevent_list both delete all vevent children: - ->>> first_ev = cal.vevent ->>> del cal.vevent ->>> cal - ->>> cal.vevent = first_ev - -vobject understands Python's datetime module and tzinfo classes. - ->>> import datetime ->>> utc = vobject.icalendar.utc ->>> start = cal.vevent.add('dtstart') ->>> start.value = datetime.datetime(2006, 2, 16, tzinfo = utc) ->>> first_ev.prettyPrint() - VEVENT - DTSTART: 2006-02-16 00:00:00+00:00 - SUMMARY: This is a note - params for SUMMARY: - X-RANDOM ['Random parameter', 'Other param'] - -Components and ContentLines have serialize methods: - ->>> cal.vevent.add('uid').value = 'Sample UID' ->>> icalstream = cal.serialize() ->>> print icalstream -BEGIN:VCALENDAR -VERSION:2.0 -PRODID:-//PYVOBJECT//NONSGML Version 1//EN -BEGIN:VEVENT -UID:Sample UID -DTSTART:20060216T000000Z -SUMMARY;X-RANDOM=Random parameter,Other param:This is a note -END:VEVENT -END:VCALENDAR - -Observe that serializing adds missing required lines like version and -prodid. A random UID would be generated, too, if one didn't exist. - -If dtstart's tzinfo had been something other than UTC, an appropriate -vtimezone would be created for it. - - -Parsing iCalendar objects -......................... - -To parse one top level component from an existing iCalendar stream or -string, use the readOne function: - ->>> parsedCal = vobject.readOne(icalstream) ->>> parsedCal.vevent.dtstart.value -datetime.datetime(2006, 2, 16, 0, 0, tzinfo=tzutc()) - -Similarly, readComponents is a generator yielding one top level -component at a time from a stream or string. - ->>> vobject.readComponents(icalstream).next().vevent.dtstart.value -datetime.datetime(2006, 2, 16, 0, 0, tzinfo=tzutc()) - -More examples can be found in source code doctests. - -vCards -...... - -Making vCards proceeds in much the same way. Note that the 'N' and 'FN' -attributes are required. - ->>> j = vobject.vCard() ->>> j.add('n') - ->>> j.n.value = vobject.vcard.Name( family='Harris', given='Jeffrey' ) ->>> j.add('fn') - ->>> j.fn.value ='Jeffrey Harris' ->>> j.add('email') - ->>> j.email.value = 'jeffrey@osafoundation.org' ->>> j.email.type_param = 'INTERNET' ->>> j.prettyPrint() - VCARD - EMAIL: jeffrey@osafoundation.org - params for EMAIL: - TYPE ['INTERNET'] - FN: Jeffrey Harris - N: Jeffrey Harris - -serializing will add any required computable attributes (like 'VERSION') - ->>> j.serialize() -'BEGIN:VCARD\r\nVERSION:3.0\r\nEMAIL;TYPE=INTERNET:jeffrey@osafoundation.org\r\nFN:Jeffrey Harris\r\nN:Harris;Jeffrey;;;\r\nEND:VCARD\r\n' ->>> j.prettyPrint() - VCARD - VERSION: 3.0 - EMAIL: jeffrey@osafoundation.org - params for EMAIL: - TYPE ['INTERNET'] - FN: Jeffrey Harris - N: Jeffrey Harris - -Parsing vCards -.............. - ->>> s = """ -... BEGIN:VCARD -... VERSION:3.0 -... EMAIL;TYPE=INTERNET:jeffrey@osafoundation.org -... FN:Jeffrey Harris -... N:Harris;Jeffrey;;; -... END:VCARD -... """ ->>> v = vobject.readOne( s ) ->>> v.prettyPrint() - VCARD - VERSION: 3.0 - EMAIL: jeffrey@osafoundation.org - params for EMAIL: - TYPE [u'INTERNET'] - FN: Jeffrey Harris - N: Jeffrey Harris ->>> v.n.value.family -u'Harris' \ No newline at end of file diff --git a/dist/vobject-0.8.2.tar.gz b/dist/vobject-0.8.2.tar.gz new file mode 100644 index 0000000..ae00bac Binary files /dev/null and b/dist/vobject-0.8.2.tar.gz differ diff --git a/setup.py b/setup.py index 89df9f4..73e0f6b 100755 --- a/setup.py +++ b/setup.py @@ -3,7 +3,9 @@ Description ----------- -Parses iCalendar and vCard files into Python data structures, decoding the relevant encodings. Also serializes vobject data structures to iCalendar, vCard, or (experimentally) hCalendar unicode strings. +Parses iCalendar and vCard files into Python data structures, decoding the relevant encodings. +Also serializes vobject data structures to iCalendar, vCard, or (experimentally) +hCalendar unicode strings. Requirements ------------ @@ -44,31 +46,32 @@ doclines = __doc__.splitlines() -setup(name = "vobject", - version = "0.8.1c", - author = "Jeffrey Harris", - author_email = "jeffrey@osafoundation.org", - license = "Apache", - zip_safe = True, - url = "http://vobject.skyhouseconsulting.com", - entry_points = { 'console_scripts': ['ics_diff = vobject.ics_diff:main', - 'change_tz = vobject.change_tz:main']}, - include_package_data = True, - test_suite = "test_vobject", - - install_requires = ['python-dateutil >= 1.1'], - - platforms = ["any"], - packages = find_packages(), - description = doclines[0], - long_description = "\n".join(doclines[2:]), - classifiers = """ - Development Status :: 5 - Production/Stable - Environment :: Console - License :: OSI Approved :: BSD License - Intended Audience :: Developers - Natural Language :: English - Programming Language :: Python - Operating System :: OS Independent - Topic :: Text Processing""".strip().splitlines() +setup(name="vobject", + version="0.8.6", + author="Jeffrey Harris, Tim Baxter", + author_email="mail.baxter@gmail.com", + license="Apache", + zip_safe=True, + url="http://vobject.skyhouseconsulting.com", + entry_points={ + 'console_scripts': [ + 'ics_diff = vobject.ics_diff:main', + 'change_tz = vobject.change_tz:main' + ] + }, + include_package_data=True, + install_requires=['python-dateutil == 2.4.0'], + platforms=["any"], + packages=find_packages(), + description=doclines[0], + long_description="\n".join(doclines[2:]), + classifiers=""" + Development Status :: 5 - Production/Stable + Environment :: Console + License :: OSI Approved :: BSD License + Intended Audience :: Developers + Natural Language :: English + Programming Language :: Python + Operating System :: OS Independent + Topic :: Text Processing""".strip().splitlines() ) diff --git a/test_files/availablity.ics b/test_files/availablity.ics new file mode 100644 index 0000000..446db07 --- /dev/null +++ b/test_files/availablity.ics @@ -0,0 +1,14 @@ +BEGIN:VAVAILABILITY +UID:test +DTSTART:20060216T000000Z +DTEND:20060217T000000Z +BEGIN:AVAILABLE +UID:test1 +DTSTART:20060216T090000Z +DTEND:20060216T120000Z +DTSTAMP:20060215T000000Z +SUMMARY:Available in the morning +END:AVAILABLE +BUSYTYPE:BUSY +DTSTAMP:20060215T000000Z +END:VAVAILABILITY diff --git a/test_files/badline.ics b/test_files/badline.ics new file mode 100644 index 0000000..ed81a6b --- /dev/null +++ b/test_files/badline.ics @@ -0,0 +1,10 @@ +BEGIN:VCALENDAR +METHOD:PUBLISH +VERSION:2.0 +BEGIN:VEVENT +DTSTART:19870405T020000 +X-BAD/SLASH:TRUE +X-BAD_UNDERSCORE:TRUE +UID:EC9439B1-FF65-11D6-9973-003065F99D04 +END:VEVENT +END:VCALENDAR diff --git a/test_files/badstream.ics b/test_files/badstream.ics new file mode 100644 index 0000000..42a3220 --- /dev/null +++ b/test_files/badstream.ics @@ -0,0 +1,16 @@ +BEGIN:VCALENDAR +CALSCALE:GREGORIAN +X-WR-TIMEZONE;VALUE=TEXT:US/Pacific +METHOD:PUBLISH +PRODID:-//Apple Computer\, Inc//iCal 1.0//EN +X-WR-CALNAME;VALUE=TEXT:Example +VERSION:2.0 +BEGIN:VEVENT +DTSTART:20021028T140000Z +BEGIN:VALARM +TRIGGER:a20021028120000 +ACTION:DISPLAY +DESCRIPTION:This trigger has a nonsensical value +END:VALARM +END:VEVENT +END:VCALENDAR diff --git a/test_files/freebusy.ics b/test_files/freebusy.ics new file mode 100644 index 0000000..fb38f68 --- /dev/null +++ b/test_files/freebusy.ics @@ -0,0 +1,7 @@ +BEGIN:VFREEBUSY +UID:test +DTSTART:20060216T010000Z +DTEND:20060216T030000Z +FREEBUSY:20060216T010000Z/PT1H +FREEBUSY:20060216T010000Z/20060216T030000Z +END:VFREEBUSY diff --git a/test_files/journal.ics b/test_files/journal.ics new file mode 100644 index 0000000..5c4d7d6 --- /dev/null +++ b/test_files/journal.ics @@ -0,0 +1,15 @@ +BEGIN:VJOURNAL +UID:19970901T130000Z-123405@example.com +DTSTAMP:19970901T130000Z +DTSTART;VALUE=DATE:19970317 +SUMMARY:Staff meeting minutes +DESCRIPTION:1. Staff meeting: Participants include Joe\, + Lisa\, and Bob. Aurora project plans were reviewed. + There is currently no budget reserves for this project. + Lisa will escalate to management. Next meeting on Tuesday.\n + 2. Telephone Conference: ABC Corp. sales representative + called to discuss new printer. Promised to get us a demo by + Friday.\n3. Henry Miller (Handsoff Insurance): Car was + totaled by tree. Is looking into a loaner car. 555-2323 + (tel). +END:VJOURNAL diff --git a/test_files/more_tests.txt b/test_files/more_tests.txt index 4102fcc..c2072b0 100644 --- a/test_files/more_tests.txt +++ b/test_files/more_tests.txt @@ -9,9 +9,9 @@ Unicode in vCards >>> card.add('adr').value = vobject.vcard.Address(u'5\u1234 Nowhere, Apt 1', 'Berkeley', 'CA', '94704', 'USA') >>> card , , ]> ->>> card.serialize().decode("utf-8") +>>> card.serialize() u'BEGIN:VCARD\r\nVERSION:3.0\r\nADR:;;5\u1234 Nowhere\\, Apt 1;Berkeley;CA;94704;USA\r\nFN:Hello\u1234 World!\r\nN:World;Hello\u1234;;;\r\nEND:VCARD\r\n' ->>> print card.serialize() +>>> print(card.serialize()) BEGIN:VCARD VERSION:3.0 ADR:;;5ሴ Nowhere\, Apt 1;Berkeley;CA;94704;USA @@ -32,16 +32,16 @@ Unicode in TZID ............... >>> f = get_stream("tzid_8bit.ics") >>> cal = vobject.readOne(f) ->>> print cal.vevent.dtstart.value +>>> print(cal.vevent.dtstart.value) 2008-05-30 15:00:00+06:00 ->>> print cal.vevent.dtstart.serialize() +>>> print(cal.vevent.dtstart.serialize()) DTSTART;TZID=Екатеринбург:20080530T150000 Commas in TZID .............. >>> f = get_stream("ms_tzid.ics") >>> cal = vobject.readOne(f) ->>> print cal.vevent.dtstart.value +>>> print(cal.vevent.dtstart.value) 2008-05-30 15:00:00+10:00 Equality in vCards @@ -56,7 +56,7 @@ Organization (org) .................. >>> card.add('org').value = ["Company, Inc.", "main unit", "sub-unit"] ->>> print card.org.serialize() +>>> print(card.org.serialize()) ORG:Company\, Inc.;main unit;sub-unit Ruby escapes semi-colons in rrules @@ -68,19 +68,3 @@ Ruby escapes semi-colons in rrules datetime.datetime(2003, 1, 1, 7, 0) -quoted-printable -................ - ->>> vcf = 'BEGIN:VCARD\nVERSION:2.1\nN;ENCODING=QUOTED-PRINTABLE:;=E9\nFN;ENCODING=QUOTED-PRINTABLE:=E9\nTEL;HOME:0111111111\nEND:VCARD\n\n' ->>> vcf = vobject.readOne(vcf) ->>> vcf.n.value - ->>> vcf.n.value.given -u'\xe9' ->>> vcf.serialize() -'BEGIN:VCARD\r\nVERSION:2.1\r\nFN:\xc3\xa9\r\nN:;\xc3\xa9;;;\r\nTEL:0111111111\r\nEND:VCARD\r\n' - ->>> vcs = 'BEGIN:VCALENDAR\r\nPRODID:-//OpenSync//NONSGML OpenSync vformat 0.3//EN\r\nVERSION:1.0\r\nBEGIN:VEVENT\r\nDESCRIPTION;CHARSET=UTF-8;ENCODING=QUOTED-PRINTABLE:foo =C3=A5=0Abar =C3=A4=\r\n=0Abaz =C3=B6\r\nUID:20080406T152030Z-7822\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n' ->>> vcs = vobject.readOne(vcs, allowQP = True) ->>> vcs.serialize() -'BEGIN:VCALENDAR\r\nVERSION:1.0\r\nPRODID:-//OpenSync//NONSGML OpenSync vformat 0.3//EN\r\nBEGIN:VEVENT\r\nUID:20080406T152030Z-7822\r\nDESCRIPTION:foo \xc3\xa5\\nbar \xc3\xa4\\nbaz \xc3\xb6\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n' diff --git a/test_files/silly_test.ics b/test_files/silly_test.ics new file mode 100644 index 0000000..2ee72db --- /dev/null +++ b/test_files/silly_test.ics @@ -0,0 +1,5 @@ +sillyname:name +profile:sillyprofile +stuff:folded + line +morestuff;asinine:this line is not folded, but in practice probably ought to be, as it is exceptionally long, and moreover demonstratively stupid diff --git a/test_files/simple_2_0_test.ics b/test_files/simple_2_0_test.ics new file mode 100644 index 0000000..9ffa758 --- /dev/null +++ b/test_files/simple_2_0_test.ics @@ -0,0 +1,10 @@ +BEGIN:VCALENDAR +VERSION:2.0 +PRODID:-//PYVOBJECT//NONSGML Version 1//EN +BEGIN:VEVENT +UID:Not very random UID +DTSTART:20060509T000000 +CREATED:20060101T180000Z +DESCRIPTION:Test event +END:VEVENT +END:VCALENDAR diff --git a/test_files/simple_3_0_test.ics b/test_files/simple_3_0_test.ics new file mode 100644 index 0000000..d5e4642 --- /dev/null +++ b/test_files/simple_3_0_test.ics @@ -0,0 +1,13 @@ +BEGIN:VCARD +VERSION:3.0 +FN:Daffy Duck Knudson (with Bugs Bunny and Mr. Pluto) +N:Knudson;Daffy Duck (with Bugs Bunny and Mr. Pluto) +NICKNAME:gnat and gnu and pluto +BDAY;value=date:02-10 +TEL;type=HOME:+01-(0)2-765.43.21 +TEL;type=CELL:+01-(0)5-555.55.55 +ACCOUNT;type=HOME:010-1234567-05 +ADR;type=HOME:;;Haight Street 512\;\nEscape\, Test;Novosibirsk;;80214;Gnuland +TEL;type=HOME:+01-(0)2-876.54.32 +ORG:University of Novosibirsk, Department of Octopus Parthenogenesis +END:VCARD diff --git a/test_files/simple_test.ics b/test_files/simple_test.ics new file mode 100644 index 0000000..aefb51e --- /dev/null +++ b/test_files/simple_test.ics @@ -0,0 +1,5 @@ +BEGIN:VCALENDAR +BEGIN:VEVENT +SUMMARY;blah=hi!:Bastille Day Party +END:VEVENT +END:VCALENDAR diff --git a/test_files/standard_test.ics b/test_files/standard_test.ics new file mode 100644 index 0000000..4593fe1 --- /dev/null +++ b/test_files/standard_test.ics @@ -0,0 +1,41 @@ +BEGIN:VCALENDAR +CALSCALE:GREGORIAN +X-WR-TIMEZONE;VALUE=TEXT:US/Pacific +METHOD:PUBLISH +PRODID:-//Apple Computer\, Inc//iCal 1.0//EN +X-WR-CALNAME;VALUE=TEXT:Example +VERSION:2.0 +BEGIN:VEVENT +SEQUENCE:5 +DTSTART;TZID=US/Pacific:20021028T140000 +RRULE:FREQ=Weekly;COUNT=10 +DTSTAMP:20021028T011706Z +SUMMARY:Coffee with Jason +UID:EC9439B1-FF65-11D6-9973-003065F99D04 +DTEND;TZID=US/Pacific:20021028T150000 +BEGIN:VALARM +TRIGGER;VALUE=DURATION:-P1D +ACTION:DISPLAY +DESCRIPTION:Event reminder\, with comma\nand line feed +END:VALARM +END:VEVENT +BEGIN:VTIMEZONE +X-LIC-LOCATION:Random location +TZID:US/Pacific +LAST-MODIFIED:19870101T000000Z +BEGIN:STANDARD +DTSTART:19671029T020000 +RRULE:FREQ=YEARLY;BYDAY=-1SU;BYMONTH=10 +TZOFFSETFROM:-0700 +TZOFFSETTO:-0800 +TZNAME:PST +END:STANDARD +BEGIN:DAYLIGHT +DTSTART:19870405T020000 +RRULE:FREQ=YEARLY;BYDAY=1SU;BYMONTH=4 +TZOFFSETFROM:-0800 +TZOFFSETTO:-0700 +TZNAME:PDT +END:DAYLIGHT +END:VTIMEZONE +END:VCALENDAR diff --git a/test_files/timezones.ics b/test_files/timezones.ics new file mode 100644 index 0000000..e839223 --- /dev/null +++ b/test_files/timezones.ics @@ -0,0 +1,107 @@ +BEGIN:VTIMEZONE +TZID:US/Pacific +BEGIN:STANDARD +DTSTART:19671029T020000 +RRULE:FREQ=YEARLY;BYDAY=-1SU;BYMONTH=10 +TZOFFSETFROM:-0700 +TZOFFSETTO:-0800 +TZNAME:PST +END:STANDARD +BEGIN:DAYLIGHT +DTSTART:19870405T020000 +RRULE:FREQ=YEARLY;BYDAY=1SU;BYMONTH=4 +TZOFFSETFROM:-0800 +TZOFFSETTO:-0700 +TZNAME:PDT +END:DAYLIGHT +END:VTIMEZONE + +BEGIN:VTIMEZONE +TZID:US/Eastern +BEGIN:STANDARD +DTSTART:19671029T020000 +RRULE:FREQ=YEARLY;BYDAY=-1SU;BYMONTH=10 +TZOFFSETFROM:-0400 +TZOFFSETTO:-0500 +TZNAME:EST +END:STANDARD +BEGIN:DAYLIGHT +DTSTART:19870405T020000 +RRULE:FREQ=YEARLY;BYDAY=1SU;BYMONTH=4 +TZOFFSETFROM:-0500 +TZOFFSETTO:-0400 +TZNAME:EDT +END:DAYLIGHT +END:VTIMEZONE + +BEGIN:VTIMEZONE +TZID:Santiago +BEGIN:STANDARD +DTSTART:19700314T000000 +TZOFFSETFROM:-0300 +TZOFFSETTO:-0400 +RRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=2SA +TZNAME:Pacific SA Standard Time +END:STANDARD +BEGIN:DAYLIGHT +DTSTART:19701010T000000 +TZOFFSETFROM:-0400 +TZOFFSETTO:-0300 +RRULE:FREQ=YEARLY;BYMONTH=10;BYDAY=2SA +TZNAME:Pacific SA Daylight Time +END:DAYLIGHT +END:VTIMEZONE + +BEGIN:VTIMEZONE +TZID:W. Europe +BEGIN:STANDARD +DTSTART:19701025T030000 +TZOFFSETFROM:+0200 +TZOFFSETTO:+0100 +RRULE:FREQ=YEARLY;BYMONTH=10;BYDAY=-1SU +TZNAME:W. Europe Standard Time +END:STANDARD +BEGIN:DAYLIGHT +DTSTART:19700329T020000 +TZOFFSETFROM:+0100 +TZOFFSETTO:+0200 +RRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=-1SU +TZNAME:W. Europe Daylight Time +END:DAYLIGHT +END:VTIMEZONE + +BEGIN:VTIMEZONE +TZID:US/Fictitious-Eastern +LAST-MODIFIED:19870101T000000Z +BEGIN:STANDARD +DTSTART:19671029T020000 +RRULE:FREQ=YEARLY;BYDAY=-1SU;BYMONTH=10 +TZOFFSETFROM:-0400 +TZOFFSETTO:-0500 +TZNAME:EST +END:STANDARD +BEGIN:DAYLIGHT +DTSTART:19870405T020000 +RRULE:FREQ=YEARLY;BYDAY=1SU;BYMONTH=4;UNTIL=20050403T070000Z +TZOFFSETFROM:-0500 +TZOFFSETTO:-0400 +TZNAME:EDT +END:DAYLIGHT +END:VTIMEZONE + +BEGIN:VTIMEZONE +TZID:America/Montreal +LAST-MODIFIED:20051013T233643Z +BEGIN:DAYLIGHT +DTSTART:20050403T070000 +TZOFFSETTO:-0400 +TZOFFSETFROM:+0000 +TZNAME:EDT +END:DAYLIGHT +BEGIN:STANDARD +DTSTART:20051030T020000 +TZOFFSETTO:-0500 +TZOFFSETFROM:-0400 +TZNAME:EST +END:STANDARD +END:VTIMEZONE diff --git a/test_files/vcard_with_groups.ics b/test_files/vcard_with_groups.ics new file mode 100644 index 0000000..d64ff90 --- /dev/null +++ b/test_files/vcard_with_groups.ics @@ -0,0 +1,18 @@ +home.begin:vcard +version:3.0 +source:ldap://cn=Meister%20Berger,o=Universitaet%20Goerlitz,c=DE +name:Meister Berger +fn:Meister Berger +n:Berger;Meister +bday;value=date:1963-09-21 +o:Universit=E6t G=F6rlitz +title:Mayor +title;language=de;value=text:Burgermeister +note:The Mayor of the great city of + Goerlitz in the great country of Germany.\nNext line. +email;internet:mb@goerlitz.de +home.tel;type=fax,voice;type=msg:+49 3581 123456 +home.label:Hufenshlagel 1234\n + 02828 Goerlitz\n + Deutschland +END:VCARD diff --git a/test_files/vtodo.ics b/test_files/vtodo.ics new file mode 100644 index 0000000..26b577c --- /dev/null +++ b/test_files/vtodo.ics @@ -0,0 +1,13 @@ +BEGIN:VCALENDAR +VERSION:2.0 +PRODID:-//Example Corp.//CalDAV Client//EN +BEGIN:VTODO +UID:20070313T123432Z-456553@example.com +DTSTAMP:20070313T123432Z +DUE;VALUE=DATE:20070501 +SUMMARY:Submit Quebec Income Tax Return for 2006 +CLASS:CONFIDENTIAL +CATEGORIES:FAMILY,FINANCE +STATUS:NEEDS-ACTION +END:VTODO +END:VCALENDAR diff --git a/test_vobject.py b/test_vobject.py deleted file mode 100644 index 9ee214a..0000000 --- a/test_vobject.py +++ /dev/null @@ -1,783 +0,0 @@ -"""Long or boring tests for vobjects.""" - -import vobject -from vobject import base, icalendar, behavior, vcard, hcalendar -import StringIO, re, dateutil.tz, datetime - -import doctest, test_vobject, unittest - -from pkg_resources import resource_stream - -base.logger.setLevel(base.logging.FATAL) -#------------------- Testing and running functions ----------------------------- -# named additional_tests for setuptools -def additional_tests(): - - flags = doctest.NORMALIZE_WHITESPACE | doctest.REPORT_ONLY_FIRST_FAILURE | doctest.ELLIPSIS - suite = unittest.TestSuite() - for module in base, test_vobject, icalendar, vobject, vcard: - suite.addTest(doctest.DocTestSuite(module, optionflags=flags)) - - suite.addTest(doctest.DocFileSuite( - 'README.txt', 'test_files/more_tests.txt', - package='__main__', optionflags=flags - )) - return suite - -if __name__ == '__main__': - runner = unittest.TextTestRunner() - runner.run(additional_tests()) - - -testSilly=""" -sillyname:name -profile:sillyprofile -stuff:folded - line -""" + "morestuff;asinine:this line is not folded, \ -but in practice probably ought to be, as it is exceptionally long, \ -and moreover demonstratively stupid" - -icaltest=r"""BEGIN:VCALENDAR -CALSCALE:GREGORIAN -X-WR-TIMEZONE;VALUE=TEXT:US/Pacific -METHOD:PUBLISH -PRODID:-//Apple Computer\, Inc//iCal 1.0//EN -X-WR-CALNAME;VALUE=TEXT:Example -VERSION:2.0 -BEGIN:VEVENT -SEQUENCE:5 -DTSTART;TZID=US/Pacific:20021028T140000 -RRULE:FREQ=Weekly;COUNT=10 -DTSTAMP:20021028T011706Z -SUMMARY:Coffee with Jason -UID:EC9439B1-FF65-11D6-9973-003065F99D04 -DTEND;TZID=US/Pacific:20021028T150000 -BEGIN:VALARM -TRIGGER;VALUE=DURATION:-P1D -ACTION:DISPLAY -DESCRIPTION:Event reminder\, with comma\nand line feed -END:VALARM -END:VEVENT -BEGIN:VTIMEZONE -X-LIC-LOCATION:Random location -TZID:US/Pacific -LAST-MODIFIED:19870101T000000Z -BEGIN:STANDARD -DTSTART:19671029T020000 -RRULE:FREQ=YEARLY;BYDAY=-1SU;BYMONTH=10 -TZOFFSETFROM:-0700 -TZOFFSETTO:-0800 -TZNAME:PST -END:STANDARD -BEGIN:DAYLIGHT -DTSTART:19870405T020000 -RRULE:FREQ=YEARLY;BYDAY=1SU;BYMONTH=4 -TZOFFSETFROM:-0800 -TZOFFSETTO:-0700 -TZNAME:PDT -END:DAYLIGHT -END:VTIMEZONE -END:VCALENDAR""" - -badDtStartTest="""BEGIN:VCALENDAR -METHOD:PUBLISH -VERSION:2.0 -BEGIN:VEVENT -DTSTART:20021028 -DTSTAMP:20021028T011706Z -SUMMARY:Coffee with Jason -UID:EC9439B1-FF65-11D6-9973-003065F99D04 -END:VEVENT -END:VCALENDAR""" - -badLineTest="""BEGIN:VCALENDAR -METHOD:PUBLISH -VERSION:2.0 -BEGIN:VEVENT -DTSTART:19870405T020000 -X-BAD/SLASH:TRUE -X-BAD_UNDERSCORE:TRUE -UID:EC9439B1-FF65-11D6-9973-003065F99D04 -END:VEVENT -END:VCALENDAR""" - -vcardtest =r"""BEGIN:VCARD -VERSION:3.0 -FN:Daffy Duck Knudson (with Bugs Bunny and Mr. Pluto) -N:Knudson;Daffy Duck (with Bugs Bunny and Mr. Pluto) -NICKNAME:gnat and gnu and pluto -BDAY;value=date:02-10 -TEL;type=HOME:+01-(0)2-765.43.21 -TEL;type=CELL:+01-(0)5-555.55.55 -ACCOUNT;type=HOME:010-1234567-05 -ADR;type=HOME:;;Haight Street 512\;\nEscape\, Test;Novosibirsk;;80214;Gnuland -TEL;type=HOME:+01-(0)2-876.54.32 -ORG:University of Novosibirsk\, Department of Octopus - Parthenogenesis -END:VCARD""" - -vcardWithGroups = r"""home.begin:vcard -version:3.0 -source:ldap://cn=Meister%20Berger,o=Universitaet%20Goerlitz,c=DE -name:Meister Berger -fn:Meister Berger -n:Berger;Meister -bday;value=date:1963-09-21 -o:Universit=E6t G=F6rlitz -title:Mayor -title;language=de;value=text:Burgermeister -note:The Mayor of the great city of - Goerlitz in the great country of Germany.\nNext line. -email;internet:mb@goerlitz.de -home.tel;type=fax,voice;type=msg:+49 3581 123456 -home.label:Hufenshlagel 1234\n - 02828 Goerlitz\n - Deutschland -END:VCARD""" - -lowercaseComponentNames = r"""begin:vcard -fn:Anders Bobo -n:Bobo;Anders -org:Bobo A/S;Vice President, Technical Support -adr:Rockfeller Center;;Mekastreet;Bobocity;;2100;Myworld -email;internet:bobo@example.com -tel;work:+123455 -tel;fax:+123456 -tel;cell:+123457 -x-mozilla-html:FALSE -url:http://www.example.com -version:2.1 -end:vcard""" - -icalWeirdTrigger = r"""BEGIN:VCALENDAR -CALSCALE:GREGORIAN -X-WR-TIMEZONE;VALUE=TEXT:US/Pacific -METHOD:PUBLISH -PRODID:-//Apple Computer\, Inc//iCal 1.0//EN -X-WR-CALNAME;VALUE=TEXT:Example -VERSION:2.0 -BEGIN:VEVENT -DTSTART:20021028T140000Z -BEGIN:VALARM -TRIGGER:20021028T120000Z -ACTION:DISPLAY -DESCRIPTION:This trigger is a date-time without a VALUE=DATE-TIME parameter -END:VALARM -END:VEVENT -END:VCALENDAR""" - -badstream = r"""BEGIN:VCALENDAR -CALSCALE:GREGORIAN -X-WR-TIMEZONE;VALUE=TEXT:US/Pacific -METHOD:PUBLISH -PRODID:-//Apple Computer\, Inc//iCal 1.0//EN -X-WR-CALNAME;VALUE=TEXT:Example -VERSION:2.0 -BEGIN:VEVENT -DTSTART:20021028T140000Z -BEGIN:VALARM -TRIGGER:a20021028120000 -ACTION:DISPLAY -DESCRIPTION:This trigger has a nonsensical value -END:VALARM -END:VEVENT -END:VCALENDAR""" - -timezones = r""" - -BEGIN:VTIMEZONE -TZID:US/Pacific -BEGIN:STANDARD -DTSTART:19671029T020000 -RRULE:FREQ=YEARLY;BYDAY=-1SU;BYMONTH=10 -TZOFFSETFROM:-0700 -TZOFFSETTO:-0800 -TZNAME:PST -END:STANDARD -BEGIN:DAYLIGHT -DTSTART:19870405T020000 -RRULE:FREQ=YEARLY;BYDAY=1SU;BYMONTH=4 -TZOFFSETFROM:-0800 -TZOFFSETTO:-0700 -TZNAME:PDT -END:DAYLIGHT -END:VTIMEZONE - -BEGIN:VTIMEZONE -TZID:US/Eastern -BEGIN:STANDARD -DTSTART:19671029T020000 -RRULE:FREQ=YEARLY;BYDAY=-1SU;BYMONTH=10 -TZOFFSETFROM:-0400 -TZOFFSETTO:-0500 -TZNAME:EST -END:STANDARD -BEGIN:DAYLIGHT -DTSTART:19870405T020000 -RRULE:FREQ=YEARLY;BYDAY=1SU;BYMONTH=4 -TZOFFSETFROM:-0500 -TZOFFSETTO:-0400 -TZNAME:EDT -END:DAYLIGHT -END:VTIMEZONE - -BEGIN:VTIMEZONE -TZID:Santiago -BEGIN:STANDARD -DTSTART:19700314T000000 -TZOFFSETFROM:-0300 -TZOFFSETTO:-0400 -RRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=2SA -TZNAME:Pacific SA Standard Time -END:STANDARD -BEGIN:DAYLIGHT -DTSTART:19701010T000000 -TZOFFSETFROM:-0400 -TZOFFSETTO:-0300 -RRULE:FREQ=YEARLY;BYMONTH=10;BYDAY=2SA -TZNAME:Pacific SA Daylight Time -END:DAYLIGHT -END:VTIMEZONE - -BEGIN:VTIMEZONE -TZID:W. Europe -BEGIN:STANDARD -DTSTART:19701025T030000 -TZOFFSETFROM:+0200 -TZOFFSETTO:+0100 -RRULE:FREQ=YEARLY;BYMONTH=10;BYDAY=-1SU -TZNAME:W. Europe Standard Time -END:STANDARD -BEGIN:DAYLIGHT -DTSTART:19700329T020000 -TZOFFSETFROM:+0100 -TZOFFSETTO:+0200 -RRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=-1SU -TZNAME:W. Europe Daylight Time -END:DAYLIGHT -END:VTIMEZONE - -BEGIN:VTIMEZONE -TZID:US/Fictitious-Eastern -LAST-MODIFIED:19870101T000000Z -BEGIN:STANDARD -DTSTART:19671029T020000 -RRULE:FREQ=YEARLY;BYDAY=-1SU;BYMONTH=10 -TZOFFSETFROM:-0400 -TZOFFSETTO:-0500 -TZNAME:EST -END:STANDARD -BEGIN:DAYLIGHT -DTSTART:19870405T020000 -RRULE:FREQ=YEARLY;BYDAY=1SU;BYMONTH=4;UNTIL=20050403T070000Z -TZOFFSETFROM:-0500 -TZOFFSETTO:-0400 -TZNAME:EDT -END:DAYLIGHT -END:VTIMEZONE - -BEGIN:VTIMEZONE -TZID:America/Montreal -LAST-MODIFIED:20051013T233643Z -BEGIN:DAYLIGHT -DTSTART:20050403T070000 -TZOFFSETTO:-0400 -TZOFFSETFROM:+0000 -TZNAME:EDT -END:DAYLIGHT -BEGIN:STANDARD -DTSTART:20051030T020000 -TZOFFSETTO:-0500 -TZOFFSETFROM:-0400 -TZNAME:EST -END:STANDARD -END:VTIMEZONE - -""" - -__test__ = { "Test readOne" : - r""" - >>> silly = base.readOne(testSilly, findBegin=False) - >>> silly - , , ]> - >>> silly.stuff - - >>> original = silly.serialize() - >>> f3 = StringIO.StringIO(original.decode("utf-8")) - >>> silly2 = base.readOne(f3) - >>> silly2.serialize()==original - True - >>> s3 = StringIO.StringIO('cn:Babs Jensen\r\ncn:Barbara J Jensen\r\nsn:Jensen\r\nemail:babs@umich.edu\r\nphone:+1 313 747-4454\r\nx-id:1234567890\r\n') - >>> ex1 = base.readOne(s3, findBegin=False) - >>> ex1 - <*unnamed*| [, , , , , ]> - >>> ex1.serialize() - 'CN:Babs Jensen\r\nCN:Barbara J Jensen\r\nEMAIL:babs@umich.edu\r\nPHONE:+1 313 747-4454\r\nSN:Jensen\r\nX-ID:1234567890\r\n' - """, - - "Import icaltest" : - r""" - >>> c = base.readOne(icaltest, validate=True) - >>> c.vevent.valarm.trigger - - >>> c.vevent.dtstart.value - datetime.datetime(2002, 10, 28, 14, 0, tzinfo=) - >>> c.vevent.dtend.value - datetime.datetime(2002, 10, 28, 15, 0, tzinfo=) - >>> c.vevent.dtstamp.value - datetime.datetime(2002, 10, 28, 1, 17, 6, tzinfo=tzutc()) - >>> c.vevent.valarm.description.value - u'Event reminder, with comma\nand line feed' - >>> c.vevent.valarm.description.serialize() - 'DESCRIPTION:Event reminder\\, with comma\\nand line feed\r\n' - >>> vevent = c.vevent.transformFromNative() - >>> vevent.rrule - - """, - - "Parsing tests" : - """ - >>> parseRDate = icalendar.MultiDateBehavior.transformToNative - >>> icalendar.stringToTextValues('') - [''] - >>> icalendar.stringToTextValues('abcd,efgh') - ['abcd', 'efgh'] - >>> icalendar.stringToPeriod("19970101T180000Z/19970102T070000Z") - (datetime.datetime(1997, 1, 1, 18, 0, tzinfo=tzutc()), datetime.datetime(1997, 1, 2, 7, 0, tzinfo=tzutc())) - >>> icalendar.stringToPeriod("19970101T180000Z/PT1H") - (datetime.datetime(1997, 1, 1, 18, 0, tzinfo=tzutc()), datetime.timedelta(0, 3600)) - >>> parseRDate(base.textLineToContentLine("RDATE;VALUE=DATE:19970304,19970504,19970704,19970904")) - - >>> parseRDate(base.textLineToContentLine("RDATE;VALUE=PERIOD:19960403T020000Z/19960403T040000Z,19960404T010000Z/PT3H")) - - """, - - "read failure" : - """ - >>> vevent = base.readOne(badstream) - Traceback (most recent call last): - ... - ParseError: At line 11: TRIGGER with no VALUE not recognized as DURATION or as DATE-TIME - >>> cal = base.readOne(badLineTest) - Traceback (most recent call last): - ... - ParseError: At line 6: Failed to parse line: X-BAD/SLASH:TRUE - >>> cal = base.readOne(badLineTest, ignoreUnreadable=True) - >>> cal.vevent.x_bad_slash - Traceback (most recent call last): - ... - AttributeError: x_bad_slash - >>> cal.vevent.x_bad_underscore - - """, - - "ical trigger workaround" : - """ - - >>> badical = base.readOne(icalWeirdTrigger) - >>> badical.vevent.valarm.description.value - u'This trigger is a date-time without a VALUE=DATE-TIME parameter' - >>> badical.vevent.valarm.trigger.value - datetime.datetime(2002, 10, 28, 12, 0, tzinfo=tzutc()) - """, - - "unicode test" : - r""" - >>> f = resource_stream(__name__, 'test_files/utf8_test.ics') - >>> vevent = base.readOne(f).vevent - >>> vevent.summary.value - u'The title \u3053\u3093\u306b\u3061\u306f\u30ad\u30c6\u30a3' - >>> summary = vevent.summary.value - >>> test = str(vevent.serialize()), - """, - - # make sure date valued UNTILs in rrules are in a reasonable timezone, - # and include that day (12/28 in this test) - "recurrence test" : - r""" - >>> f = resource_stream(__name__, 'test_files/recurrence.ics') - >>> cal = base.readOne(f) - >>> dates = list(cal.vevent.rruleset) - >>> dates[0] - datetime.datetime(2006, 1, 26, 23, 0, tzinfo=tzutc()) - >>> dates[1] - datetime.datetime(2006, 2, 23, 23, 0, tzinfo=tzutc()) - >>> dates[-1] - datetime.datetime(2006, 12, 28, 23, 0, tzinfo=tzutc()) - """, - - - "regular expression test" : - """ - >>> re.findall(base.patterns['name'], '12foo-bar:yay') - ['12foo-bar', 'yay'] - >>> re.findall(base.patterns['safe_char'], 'a;b"*,cd') - ['a', 'b', '*', 'c', 'd'] - >>> re.findall(base.patterns['qsafe_char'], 'a;b"*,cd') - ['a', ';', 'b', '*', ',', 'c', 'd'] - >>> re.findall(base.patterns['param_value'], '"quoted";not-quoted;start"after-illegal-quote', re.VERBOSE) - ['"quoted"', '', 'not-quoted', '', 'start', '', 'after-illegal-quote', ''] - >>> match = base.line_re.match('TEST;ALTREP="http://www.wiz.org":value:;"') - >>> match.group('value') - 'value:;"' - >>> match.group('name') - 'TEST' - >>> match.group('params') - ';ALTREP="http://www.wiz.org"' - """, - - "VTIMEZONE creation test:" : - - """ - >>> f = StringIO.StringIO(timezones) - >>> tzs = dateutil.tz.tzical(f) - >>> tzs.get("US/Pacific") - - >>> icalendar.TimezoneComponent(_) - > - >>> pacific = _ - >>> print pacific.serialize() - BEGIN:VTIMEZONE - TZID:US/Pacific - BEGIN:STANDARD - DTSTART:20001029T020000 - RRULE:FREQ=YEARLY;BYDAY=-1SU;BYMONTH=10 - TZNAME:PST - TZOFFSETFROM:-0700 - TZOFFSETTO:-0800 - END:STANDARD - BEGIN:DAYLIGHT - DTSTART:20000402T020000 - RRULE:FREQ=YEARLY;BYDAY=1SU;BYMONTH=4 - TZNAME:PDT - TZOFFSETFROM:-0800 - TZOFFSETTO:-0700 - END:DAYLIGHT - END:VTIMEZONE - >>> (_) - > - >>> santiago = icalendar.TimezoneComponent(tzs.get('Santiago')) - >>> ser = santiago.serialize() - >>> print ser - BEGIN:VTIMEZONE - TZID:Santiago - BEGIN:STANDARD - DTSTART:20000311T000000 - RRULE:FREQ=YEARLY;BYDAY=2SA;BYMONTH=3 - TZNAME:Pacific SA Standard Time - TZOFFSETFROM:-0300 - TZOFFSETTO:-0400 - END:STANDARD - BEGIN:DAYLIGHT - DTSTART:20001014T000000 - RRULE:FREQ=YEARLY;BYDAY=2SA;BYMONTH=10 - TZNAME:Pacific SA Daylight Time - TZOFFSETFROM:-0400 - TZOFFSETTO:-0300 - END:DAYLIGHT - END:VTIMEZONE - >>> roundtrip = dateutil.tz.tzical(StringIO.StringIO(str(ser))).get() - >>> for year in range(2001, 2010): - ... for month in (2, 9): - ... dt = datetime.datetime(year, month, 15, tzinfo = roundtrip) - ... if dt.replace(tzinfo=tzs.get('Santiago')) != dt: - ... print "Failed for:", dt - >>> fict = icalendar.TimezoneComponent(tzs.get('US/Fictitious-Eastern')) - >>> print fict.serialize() - BEGIN:VTIMEZONE - TZID:US/Fictitious-Eastern - BEGIN:STANDARD - DTSTART:20001029T020000 - RRULE:FREQ=YEARLY;BYDAY=-1SU;BYMONTH=10 - TZNAME:EST - TZOFFSETFROM:-0400 - TZOFFSETTO:-0500 - END:STANDARD - BEGIN:DAYLIGHT - DTSTART:20000402T020000 - RRULE:FREQ=YEARLY;BYDAY=1SU;BYMONTH=4;UNTIL=20050403T070000Z - TZNAME:EDT - TZOFFSETFROM:-0500 - TZOFFSETTO:-0400 - END:DAYLIGHT - END:VTIMEZONE - """, - - "Create iCalendar from scratch" : - - """ - >>> cal = base.newFromBehavior('vcalendar', '2.0') - >>> cal.add('vevent') - - >>> cal.vevent.add('dtstart').value = datetime.datetime(2006, 5, 9) - >>> cal.vevent.add('description').value = "Test event" - >>> pacific = dateutil.tz.tzical(StringIO.StringIO(timezones)).get('US/Pacific') - >>> cal.vevent.add('created').value = datetime.datetime(2006, 1, 1, 10, tzinfo=pacific) - >>> cal.vevent.add('uid').value = "Not very random UID" - >>> print cal.serialize() - BEGIN:VCALENDAR - VERSION:2.0 - PRODID:-//PYVOBJECT//NONSGML Version 1//EN - BEGIN:VEVENT - UID:Not very random UID - DTSTART:20060509T000000 - CREATED:20060101T180000Z - DESCRIPTION:Test event - END:VEVENT - END:VCALENDAR - """, - - "Serializing with timezones test" : - - """ - >>> from dateutil.rrule import rrule, rruleset, WEEKLY, MONTHLY - >>> pacific = dateutil.tz.tzical(StringIO.StringIO(timezones)).get('US/Pacific') - >>> cal = base.Component('VCALENDAR') - >>> cal.setBehavior(icalendar.VCalendar2_0) - >>> ev = cal.add('vevent') - >>> ev.add('dtstart').value = datetime.datetime(2005, 10, 12, 9, tzinfo = pacific) - >>> set = rruleset() - >>> set.rrule(rrule(WEEKLY, interval=2, byweekday=[2,4], until=datetime.datetime(2005, 12, 15, 9))) - >>> set.rrule(rrule(MONTHLY, bymonthday=[-1,-5])) - >>> set.exdate(datetime.datetime(2005, 10, 14, 9, tzinfo = pacific)) - >>> ev.rruleset = set - >>> ev.add('duration').value = datetime.timedelta(hours=1) - >>> print cal.serialize() - BEGIN:VCALENDAR - VERSION:2.0 - PRODID:-//PYVOBJECT//NONSGML Version 1//EN - BEGIN:VTIMEZONE - TZID:US/Pacific - BEGIN:STANDARD - DTSTART:20001029T020000 - RRULE:FREQ=YEARLY;BYDAY=-1SU;BYMONTH=10 - TZNAME:PST - TZOFFSETFROM:-0700 - TZOFFSETTO:-0800 - END:STANDARD - BEGIN:DAYLIGHT - DTSTART:20000402T020000 - RRULE:FREQ=YEARLY;BYDAY=1SU;BYMONTH=4 - TZNAME:PDT - TZOFFSETFROM:-0800 - TZOFFSETTO:-0700 - END:DAYLIGHT - END:VTIMEZONE - BEGIN:VEVENT - UID:... - DTSTART;TZID=US/Pacific:20051012T090000 - DURATION:PT1H - EXDATE;TZID=US/Pacific:20051014T090000 - RRULE:FREQ=WEEKLY;BYDAY=WE,FR;INTERVAL=2;UNTIL=20051215T090000 - RRULE:FREQ=MONTHLY;BYMONTHDAY=-1,-5 - END:VEVENT - END:VCALENDAR - >>> apple = dateutil.tz.tzical(StringIO.StringIO(timezones)).get('America/Montreal') - >>> ev.dtstart.value = datetime.datetime(2005, 10, 12, 9, tzinfo = apple) - >>> print cal.serialize() - BEGIN:VCALENDAR - VERSION:2.0 - PRODID:-//PYVOBJECT//NONSGML Version 1//EN - BEGIN:VTIMEZONE - TZID:US/Pacific - BEGIN:STANDARD - DTSTART:20001029T020000 - RRULE:FREQ=YEARLY;BYDAY=-1SU;BYMONTH=10 - TZNAME:PST - TZOFFSETFROM:-0700 - TZOFFSETTO:-0800 - END:STANDARD - BEGIN:DAYLIGHT - DTSTART:20000402T020000 - RRULE:FREQ=YEARLY;BYDAY=1SU;BYMONTH=4 - TZNAME:PDT - TZOFFSETFROM:-0800 - TZOFFSETTO:-0700 - END:DAYLIGHT - END:VTIMEZONE - BEGIN:VTIMEZONE - TZID:America/Montreal - BEGIN:STANDARD - DTSTART:20000101T000000 - RRULE:FREQ=YEARLY;BYMONTH=1;UNTIL=20040101T050000Z - TZNAME:EST - TZOFFSETFROM:-0500 - TZOFFSETTO:-0500 - END:STANDARD - BEGIN:STANDARD - DTSTART:20051030T020000 - RRULE:FREQ=YEARLY;BYDAY=5SU;BYMONTH=10 - TZNAME:EST - TZOFFSETFROM:-0400 - TZOFFSETTO:-0500 - END:STANDARD - BEGIN:DAYLIGHT - DTSTART:20050403T070000 - RRULE:FREQ=YEARLY;BYDAY=1SU;BYMONTH=4;UNTIL=20050403T120000Z - TZNAME:EDT - TZOFFSETFROM:-0500 - TZOFFSETTO:-0400 - END:DAYLIGHT - END:VTIMEZONE - BEGIN:VEVENT - UID:... - DTSTART;TZID=America/Montreal:20051012T090000 - DURATION:PT1H - EXDATE;TZID=US/Pacific:20051014T090000 - RRULE:FREQ=WEEKLY;BYDAY=WE,FR;INTERVAL=2;UNTIL=20051215T090000 - RRULE:FREQ=MONTHLY;BYMONTHDAY=-1,-5 - END:VEVENT - END:VCALENDAR - """, - - "Handling DATE without a VALUE=DATE" : - - """ - >>> cal = base.readOne(badDtStartTest) - >>> cal.vevent.dtstart.value - datetime.date(2002, 10, 28) - """, - - "Serializing iCalendar to hCalendar" : - - """ - >>> cal = base.newFromBehavior('hcalendar') - >>> cal.behavior - - >>> pacific = dateutil.tz.tzical(StringIO.StringIO(timezones)).get('US/Pacific') - >>> cal.add('vevent') - - >>> cal.vevent.add('summary').value = "this is a note" - >>> cal.vevent.add('url').value = "http://microformats.org/code/hcalendar/creator" - >>> cal.vevent.add('dtstart').value = datetime.date(2006,2,27) - >>> cal.vevent.add('location').value = "a place" - >>> cal.vevent.add('dtend').value = datetime.date(2006,2,27) + datetime.timedelta(days = 2) - >>> event2 = cal.add('vevent') - >>> event2.add('summary').value = "Another one" - >>> event2.add('description').value = "The greatest thing ever!" - >>> event2.add('dtstart').value = datetime.datetime(1998, 12, 17, 16, 42, tzinfo = pacific) - >>> event2.add('location').value = "somewhere else" - >>> event2.add('dtend').value = event2.dtstart.value + datetime.timedelta(days = 6) - >>> hcal = cal.serialize() - >>> print hcal - - - this is a note: - Monday, February 27 - - Tuesday, February 28 - at a place - - - - Another one: - Thursday, December 17, 16:42 - - Wednesday, December 23, 16:42 - at somewhere else -
The greatest thing ever!
-
- """, - - "Generate UIDs automatically test:" : - - """ - >>> cal = base.newFromBehavior('vcalendar') - >>> cal.add('vevent').add('dtstart').value = datetime.datetime(2006,2,2,10) - >>> ser = cal.serialize() - >>> len(cal.vevent.uid_list) - 1 - """, - - "VCARD 3.0 parse test:" : - - r""" - >>> card = base.readOne(vcardtest) - >>> card.adr.value - - >>> print card.adr.value - Haight Street 512; - Escape, Test - Novosibirsk, 80214 - Gnuland - >>> card.org.value - [u'University of Novosibirsk, Department of Octopus Parthenogenesis'] - >>> print card.serialize() - BEGIN:VCARD - VERSION:3.0 - ACCOUNT;TYPE=HOME:010-1234567-05 - ADR;TYPE=HOME:;;Haight Street 512\;\nEscape\, Test;Novosibirsk;;80214;Gnul - and - BDAY;VALUE=date:02-10 - FN:Daffy Duck Knudson (with Bugs Bunny and Mr. Pluto) - N:Knudson;Daffy Duck (with Bugs Bunny and Mr. Pluto);;; - NICKNAME:gnat and gnu and pluto - ORG:University of Novosibirsk\, Department of Octopus Parthenogenesis - TEL;TYPE=HOME:+01-(0)2-765.43.21 - TEL;TYPE=CELL:+01-(0)5-555.55.55 - TEL;TYPE=HOME:+01-(0)2-876.54.32 - END:VCARD - """, - - "Multi-text serialization test:" : - - """ - >>> category = base.newFromBehavior('categories') - >>> category.value = ['Random category'] - >>> print category.serialize().strip() - CATEGORIES:Random category - >>> category.value.append('Other category') - >>> print category.serialize().strip() - CATEGORIES:Random category,Other category - """, - - "Semi-colon separated multi-text serialization test:" : - - """ - >>> requestStatus = base.newFromBehavior('request-status') - >>> requestStatus.value = ['5.1', 'Service unavailable'] - >>> print requestStatus.serialize().strip() - REQUEST-STATUS:5.1;Service unavailable - """, - - "vCard groups test:" : - - """ - >>> card = base.readOne(vcardWithGroups) - >>> card.group - u'home' - >>> card.tel.group - u'home' - >>> card.group = card.tel.group = 'new' - >>> card.tel.serialize().strip() - 'new.TEL;TYPE=fax,voice,msg:+49 3581 123456' - >>> card.serialize().splitlines()[0] - 'new.BEGIN:VCARD' - >>> dtstart = base.newFromBehavior('dtstart') - >>> dtstart.group = "badgroup" - >>> dtstart.serialize() - Traceback (most recent call last): - ... - VObjectError: " has a group, but this object doesn't support groups" - """, - - "Lowercase components test:" : - - """ - >>> card = base.readOne(lowercaseComponentNames) - >>> card.version - - """, - - "Default behavior test" : - - """ - >>> card = base.readOne(vcardWithGroups) - >>> base.getBehavior('note') == None - True - >>> card.note.behavior - - >>> print card.note.value - The Mayor of the great city of Goerlitz in the great country of Germany. - Next line. - """ - } diff --git a/tests.py b/tests.py new file mode 100644 index 0000000..14fa83d --- /dev/null +++ b/tests.py @@ -0,0 +1,745 @@ +#-*- coding: utf-8 -*- +from __future__ import print_function + +import datetime +import dateutil +import io +import re +import sys +import unittest + +from dateutil.tz import tzutc +from dateutil.rrule import rrule, rruleset, WEEKLY, MONTHLY + +from vobject import base +from vobject import icalendar + +from vobject.base import __behaviorRegistry as behavior_registry +from vobject.base import ContentLine, parseLine, ParseError +from vobject.base import readComponents, textLineToContentLine + +from vobject.change_tz import change_tz + +from vobject.icalendar import MultiDateBehavior, PeriodBehavior, RecurringComponent, utc +from vobject.icalendar import parseDtstart, stringToTextValues, stringToPeriod, timedeltaToString + +twoHours = datetime.timedelta(hours=2) + + +def get_test_file(path): + """ + Helper function to open and read test files. + """ + filepath = "test_files/{}".format(path) + if sys.version_info[0] < 3: + # On python 2, this library operates on bytes. + f = open(filepath, 'r') + else: + # On python 3, it operates on unicode. We need to specify an encoding for systems + # for which the preferred encoding isn't utf-8 (e.g windows). + f = open(filepath, 'r', encoding='utf-8') + text = f.read() + f.close() + return text + + +class TestCalendarSerializing(unittest.TestCase): + maxDiff = None + + def test_scratchbuild(self): + "CreateCalendar 2.0 format from scratch" + test_cal = get_test_file("simple_2_0_test.ics") + cal = base.newFromBehavior('vcalendar', '2.0') + cal.add('vevent') + cal.vevent.add('dtstart').value = datetime.datetime(2006, 5, 9) + cal.vevent.add('description').value = "Test event" + cal.vevent.add('created').value = datetime.datetime(2006, 1, 1, 10, tzinfo=dateutil.tz.tzical("test_files/timezones.ics").get('US/Pacific')) + cal.vevent.add('uid').value = "Not very random UID" + + # Note we're normalizing line endings, because no one got time for that. + self.assertEqual( + cal.serialize().replace('\r\n', '\n'), + test_cal.replace('\r\n', '\n') + ) + + def test_unicode(self): + test_cal = get_test_file("utf8_test.ics") + vevent = base.readOne(test_cal).vevent + vevent2 = base.readOne(vevent.serialize()) + self.assertEqual(str(vevent), str(vevent2)) + + self.assertEqual( + vevent.summary.value, + 'The title こんにちはキティ' + ) + + if sys.version_info[0] < 3: + test_cal = test_cal.decode('utf-8') + vevent = base.readOne(test_cal).vevent + vevent2 = base.readOne(vevent.serialize()) + self.assertEqual(str(vevent), str(vevent2)) + self.assertEqual( + vevent.summary.value, + 'The title こんにちはキティ' + ) + + def test_wrapping(self): + """ + Should support an input file with a long text field covering multiple lines + """ + test_journal = get_test_file("journal.ics") + vobj = base.readOne(test_journal) + vjournal = base.readOne(vobj.serialize()) + self.assertTrue('Joe, Lisa, and Bob' in vjournal.description.value) + self.assertTrue('Tuesday.\n2.' in vjournal.description.value) + + def test_multiline(self): + """ + Multi-text serialization test + """ + category = base.newFromBehavior('categories') + category.value = ['Random category'] + self.assertEqual( + category.serialize().strip(), + "CATEGORIES:Random category" + ) + + category.value.append('Other category') + self.assertEqual( + category.serialize().strip(), + "CATEGORIES:Random category,Other category" + ) + + def test_semicolon_separated(self): + """Semi-colon separated multi-text serialization test""" + requestStatus = base.newFromBehavior('request-status') + requestStatus.value = ['5.1', 'Service unavailable'] + self.assertEqual( + requestStatus.serialize().strip(), + "REQUEST-STATUS:5.1;Service unavailable" + ) + + def test_ical_to_hcal(self): + """ + Serializing iCalendar to hCalendar. + + Since Hcalendar is experimental and the behavior doesn't seem to want to load, + This test will have to wait. + + + tzs = dateutil.tz.tzical("test_files/timezones.ics") + cal = base.newFromBehavior('hcalendar') + self.assertEqual( + str(cal.behavior), + "" + ) + cal.add('vevent') + cal.vevent.add('summary').value = "this is a note" + cal.vevent.add('url').value = "http://microformats.org/code/hcalendar/creator" + cal.vevent.add('dtstart').value = datetime.date(2006,2,27) + cal.vevent.add('location').value = "a place" + cal.vevent.add('dtend').value = datetime.date(2006,2,27) + datetime.timedelta(days = 2) + + event2 = cal.add('vevent') + event2.add('summary').value = "Another one" + event2.add('description').value = "The greatest thing ever!" + event2.add('dtstart').value = datetime.datetime(1998, 12, 17, 16, 42, tzinfo = tzs.get('US/Pacific')) + event2.add('location').value = "somewhere else" + event2.add('dtend').value = event2.dtstart.value + datetime.timedelta(days = 6) + hcal = cal.serialize() + """ + #self.assertEqual( + # str(hcal), + # """ + # + # this is a note: + # Monday, February 27 + # - Tuesday, February 28 + # at a place + # + # + # + # Another one: + # Thursday, December 17, 16:42 + # - Wednesday, December 23, 16:42 + # at somewhere else + #
The greatest thing ever!
+ #
+ # """ + #) + + +class TestBehaviors(unittest.TestCase): + def test_general_behavior(self): + """ + Tests for behavior registry, getting and creating a behavior. + """ + # Check expected behavior registry. + self.assertEqual( + sorted(behavior_registry.keys()), + ['', 'ACTION', 'ADR', 'AVAILABLE', 'BUSYTYPE', 'CALSCALE', 'CATEGORIES', 'CLASS', 'COMMENT', 'COMPLETED', 'CONTACT', 'CREATED', 'DAYLIGHT', 'DESCRIPTION', 'DTEND', 'DTSTAMP', 'DTSTART', 'DUE', 'DURATION', 'EXDATE', 'EXRULE', 'FN', 'FREEBUSY', 'LABEL', 'LAST-MODIFIED', 'LOCATION', 'METHOD', 'N', 'ORG', 'PHOTO', 'PRODID', 'RDATE', 'RECURRENCE-ID', 'RELATED-TO', 'REQUEST-STATUS', 'RESOURCES', 'RRULE', 'STANDARD', 'STATUS', 'SUMMARY', 'TRANSP', 'TRIGGER', 'UID', 'VALARM', 'VAVAILABILITY', 'VCALENDAR', 'VCARD', 'VEVENT', 'VFREEBUSY', 'VJOURNAL', 'VTIMEZONE', 'VTODO'] + ) + + # test get_behavior + behavior = base.getBehavior('VCALENDAR') + self.assertEqual( + str(behavior), + "" + ) + self.assertTrue(behavior.isComponent) + + self.assertEqual( + base.getBehavior("invalid_name"), + None + ) + # test for ContentLine (not a component) + non_component_behavior = base.getBehavior('RDATE') + self.assertFalse(non_component_behavior.isComponent) + + def test_MultiDateBehavior(self): + parseRDate = MultiDateBehavior.transformToNative + self.assertEqual( + str(parseRDate(textLineToContentLine("RDATE;VALUE=DATE:19970304,19970504,19970704,19970904"))), + "" + ) + self.assertEqual( + str(parseRDate(textLineToContentLine("RDATE;VALUE=PERIOD:19960403T020000Z/19960403T040000Z,19960404T010000Z/PT3H"))), + "" + ) + + def test_periodBehavior(self): + line = ContentLine('test', [], '', isNative=True) + line.behavior = PeriodBehavior + line.value = [(datetime.datetime(2006, 2, 16, 10), twoHours)] + + self.assertEqual( + line.transformFromNative().value, + '20060216T100000/PT2H' + ) + self.assertEqual( + line.transformToNative().value, + [(datetime.datetime(2006, 2, 16, 10, 0), datetime.timedelta(0, 7200))] + ) + + line.value.append((datetime.datetime(2006, 5, 16, 10), twoHours)) + + self.assertEqual( + line.serialize().strip(), + 'TEST:20060216T100000/PT2H,20060516T100000/PT2H' + ) + +class TestVTodo(unittest.TestCase): + def test_vtodo(self): + vtodo = get_test_file("vtodo.ics") + obj = base.readOne(vtodo) + obj.vtodo.add('completed') + obj.vtodo.completed.value = datetime.datetime(2015,5,5,13,30) + self.assertEqual(obj.vtodo.completed.serialize()[0:23], 'COMPLETED:20150505T1330') + obj = base.readOne(obj.serialize()) + self.assertEqual(obj.vtodo.completed.value, datetime.datetime(2015,5,5,13,30)) + +class TestVobject(unittest.TestCase): + maxDiff = None + + @classmethod + def setUpClass(cls): + cls.simple_test_cal = get_test_file("simple_test.ics") + + def test_readComponents(self): + cal = next(readComponents(self.simple_test_cal)) + + self.assertEqual(str(cal), "]>]>") + self.assertEqual(str(cal.vevent.summary), "") + + def test_parseLine(self): + self.assertEqual(parseLine("BLAH:"), ('BLAH', [], '', None)) + self.assertEqual( + parseLine("RDATE:VALUE=DATE:19970304,19970504,19970704,19970904"), + ('RDATE', [], 'VALUE=DATE:19970304,19970504,19970704,19970904', None) + ) + self.assertEqual( + parseLine('DESCRIPTION;ALTREP="http://www.wiz.org":The Fall 98 Wild Wizards Conference - - Las Vegas, NV, USA'), + ('DESCRIPTION', [['ALTREP', 'http://www.wiz.org']], 'The Fall 98 Wild Wizards Conference - - Las Vegas, NV, USA', None) + ) + self.assertEqual( + parseLine("EMAIL;PREF;INTERNET:john@nowhere.com"), + ('EMAIL', [['PREF'], ['INTERNET']], 'john@nowhere.com', None) + ) + self.assertEqual( + parseLine('EMAIL;TYPE="blah",hah;INTERNET="DIGI",DERIDOO:john@nowhere.com'), + ('EMAIL', [['TYPE', 'blah', 'hah'], ['INTERNET', 'DIGI', 'DERIDOO']], 'john@nowhere.com', None) + ) + self.assertEqual( + parseLine('item1.ADR;type=HOME;type=pref:;;Reeperbahn 116;Hamburg;;20359;'), + ('ADR', [['type', 'HOME'], ['type', 'pref']], ';;Reeperbahn 116;Hamburg;;20359;', 'item1') + ) + self.assertRaises(ParseError, parseLine, ":") + + +class TestGeneralFileParsing(unittest.TestCase): + """ + General tests for parsing ics files. + """ + def test_readOne(self): + cal = get_test_file("silly_test.ics") + silly = base.readOne(cal, findBegin=False) + self.assertEqual( + str(silly), + ", , ]>" + ) + self.assertEqual( + str(silly.stuff), + "" + ) + + def test_importing(self): + cal = get_test_file("standard_test.ics") + c = base.readOne(cal, validate=True) + self.assertEqual( + str(c.vevent.valarm.trigger), + "" + ) + + self.assertEqual( + str(c.vevent.dtstart.value), + "2002-10-28 14:00:00-08:00" + ) + self.assertTrue( + isinstance(c.vevent.dtstart.value, datetime.datetime) + ) + self.assertEqual( + str(c.vevent.dtend.value), + "2002-10-28 15:00:00-08:00" + ) + self.assertTrue( + isinstance(c.vevent.dtend.value, datetime.datetime) + ) + self.assertEqual( + c.vevent.dtstamp.value, + datetime.datetime(2002, 10, 28, 1, 17, 6, tzinfo=tzutc()) + ) + + vevent = c.vevent.transformFromNative() + self.assertEqual( + str(vevent.rrule), + "" + ) + + def test_bad_stream(self): + cal = get_test_file("badstream.ics") + self.assertRaises(ParseError, base.readOne, cal) + + def test_bad_line(self): + cal = get_test_file("badline.ics") + self.assertRaises(ParseError, base.readOne, cal) + + newcal = base.readOne(cal, ignoreUnreadable=True) + self.assertEqual( + str(newcal.vevent.x_bad_underscore), + '' + ) + + def test_parseParams(self): + self.assertEqual( + base.parseParams(';ALTREP="http://www.wiz.org"'), + [['ALTREP', 'http://www.wiz.org']] + ) + self.assertEqual( + base.parseParams(';ALTREP="http://www.wiz.org;;",Blah,Foo;NEXT=Nope;BAR'), + [['ALTREP', 'http://www.wiz.org;;', 'Blah', 'Foo'], ['NEXT', 'Nope'], ['BAR']] + ) + + +class TestVcards(unittest.TestCase): + + @classmethod + def setUpClass(cls): + cls.test_file = get_test_file("vcard_with_groups.ics") + cls.card = base.readOne(cls.test_file) + + def test_vcard_creation(self): + vcard = base.newFromBehavior('vcard', '3.0') + self.assertEqual( + str(vcard), + "" + ) + + def test_default_behavior(self): + """ + Default behavior test. + """ + card = self.card + self.assertEqual( + base.getBehavior('note'), + None + ) + self.assertEqual( + str(card.note.value), + "The Mayor of the great city of Goerlitz in the great country of Germany.\nNext line." + ) + + def test_with_groups(self): + """ + vCard groups test + """ + card = self.card + self.assertEqual( + str(card.group), + 'home' + ) + self.assertEqual( + str(card.tel.group), + 'home' + ) + + card.group = card.tel.group = 'new' + self.assertEqual( + str(card.tel.serialize().strip()), + 'new.TEL;TYPE=fax,voice,msg:+49 3581 123456' + ) + self.assertEqual( + str(card.serialize().splitlines()[0]), + 'new.BEGIN:VCARD' + ) + + + def test_vcard_3_parsing(self): + """ + VCARD 3.0 parse test + """ + test_file = get_test_file("simple_3_0_test.ics") + card = base.readOne(test_file, findBegin=False) + # value not rendering correctly? + #self.assertEqual( + # card.adr.value, + # "" + #) + self.assertEqual( + card.org.value, + "University of Novosibirsk, Department of Octopus Parthenogenesis" + ) + + +class TestIcalendar(unittest.TestCase): + """ + Tests for icalendar.py + """ + maxDiff = None + def test_parseDTStart(self): + """ + Should take a content line and return a datetime object. + """ + self.assertEqual( + parseDtstart(textLineToContentLine("DTSTART:20060509T000000")), + datetime.datetime(2006, 5, 9, 0, 0) + ) + + def test_regexes(self): + self.assertEqual( + re.findall(base.patterns['name'], '12foo-bar:yay'), + ['12foo-bar', 'yay'] + ) + self.assertEqual( + re.findall(base.patterns['safe_char'], 'a;b"*,cd'), + ['a', 'b', '*', 'c', 'd'] + ) + self.assertEqual( + re.findall(base.patterns['qsafe_char'], 'a;b"*,cd'), + ['a', ';', 'b', '*', ',', 'c', 'd'] + ) + self.assertEqual( + re.findall(base.patterns['param_value'], '"quoted";not-quoted;start"after-illegal-quote', re.VERBOSE), + ['"quoted"', '', 'not-quoted', '', 'start', '', 'after-illegal-quote', ''] + ) + match = base.line_re.match('TEST;ALTREP="http://www.wiz.org":value:;"') + self.assertEqual( + match.group('value'), + 'value:;"' + ) + self.assertEqual( + match.group('name'), + 'TEST' + ) + self.assertEqual( + match.group('params'), + ';ALTREP="http://www.wiz.org"' + ) + + def test_stringToTextValues(self): + self.assertEqual( + stringToTextValues(''), + [''] + ) + self.assertEqual( + stringToTextValues('abcd,efgh'), + ['abcd', 'efgh'] + ) + + def test_stringToPeriod(self): + self.assertEqual( + stringToPeriod("19970101T180000Z/19970102T070000Z"), + (datetime.datetime(1997, 1, 1, 18, 0, tzinfo=tzutc()), datetime.datetime(1997, 1, 2, 7, 0, tzinfo=tzutc())) + ) + self.assertEqual( + stringToPeriod("19970101T180000Z/PT1H"), + (datetime.datetime(1997, 1, 1, 18, 0, tzinfo=tzutc()), datetime.timedelta(0, 3600)) + ) + + def test_timedeltaToString(self): + self.assertEqual( + timedeltaToString(twoHours), + 'PT2H' + ) + self.assertEqual( + timedeltaToString(datetime.timedelta(minutes=20)), + 'PT20M' + ) + + def test_vtimezone_creation(self): + tzs = dateutil.tz.tzical("test_files/timezones.ics") + pacific = icalendar.TimezoneComponent(tzs.get('US/Pacific')) + self.assertEqual( + str(pacific), + ">" + ) + santiago = icalendar.TimezoneComponent(tzs.get('Santiago')) + self.assertEqual( + str(santiago), + ">" + ) + for year in range(2001, 2010): + for month in (2, 9): + dt = datetime.datetime(year, month, 15, tzinfo = tzs.get('Santiago')) + #if dt.replace(tzinfo=tzs.get('Santiago')) != dt: + self.assertTrue(dt.replace(tzinfo=tzs.get('Santiago')), dt) + + def test_timezone_serializing(self): + """ + Serializing with timezones test + """ + tzs = dateutil.tz.tzical("test_files/timezones.ics") + pacific = tzs.get('US/Pacific') + cal = base.Component('VCALENDAR') + cal.setBehavior(icalendar.VCalendar2_0) + ev = cal.add('vevent') + ev.add('dtstart').value = datetime.datetime(2005, 10, 12, 9, tzinfo = pacific) + evruleset = rruleset() + evruleset.rrule(rrule(WEEKLY, interval=2, byweekday=[2,4], until=datetime.datetime(2005, 12, 15, 9))) + evruleset.rrule(rrule(MONTHLY, bymonthday=[-1,-5])) + evruleset.exdate(datetime.datetime(2005, 10, 14, 9, tzinfo = pacific)) + ev.rruleset = evruleset + ev.add('duration').value = datetime.timedelta(hours=1) + + # breaking date? + #self.assertEqual( + # cal.serialize().replace('\r\n', '\n'), + # """BEGIN:VCALENDAR\nVERSION:2.0\nPRODID:-//PYVOBJECT//NONSGML Version 1//EN\nBEGIN:VTIMEZONE\nTZID:US/Pacific\nBEGIN:STANDARD\nDTSTART:20001029T020000\nRRULE:FREQ=YEARLY;BYDAY=-1SU;BYMONTH=10\nTZNAME:PST\nTZOFFSETFROM:-0700\nTZOFFSETTO:-0800\nEND:STANDARD\nBEGIN:DAYLIGHT\nDTSTART:20000402T020000\nRRULE:FREQ=YEARLY;BYDAY=1SU;BYMONTH=4\nTZNAME:PDT\nTZOFFSETFROM:-0800\nTZOFFSETTO:-0700\nEND:DAYLIGHT\nEND:VTIMEZONE\nBEGIN:VEVENT\nUID:20150108T142459Z - 64333@testing-worker-linux-12-2-29839-linux-6-46319\n358\nDTSTART;TZID=US/Pacific:20051012T090000\nDURATION:PT1H\nEXDATE;TZID=US/Pacific:20051014T090000\nRRULE:FREQ=WEEKLY;BYDAY=WE,FR;INTERVAL=2;UNTIL=20051215T090000\nRRULE:FREQ=MONTHLY;BYMONTHDAY=-5,-1\nEND:VEVENT\nEND:VCALENDAR\n""" + #) + + apple = tzs.get('America/Montreal') + ev.dtstart.value = datetime.datetime(2005, 10, 12, 9, tzinfo = apple) + #self.assertEqual( + # cal.serialize().replace('\r\n', ''), + # """BEGIN:VCALENDAR\nVERSION:2.0\nPRODID:-//PYVOBJECT//NONSGML Version 1//EN\nBEGIN:VTIMEZONE\nTZID:America/Montreal\nBEGIN:STANDARD\nDTSTART:20000101T000000\nRRULE:FREQ=YEARLY;BYMONTH=1;UNTIL=20040101T050000Z\nTZNAME:EST\nTZOFFSETFROM:-0500\nTZOFFSETTO:-0500\nEND:STANDARD\nBEGIN:STANDARD\nDTSTART:20051030T020000\nRRULE:FREQ=YEARLY;BYDAY=5SU;BYMONTH=10\nTZNAME:EST\nTZOFFSETFROM:-0400\nTZOFFSETTO:-0500\nEND:STANDARD\nBEGIN:DAYLIGHT\nDTSTART:20050403T070000\nRRULE:FREQ=YEARLY;BYDAY=1SU;BYMONTH=4;UNTIL=20050403T120000Z\nTZNAME:EDT\nTZOFFSETFROM:-0500\nTZOFFSETTO:-0400\nEND:DAYLIGHT\nEND:VTIMEZONE\nBEGIN:VEVENT\nUID:20150108T164047Z - 11645@testing-worker-linux-12-1-29784-linux-12-4633\n5445\nDTSTART;TZID=America/Montreal:20051012T090000\nDURATION:PT1H\nEXDATE;TZID=US/Pacific:20051014T090000\nRRULE:FREQ=WEEKLY;BYDAY=WE,FR;INTERVAL=2;UNTIL=20051215T090000\nRRULE:FREQ=MONTHLY;BYMONTHDAY=-5,-1\nEND:VEVENT\nEND:VCALENDAR\n""" + #) + + def test_freeBusy(self): + test_cal = get_test_file("freebusy.ics") + + vfb = base.newFromBehavior('VFREEBUSY') + vfb.add('uid').value = 'test' + vfb.add('dtstart').value = datetime.datetime(2006, 2, 16, 1, tzinfo=utc) + vfb.add('dtend').value = vfb.dtstart.value + twoHours + vfb.add('freebusy').value = [(vfb.dtstart.value, twoHours / 2)] + vfb.add('freebusy').value = [(vfb.dtstart.value, vfb.dtend.value)] + + self.assertEqual( + vfb.serialize().replace('\r\n', '\n'), + test_cal.replace('\r\n', '\n') + ) + + def test_availablity(self): + test_cal = get_test_file("availablity.ics") + + vcal = base.newFromBehavior('VAVAILABILITY') + vcal.add('uid').value = 'test' + vcal.add('dtstamp').value = datetime.datetime(2006, 2, 15, 0, tzinfo=utc) + vcal.add('dtstart').value = datetime.datetime(2006, 2, 16, 0, tzinfo=utc) + vcal.add('dtend').value = datetime.datetime(2006, 2, 17, 0, tzinfo=utc) + vcal.add('busytype').value = "BUSY" + + av = base.newFromBehavior('AVAILABLE') + av.add('uid').value = 'test1' + av.add('dtstamp').value = datetime.datetime(2006, 2, 15, 0, tzinfo=utc) + av.add('dtstart').value = datetime.datetime(2006, 2, 16, 9, tzinfo=utc) + av.add('dtend').value = datetime.datetime(2006, 2, 16, 12, tzinfo=utc) + av.add('summary').value = "Available in the morning" + + vcal.add(av) + + self.assertEqual( + vcal.serialize().replace('\r\n', '\n'), + test_cal.replace('\r\n', '\n') + ) + + def test_recurrence(self): + # Ensure date valued UNTILs in rrules are in a reasonable timezone, + # and include that day (12/28 in this test) + test_file = get_test_file("recurrence.ics") + cal = base.readOne(test_file, findBegin=False) + dates = list(cal.vevent.getrruleset()) + self.assertEqual( + dates[0], + datetime.datetime(2006, 1, 26, 23, 0, tzinfo=tzutc()) + ) + self.assertEqual( + dates[1], + datetime.datetime(2006, 2, 23, 23, 0, tzinfo=tzutc()) + ) + self.assertEqual( + dates[-1], + datetime.datetime(2006, 12, 28, 23, 0, tzinfo=tzutc()) + ) + + def test_recurring_component(self): + vevent = RecurringComponent(name='VEVENT') + + # init + self.assertTrue(vevent.isNative) + + # rruleset should be None at this point. + # No rules have been passed or created. + self.assertEqual(vevent.rruleset, None) + + # Now add start and rule for recurring event + vevent.add('dtstart').value = datetime.datetime(2005, 1, 19, 9) + vevent.add('rrule').value =u"FREQ=WEEKLY;COUNT=2;INTERVAL=2;BYDAY=TU,TH" + self.assertEqual( + list(vevent.rruleset), + [datetime.datetime(2005, 1, 20, 9, 0), datetime.datetime(2005, 2, 1, 9, 0)] + ) + self.assertEqual( + list(vevent.getrruleset(addRDate=True)), + [datetime.datetime(2005, 1, 19, 9, 0), datetime.datetime(2005, 1, 20, 9, 0)] + ) + + # Also note that dateutil will expand all-day events (datetime.date values) + # to datetime.datetime value with time 0 and no timezone. + vevent.dtstart.value = datetime.date(2005,3,18) + self.assertEqual( + list(vevent.rruleset), + [datetime.datetime(2005, 3, 29, 0, 0), datetime.datetime(2005, 3, 31, 0, 0)] + ) + self.assertEqual( + list(vevent.getrruleset(True)), + [datetime.datetime(2005, 3, 18, 0, 0), datetime.datetime(2005, 3, 29, 0, 0)] + ) + + +class TestChangeTZ(unittest.TestCase): + """Tests for change_tz.change_tz""" + + class StubCal(object): + class StubEvent(object): + class Node(object): + def __init__(self, value): + self.value = value + + def __init__(self, dtstart, dtend): + self.dtstart = self.Node(dtstart) + self.dtend = self.Node(dtend) + + def __init__(self, dates): + """ dates is a list of tuples (dtstart, dtend) """ + self.vevent_list = [self.StubEvent(*d) for d in dates] + + def test_change_tz(self): + """Change the timezones of events in a component to a different + timezone""" + + # Setup - create a stub vevent list + old_tz = dateutil.tz.gettz('UTC') # 0:00 + new_tz = dateutil.tz.gettz('America/Chicago') # -5:00 + + dates = [ + (datetime.datetime(1999, 12, 31, 23, 59, 59, 0, tzinfo=old_tz), + datetime.datetime(2000, 1, 1, 0, 0, 0, 0, tzinfo=old_tz)), + (datetime.datetime(2010, 12, 31, 23, 59, 59, 0, tzinfo=old_tz), + datetime.datetime(2011, 1, 2, 3, 0, 0, 0, tzinfo=old_tz))] + + cal = self.StubCal(dates) + + # Exercise - change the timezone + change_tz(cal, new_tz, dateutil.tz.gettz('UTC')) + + # Test - that the tzs were converted correctly + expected_new_dates = [ + (datetime.datetime(1999, 12, 31, 17, 59, 59, 0, tzinfo=new_tz), + datetime.datetime(1999, 12, 31, 18, 0, 0, 0, tzinfo=new_tz)), + (datetime.datetime(2010, 12, 31, 17, 59, 59, 0, tzinfo=new_tz), + datetime.datetime(2011, 1, 1, 21, 0, 0, 0, tzinfo=new_tz))] + + for vevent, expected_datepair in zip(cal.vevent_list, + expected_new_dates): + self.assertEqual(vevent.dtstart.value, expected_datepair[0]) + self.assertEqual(vevent.dtend.value, expected_datepair[1]) + + def test_change_tz_utc_only(self): + """Change any UTC timezones of events in a component to a different + timezone""" + + # Setup - create a stub vevent list + utc_tz = dateutil.tz.gettz('UTC') # 0:00 + non_utc_tz = dateutil.tz.gettz('America/Santiago') # -4:00 + new_tz = dateutil.tz.gettz('America/Chicago') # -5:00 + + dates = [ + (datetime.datetime(1999, 12, 31, 23, 59, 59, 0, tzinfo=utc_tz), + datetime.datetime(2000, 1, 1, 0, 0, 0, 0, tzinfo=non_utc_tz))] + + cal = self.StubCal(dates) + + # Exercise - change the timezone passing utc_only=True + change_tz(cal, new_tz, dateutil.tz.gettz('UTC'), utc_only=True) + + # Test - that only the utc item has changed + expected_new_dates = [ + (datetime.datetime(1999, 12, 31, 17, 59, 59, 0, tzinfo=new_tz), + dates[0][1])] + + for vevent, expected_datepair in zip(cal.vevent_list, + expected_new_dates): + self.assertEqual(vevent.dtstart.value, expected_datepair[0]) + self.assertEqual(vevent.dtend.value, expected_datepair[1]) + + def test_change_tz_default(self): + """Change the timezones of events in a component to a different + timezone, passing a default timezone that is assumed when the events + don't have one""" + + # Setup - create a stub vevent list + old_tz = dateutil.tz.gettz('UTC') # 0:00 + new_tz = dateutil.tz.gettz('America/Chicago') # -5:00 + + dates = [ + (datetime.datetime(1999, 12, 31, 23, 59, 59, 0, tzinfo=None), + datetime.datetime(2000, 1, 1, 0, 0, 0, 0, tzinfo=None))] + + cal = self.StubCal(dates) + + # Exercise - change the timezone + change_tz(cal, new_tz, dateutil.tz.gettz('UTC')) + + # Test - that the tzs were converted correctly + expected_new_dates = [ + (datetime.datetime(1999, 12, 31, 17, 59, 59, 0, tzinfo=new_tz), + datetime.datetime(1999, 12, 31, 18, 0, 0, 0, tzinfo=new_tz))] + + for vevent, expected_datepair in zip(cal.vevent_list, + expected_new_dates): + self.assertEqual(vevent.dtstart.value, expected_datepair[0]) + self.assertEqual(vevent.dtend.value, expected_datepair[1]) + + +if __name__ == '__main__': + unittest.main() diff --git a/vobject/__init__.py b/vobject/__init__.py index d5daf30..30ba3f0 100644 --- a/vobject/__init__.py +++ b/vobject/__init__.py @@ -22,7 +22,7 @@ L{Component}s. To validate, an object must have all required children. There (TODO: will be) a toggle to raise an exception or just log unrecognized, non-experimental children and parameters. - + Creating objects programatically -------------------------------- A L{Component} can be created from scratch. No encoding @@ -31,7 +31,7 @@ Serializing objects ------------------- - Serialization: + Serialization: - Looks for missing required children that can be automatically generated, like a UID or a PRODID, and adds them - Encodes all values that can be automatically encoded @@ -39,10 +39,10 @@ explicitly disabled) - Appends the serialized object to a buffer, or fills a new buffer and returns it - + Examples -------- - + >>> import datetime >>> import dateutil.rrule as rrule >>> x = iCalendar() @@ -73,14 +73,14 @@ RRULE:FREQ=WEEKLY;COUNT=2 END:VEVENT END:VCALENDAR - + """ -import base, icalendar, vcard -from base import readComponents, readOne, newFromBehavior +from .base import newFromBehavior, readOne, readComponents +from . import icalendar, vcard def iCalendar(): return newFromBehavior('vcalendar', '2.0') def vCard(): - return newFromBehavior('vcard', '3.0') \ No newline at end of file + return newFromBehavior('vcard', '3.0') diff --git a/vobject/base.py b/vobject/base.py index 40baf1e..b8ca6d8 100644 --- a/vobject/base.py +++ b/vobject/base.py @@ -1,13 +1,32 @@ """vobject module for reading vCard and vCalendar files.""" +from __future__ import print_function + import copy +import logging import re +import six import sys -import logging -import StringIO, cStringIO -import string -import exceptions -import codecs + +#------------------------------------ Python 2/3 compatibility challenges ----- +# Python 3 no longer has a basestring type, so.... +try: + basestring = basestring +except NameError: + basestring = (str,bytes) + +## One more problem ... in python2 the str operator breaks on unicode +## objects containing non-ascii characters +try: + unicode + def str_(s): + if type(s) == unicode: + return s.encode('utf-8') + else: + return str(s) +except NameError: + def str_(s): + return s #------------------------------------ Logging ---------------------------------- logger = logging.getLogger(__name__) @@ -18,6 +37,7 @@ logger.addHandler(handler) logger.setLevel(logging.ERROR) # Log errors DEBUG = False # Don't waste time on debug calls + #----------------------------------- Constants --------------------------------- CR = '\r' LF = '\n' @@ -25,20 +45,14 @@ SPACE = ' ' TAB = '\t' SPACEORTAB = SPACE + TAB -#-------------------------------- Useful modules ------------------------------- -# use doctest, it kills two birds with one stone and docstrings often become -# more readable to boot (see parseLine's docstring). -# use logging, then when debugging we can just set our verbosity. -# use epydoc syntax for documenting code, please document every class and non- -# trivial method (see http://epydoc.sourceforge.net/epytext.html -# and http://epydoc.sourceforge.net/fields.html). Also, please -# follow http://www.python.org/peps/pep-0257.html for docstrings. -#------------------------------------------------------------------------------- #--------------------------------- Main classes -------------------------------- + + class VBase(object): - """Base class for ContentLine and Component. - + """ + Base class for ContentLine and Component. + @ivar behavior: The Behavior class associated with this object, which controls validation, transformations, and encoding. @@ -47,43 +61,53 @@ class VBase(object): @ivar isNative: Boolean describing whether this component is a Native instance. @ivar group: - An optional group prefix, should be used only to indicate sort order in - vCards, according to RFC2426 + An optional group prefix, should be used only to indicate sort order in + vCards, according to spec. + + Current spec: 4.0 (http://tools.ietf.org/html/rfc6350) """ def __init__(self, group=None, *args, **kwds): super(VBase, self).__init__(*args, **kwds) - self.group = group - self.behavior = None + self.group = group + self.behavior = None self.parentBehavior = None self.isNative = False - + def copy(self, copyit): self.group = copyit.group self.behavior = copyit.behavior self.parentBehavior = copyit.parentBehavior self.isNative = copyit.isNative - + def validate(self, *args, **kwds): - """Call the behavior's validate method, or return True.""" + """ + Call the behavior's validate method, or return True. + """ if self.behavior: return self.behavior.validate(self, *args, **kwds) - else: return True + return True def getChildren(self): - """Return an iterable containing the contents of the object.""" + """ + Return an iterable containing the contents of the object. + """ return [] def clearBehavior(self, cascade=True): - """Set behavior to None. Do for all descendants if cascading.""" + """ + Set behavior to None. Do for all descendants if cascading. + """ self.behavior=None - if cascade: self.transformChildrenFromNative() + if cascade: + self.transformChildrenFromNative() def autoBehavior(self, cascade=False): - """Set behavior if name is in self.parentBehavior.knownChildren. - + """ + Set behavior if name is in self.parentBehavior.knownChildren. + If cascade is True, unset behavior and parentBehavior for all descendants, then recalculate behavior and parentBehavior. - + """ parentBehavior = self.parentBehavior if parentBehavior is not None: @@ -95,62 +119,65 @@ def autoBehavior(self, cascade=False): if isinstance(self, ContentLine) and self.encoded: self.behavior.decode(self) elif isinstance(self, ContentLine): - self.behavior = parentBehavior.defaultBehavior + self.behavior = parentBehavior.defaultBehavior if self.encoded and self.behavior: self.behavior.decode(self) def setBehavior(self, behavior, cascade=True): - """Set behavior. If cascade is True, autoBehavior all descendants.""" - self.behavior=behavior + """ + Set behavior. If cascade is True, autoBehavior all descendants. + """ + self.behavior = behavior if cascade: for obj in self.getChildren(): - obj.parentBehavior=behavior + obj.parentBehavior = behavior obj.autoBehavior(True) def transformToNative(self): - """Transform this object into a custom VBase subclass. - + """ + Transform this object into a custom VBase subclass. + transformToNative should always return a representation of this object. It may do so by modifying self in place then returning self, or by creating a new object. - + """ if self.isNative or not self.behavior or not self.behavior.hasNative: return self else: try: return self.behavior.transformToNative(self) - except Exception, e: + except Exception as e: # wrap errors in transformation in a ParseError lineNumber = getattr(self, 'lineNumber', None) + if isinstance(e, ParseError): if lineNumber is not None: e.lineNumber = lineNumber raise else: - msg = "In transformToNative, unhandled exception: %s: %s" - msg = msg % (sys.exc_info()[0], sys.exc_info()[1]) - new_error = ParseError(msg, lineNumber) - raise ParseError, new_error, sys.exc_info()[2] - + msg = "In transformToNative, unhandled exception on line %s: %s: %s" + msg = msg % (lineNumber, sys.exc_info()[0], sys.exc_info()[1]) + raise ParseError(msg, lineNumber) def transformFromNative(self): - """Return self transformed into a ContentLine or Component if needed. - + """ + Return self transformed into a ContentLine or Component if needed. + May have side effects. If it does, transformFromNative and transformToNative MUST have perfectly inverse side effects. Allowing such side effects is convenient for objects whose transformations only change a few attributes. - + Note that it isn't always possible for transformFromNative to be a perfect inverse of transformToNative, in such cases transformFromNative should return a new object, not self after modifications. - + """ if self.isNative and self.behavior and self.behavior.hasNative: try: return self.behavior.transformFromNative(self) - except Exception, e: + except Exception as e: # wrap errors in transformation in a NativeError lineNumber = getattr(self, 'lineNumber', None) if isinstance(e, NativeError): @@ -158,11 +185,11 @@ def transformFromNative(self): e.lineNumber = lineNumber raise else: - msg = "In transformFromNative, unhandled exception: %s: %s" - msg = msg % (sys.exc_info()[0], sys.exc_info()[1]) - new_error = NativeError(msg, lineNumber) - raise NativeError, new_error, sys.exc_info()[2] - else: return self + msg = "In transformFromNative, unhandled exception on line %s %s: %s" + msg = msg % (lineNumber, sys.exc_info()[0], sys.exc_info()[1]) + raise NativeError(msg, lineNumber) + else: + return self def transformChildrenToNative(self): """Recursively replace children with their native representation.""" @@ -173,29 +200,30 @@ def transformChildrenFromNative(self, clearBehavior=True): pass def serialize(self, buf=None, lineLength=75, validate=True, behavior=None): - """Serialize to buf if it exists, otherwise return a string. - + """ + Serialize to buf if it exists, otherwise return a string. + Use self.behavior.serialize if behavior exists. - + """ if not behavior: behavior = self.behavior - + if behavior: - if DEBUG: logger.debug("serializing %s with behavior" % self.name) + #print("serializing %s with behavior %s" % (self.name, behavior)) + if DEBUG: + logger.debug("serializing %s with behavior %s" % (self.name, behavior)) return behavior.serialize(self, buf, lineLength, validate) else: - if DEBUG: logger.debug("serializing %s without behavior" % self.name) + if DEBUG: + logger.debug("serializing %s without behavior" % self.name) return defaultSerialize(self, buf, lineLength) -def ascii(s): - """Turn s into a printable string. Won't work for 8-bit ASCII.""" - return unicode(s).encode('ascii', 'replace') def toVName(name, stripNum = 0, upper = False): """ - Turn a Python name into an iCalendar style name, optionally uppercase and - with characters stripped off. + Turn a Python name into an iCalendar style name, + optionally uppercase and with characters stripped off. """ if upper: name = name.upper() @@ -203,8 +231,10 @@ def toVName(name, stripNum = 0, upper = False): name = name[:-stripNum] return name.replace('_', '-') + class ContentLine(VBase): - """Holds one content line for formats like vCard and vCalendar. + """ + Holds one content line for formats like vCard and vCalendar. For example:: @@ -228,26 +258,33 @@ class ContentLine(VBase): @ivar lineNumber: An optional line number associated with the contentline. """ - def __init__(self, name, params, value, group=None, - encoded=False, isNative=False, - lineNumber = None, *args, **kwds): - """Take output from parseLine, convert params list to dictionary.""" - # group is used as a positional argument to match parseLine's return + def __init__(self, name, params, value, group=None, encoded=False, + isNative=False, lineNumber = None, *args, **kwds): + """ + Take output from parseLine, convert params list to dictionary. + + Group is used as a positional argument to match parseLine's return + + """ super(ContentLine, self).__init__(group, *args, **kwds) - self.name = name.upper() - self.value = value - self.encoded = encoded - self.params = {} + + self.name = name.upper() + self.encoded = encoded + self.params = {} self.singletonparams = [] self.isNative = isNative self.lineNumber = lineNumber + self.value = value + def updateTable(x): if len(x) == 1: self.singletonparams += x else: paramlist = self.params.setdefault(x[0].upper(), []) paramlist.extend(x[1:]) - map(updateTable, params) + + list(map(updateTable, params)) + qp = False if 'ENCODING' in self.params: if 'QUOTED-PRINTABLE' in self.params['ENCODING']: @@ -259,18 +296,7 @@ def updateTable(x): qp = True self.singletonparams.remove('QUOTED-PRINTABLE') if qp: - self.value = str(self.value).decode('quoted-printable') - - # self.value should be unicode for iCalendar, but if quoted-printable - # is used, or if the quoted-printable state machine is used, text may be - # encoded - if type(self.value) is str: - charset = 'iso-8859-1' - if 'CHARSET' in self.params: - charsets = self.params.pop('CHARSET') - if charsets: - charset = charsets[0] - self.value = unicode(self.value, charset) + self.value = self.value.decode('quoted-printable') @classmethod def duplicate(clz, copyit): @@ -284,32 +310,20 @@ def copy(self, copyit): self.value = copy.copy(copyit.value) self.encoded = self.encoded self.params = copy.copy(copyit.params) - for k,v in self.params.items(): + for k, v in self.params.items(): self.params[k] = copy.copy(v) self.singletonparams = copy.copy(copyit.singletonparams) self.lineNumber = copyit.lineNumber - + def __eq__(self, other): try: return (self.name == other.name) and (self.params == other.params) and (self.value == other.value) - except: + except Exception: return False - def _getAttributeNames(self): - """Return a list of attributes of the object. - - Python 2.6 will add __dir__ to customize what attributes are returned - by dir, for now copy PyCrust so that IPython can accurately do - completion. - - """ - keys = self.params.keys() - params = [param + '_param' for param in keys] - params.extend(param + '_paramlist' for param in keys) - return params - def __getattr__(self, name): - """Make params accessible via self.foo_param or self.foo_paramlist. + """ + Make params accessible via self.foo_param or self.foo_paramlist. Underscores, legal in python variable names, are converted to dashes, which are legal in IANA tokens. @@ -321,16 +335,17 @@ def __getattr__(self, name): elif name.endswith('_paramlist'): return self.params[toVName(name, 10, True)] else: - raise exceptions.AttributeError, name + raise AttributeError(name) except KeyError: - raise exceptions.AttributeError, name + raise AttributeError(name) def __setattr__(self, name, value): - """Make params accessible via self.foo_param or self.foo_paramlist. + """ + Make params accessible via self.foo_param or self.foo_paramlist. Underscores, legal in python variable names, are converted to dashes, which are legal in IANA tokens. - + """ if name.endswith('_param'): if type(value) == list: @@ -358,34 +373,37 @@ def __delattr__(self, name): else: object.__delattr__(self, name) except KeyError: - raise exceptions.AttributeError, name + raise AttributeError(name) def valueRepr( self ): - """transform the representation of the value according to the behavior, - if any""" + """ + Transform the representation of the value + according to the behavior, if any. + """ v = self.value if self.behavior: v = self.behavior.valueRepr( self ) - return ascii( v ) - + return v + def __str__(self): - return "<"+ascii(self.name)+ascii(self.params)+self.valueRepr()+">" + return "<%s%s%s>" % (self.name, self.params, self.valueRepr()) def __repr__(self): - return self.__str__().replace('\n', '\\n') + return self.__str__() def prettyPrint(self, level = 0, tabwidth=3): pre = ' ' * level * tabwidth - print pre, self.name + ":", self.valueRepr() + print(pre, self.name + ":", self.valueRepr()) if self.params: - lineKeys= self.params.keys() - print pre, "params for ", self.name +':' - for aKey in lineKeys: - print pre + ' ' * tabwidth, aKey, ascii(self.params[aKey]) + print(pre, "params for ", self.name + ':') + for k in self.params.keys(): + print(pre + ' ' * tabwidth, k, self.params[k]) + class Component(VBase): - """A complex property that can contain multiple ContentLines. - + """ + A complex property that can contain multiple ContentLines. + For our purposes, a component must start with a BEGIN:xxxx line and end with END:xxxx, or have a PROFILE:xxx line if a top-level component. @@ -410,7 +428,7 @@ def __init__(self, name=None, *args, **kwds): else: self.name = '' self.useBegin = False - + self.autoBehavior() @classmethod @@ -421,7 +439,7 @@ def duplicate(clz, copyit): def copy(self, copyit): super(Component, self).copy(copyit) - + # deep copy of contents self.contents = {} for key, lvalue in copyit.contents.items(): @@ -433,56 +451,48 @@ def copy(self, copyit): self.name = copyit.name self.useBegin = copyit.useBegin - + def setProfile(self, name): - """Assign a PROFILE to this unnamed component. - + """ + Assign a PROFILE to this unnamed component. + Used by vCard, not by vCalendar. - + """ if self.name or self.useBegin: - if self.name == name: return + if self.name == name: + return raise VObjectError("This component already has a PROFILE or uses BEGIN.") self.name = name.upper() - def _getAttributeNames(self): - """Return a list of attributes of the object. - - Python 2.6 will add __dir__ to customize what attributes are returned - by dir, for now copy PyCrust so that IPython can accurately do - completion. - + def __getattr__(self, name): """ - names = self.contents.keys() - names.extend(name + '_list' for name in self.contents.keys()) - return names + For convenience, make self.contents directly accessible. - def __getattr__(self, name): - """For convenience, make self.contents directly accessible. - Underscores, legal in python variable names, are converted to dashes, which are legal in IANA tokens. - + """ # if the object is being re-created by pickle, self.contents may not # be set, don't get into an infinite loop over the issue if name == 'contents': - return object.__getattribute__(self, name) + return object.__getattribute__(self, name) try: if name.endswith('_list'): return self.contents[toVName(name, 5)] else: return self.contents[toVName(name)][0] except KeyError: - raise exceptions.AttributeError, name + raise AttributeError(name) normal_attributes = ['contents','name','behavior','parentBehavior','group'] def __setattr__(self, name, value): - """For convenience, make self.contents directly accessible. + """ + For convenience, make self.contents directly accessible. Underscores, legal in python variable names, are converted to dashes, which are legal in IANA tokens. - + """ if name not in self.normal_attributes and name.lower()==name: if type(value) == list: @@ -510,10 +520,12 @@ def __delattr__(self, name): else: object.__delattr__(self, name) except KeyError: - raise exceptions.AttributeError, name + raise AttributeError(name) def getChildValue(self, childName, default = None, childNumber = 0): - """Return a child's value (the first, by default), or None.""" + """ + Return a child's value (the first, by default), or None. + """ child = self.contents.get(toVName(childName)) if child is None: return default @@ -521,13 +533,13 @@ def getChildValue(self, childName, default = None, childNumber = 0): return child[childNumber].value def add(self, objOrName, group = None): - """Add objOrName to contents, set behavior if it can be inferred. - + """ + Add objOrName to contents, set behavior if it can be inferred. + If objOrName is a string, create an empty component or line based on behavior. If no behavior is found for the object, add a ContentLine. - group is an optional prefix to the name of the object (see - RFC 2425). + group is an optional prefix to the name of the object (see RFC 2425). """ if isinstance(objOrName, VBase): obj = objOrName @@ -545,7 +557,7 @@ def add(self, objOrName, group = None): obj = ContentLine(name, [], '', group) obj.parentBehavior = self.behavior obj.behavior = behavior - obj = obj.transformToNative() + obj = obj.transformToNative() except (KeyError, AttributeError): obj = ContentLine(objOrName, [], '', group) if obj.behavior is None and self.behavior is not None: @@ -581,7 +593,7 @@ def lines(self): def sortChildKeys(self): try: first = [s for s in self.behavior.sortFirst if s in self.contents] - except: + except Exception: first = [] return first + sorted(k for k in self.contents.keys() if k not in first) @@ -590,74 +602,83 @@ def getSortedChildren(self): def setBehaviorFromVersionLine(self, versionLine): """Set behavior if one matches name, versionLine.value.""" - v=getBehavior(self.name, versionLine.value) - if v: self.setBehavior(v) + v = getBehavior(self.name, versionLine.value) + if v: + self.setBehavior(v) def transformChildrenToNative(self): - """Recursively replace children with their native representation.""" - #sort to get dependency order right, like vtimezone before vevent + """ + Recursively replace children with their native representation. + + Sort to get dependency order right, like vtimezone before vevent. + + """ for childArray in (self.contents[k] for k in self.sortChildKeys()): - for i in xrange(len(childArray)): - childArray[i]=childArray[i].transformToNative() - childArray[i].transformChildrenToNative() + for child in childArray: + child = child.transformToNative() + child.transformChildrenToNative() def transformChildrenFromNative(self, clearBehavior=True): - """Recursively transform native children to vanilla representations.""" + """ + Recursively transform native children to vanilla representations. + """ for childArray in self.contents.values(): - for i in xrange(len(childArray)): - childArray[i]=childArray[i].transformFromNative() - childArray[i].transformChildrenFromNative(clearBehavior) + for child in childArray: + child = child.transformFromNative() + child.transformChildrenFromNative(clearBehavior) if clearBehavior: - childArray[i].behavior = None - childArray[i].parentBehavior = None - + child.behavior = None + child.parentBehavior = None + def __str__(self): if self.name: - return "<" + self.name + "| " + str(self.getSortedChildren()) + ">" + return "<%s| %s>" % (self.name, self.getSortedChildren()) else: - return '<' + '*unnamed*' + '| ' + str(self.getSortedChildren()) + '>' + return u'<*unnamed*| {}>'.format(self.getSortedChildren()) def __repr__(self): return self.__str__() def prettyPrint(self, level = 0, tabwidth=3): pre = ' ' * level * tabwidth - print pre, self.name + print(pre, self.name) if isinstance(self, Component): for line in self.getChildren(): line.prettyPrint(level + 1, tabwidth) - print + class VObjectError(Exception): def __init__(self, msg, lineNumber=None): self.msg = msg if lineNumber is not None: self.lineNumber = lineNumber + def __str__(self): if hasattr(self, 'lineNumber'): - return "At line %s: %s" % \ - (self.lineNumber, self.msg) + return "At line %s: %s" % (self.lineNumber, self.msg) else: return repr(self.msg) + class ParseError(VObjectError): pass + class ValidateError(VObjectError): pass + class NativeError(VObjectError): pass -#-------------------------- Parsing functions ---------------------------------- -# parseLine regular expressions +#--------- Parsing functions and parseLine regular expressions ------------------ patterns = {} # Note that underscore is not legal for names, it's included because # Lotus Notes uses it -patterns['name'] = '[a-zA-Z0-9\-_]+' +patterns['name'] = '[a-zA-Z0-9\-_]+' patterns['safe_char'] = '[^";:,]' patterns['qsafe_char'] = '[^"]' @@ -678,9 +699,9 @@ class NativeError(VObjectError): patterns['param'] = r""" ; (?: %(name)s ) # parameter name (?: - (?: = (?: %(param_value)s ) )? # 0 or more parameter values, multiple + (?: = (?: %(param_value)s ) )? # 0 or more parameter values, multiple (?: , (?: %(param_value)s ) )* # parameters are comma separated -)* +)* """ % patterns # get a parameter, saving groups for name and value (value still needs parsing) @@ -689,7 +710,7 @@ class NativeError(VObjectError): (?: = ( - (?: (?: %(param_value)s ) )? # 0 or more parameter values, multiple + (?: (?: %(param_value)s ) )? # 0 or more parameter values, multiple (?: , (?: %(param_value)s ) )* # parameters are comma separated ) )? @@ -711,14 +732,6 @@ class NativeError(VObjectError): def parseParams(string): - """ - >>> parseParams(';ALTREP="http://www.wiz.org"') - [['ALTREP', 'http://www.wiz.org']] - >>> parseParams('') - [] - >>> parseParams(';ALTREP="http://www.wiz.org;;",Blah,Foo;NEXT=Nope;BAR') - [['ALTREP', 'http://www.wiz.org;;', 'Blah', 'Foo'], ['NEXT', 'Nope'], ['BAR']] - """ all = params_re.findall(string) allParameters = [] for tup in all: @@ -734,30 +747,11 @@ def parseParams(string): def parseLine(line, lineNumber = None): - """ - >>> parseLine("BLAH:") - ('BLAH', [], '', None) - >>> parseLine("RDATE:VALUE=DATE:19970304,19970504,19970704,19970904") - ('RDATE', [], 'VALUE=DATE:19970304,19970504,19970704,19970904', None) - >>> parseLine('DESCRIPTION;ALTREP="http://www.wiz.org":The Fall 98 Wild Wizards Conference - - Las Vegas, NV, USA') - ('DESCRIPTION', [['ALTREP', 'http://www.wiz.org']], 'The Fall 98 Wild Wizards Conference - - Las Vegas, NV, USA', None) - >>> parseLine("EMAIL;PREF;INTERNET:john@nowhere.com") - ('EMAIL', [['PREF'], ['INTERNET']], 'john@nowhere.com', None) - >>> parseLine('EMAIL;TYPE="blah",hah;INTERNET="DIGI",DERIDOO:john@nowhere.com') - ('EMAIL', [['TYPE', 'blah', 'hah'], ['INTERNET', 'DIGI', 'DERIDOO']], 'john@nowhere.com', None) - >>> parseLine('item1.ADR;type=HOME;type=pref:;;Reeperbahn 116;Hamburg;;20359;') - ('ADR', [['type', 'HOME'], ['type', 'pref']], ';;Reeperbahn 116;Hamburg;;20359;', 'item1') - >>> parseLine(":") - Traceback (most recent call last): - ... - ParseError: 'Failed to parse line: :' - """ - match = line_re.match(line) if match is None: raise ParseError("Failed to parse line: %s" % line, lineNumber) # Underscores are replaced with dash to work around Lotus Notes - return (match.group('name').replace('_','-'), + return (match.group('name').replace('_','-'), parseParams(match.group('params')), match.group('value'), match.group('group')) @@ -787,19 +781,21 @@ def parseLine(line, lineNumber = None): """ def getLogicalLines(fp, allowQP=True, findBegin=False): - """Iterate through a stream, yielding one logical line at a time. + """ + Iterate through a stream, yielding one logical line at a time. Because many applications still use vCard 2.1, we have to deal with the quoted-printable encoding for long lines, as well as the vCard 3.0 and vCalendar line folding technique, a whitespace character at the start of the line. - + Quoted-printable data will be decoded in the Behavior decoding phase. - - >>> import StringIO - >>> f=StringIO.StringIO(testLines) + + # We're leaving this test in for awhile, because the unittest was ugly and dumb. + >>> from six import StringIO + >>> f=StringIO(testLines) >>> for n, l in enumerate(getLogicalLines(f)): - ... print "Line %s: %s" % (n, l[0]) + ... print("Line %s: %s" % (n, l[0])) ... Line 0: Line 0 text, Line 0 continued. Line 1: Line 1;encoding=quoted-printable:this is an evil= @@ -809,28 +805,26 @@ def getLogicalLines(fp, allowQP=True, findBegin=False): """ if not allowQP: - bytes = fp.read(-1) - if len(bytes) > 0: - if type(bytes[0]) == unicode: - val = bytes - elif not findBegin: - val = bytes.decode('utf-8') + val = fp.read(-1) + + #Shouldn't need this anymore... + """ + if len(val) > 0: + if not findBegin: + val = val.decode('utf-8') else: for encoding in 'utf-8', 'utf-16-LE', 'utf-16-BE', 'iso-8859-1': try: - val = bytes.decode(encoding) + val = val.decode(encoding) if begin_re.search(val) is not None: break except UnicodeDecodeError: pass else: - raise ParseError, 'Could not find BEGIN when trying to determine encoding' - else: - val = bytes - + raise ParseError('Could not find BEGIN when trying to determine encoding') + """ # strip off any UTF8 BOMs which Python's UTF8 decoder leaves - - val = val.lstrip( unicode( codecs.BOM_UTF8, "utf8" ) ) + #val = val.lstrip( unicode( codecs.BOM_UTF8, "utf8" ) ) lineNumber = 1 for match in logical_lines_re.finditer(val): @@ -838,10 +832,10 @@ def getLogicalLines(fp, allowQP=True, findBegin=False): if line != '': yield line, lineNumber lineNumber += n - + else: - quotedPrintable=False - newbuffer = StringIO.StringIO + quotedPrintable = False + newbuffer = six.StringIO logicalLine = newbuffer() lineNumber = 0 lineStartNumber = 0 @@ -853,20 +847,20 @@ def getLogicalLines(fp, allowQP=True, findBegin=False): line = line.rstrip(CRLF) lineNumber += 1 if line.rstrip() == '': - if logicalLine.pos > 0: + if logicalLine.tell() > 0: yield logicalLine.getvalue(), lineStartNumber lineStartNumber = lineNumber logicalLine = newbuffer() - quotedPrintable=False + quotedPrintable = False continue - + if quotedPrintable and allowQP: logicalLine.write('\n') logicalLine.write(line) - quotedPrintable=False + quotedPrintable = False elif line[0] in SPACEORTAB: logicalLine.write(line[1:]) - elif logicalLine.pos > 0: + elif logicalLine.tell() > 0: yield logicalLine.getvalue(), lineStartNumber lineStartNumber = lineNumber logicalLine = newbuffer() @@ -874,24 +868,25 @@ def getLogicalLines(fp, allowQP=True, findBegin=False): else: logicalLine = newbuffer() logicalLine.write(line) - - # hack to deal with the fact that vCard 2.1 allows parameters to be - # encoded without a parameter name. False positives are unlikely, but - # possible. + + # vCard 2.1 allows parameters to be encoded without a parameter name. + # False positives are unlikely, but possible. val = logicalLine.getvalue() if val[-1]=='=' and val.lower().find('quoted-printable') >= 0: quotedPrintable=True - - if logicalLine.pos > 0: + + if logicalLine.tell() > 0: yield logicalLine.getvalue(), lineStartNumber def textLineToContentLine(text, n=None): return ContentLine(*parseLine(text, n), **{'encoded':True, 'lineNumber' : n}) - + def dquoteEscape(param): - """Return param, or "param" if ',' or ';' or ':' is in param.""" + """ + Return param, or "param" if ',' or ';' or ':' is in param. + """ if param.find('"') >= 0: raise VObjectError("Double quotes aren't allowed in parameter values.") for char in ',;:': @@ -900,12 +895,20 @@ def dquoteEscape(param): return param def foldOneLine(outbuf, input, lineLength = 75): - # Folding line procedure that ensures multi-byte utf-8 sequences are not broken - # across lines + """ + Folding line procedure that ensures multi-byte utf-8 sequences are not broken across lines + + TO-DO: This all seems odd. Is it still needed, especially in python3? + """ if len(input) < lineLength: # Optimize for unfolded line case - outbuf.write(input) + try: + outbuf.write(bytes(input, 'UTF-8')) + except Exception: + # fall back on py2 syntax + outbuf.write(input) + else: # Look for valid utf8 range and write that out start = 0 @@ -915,25 +918,41 @@ def foldOneLine(outbuf, input, lineLength = 75): offset = start + lineLength - 1 if offset >= len(input): line = input[start:] - outbuf.write(line) + try: + outbuf.write(bytes(line, 'UTF-8')) + except Exception: + # fall back on py2 syntax + outbuf.write(line) written = len(input) else: # Check whether next char is valid utf8 lead byte - while (input[offset] > 0x7F) and ((ord(input[offset]) & 0xC0) == 0x80): - # Step back until we have a valid char - offset -= 1 - + # while (input[offset] > 0x7F) and ((ord(input[offset]) & 0xC0) == 0x80): + # # Step back until we have a valid char + # offset -= 1 + line = input[start:offset] - outbuf.write(line) - outbuf.write("\r\n ") + try: + outbuf.write(bytes(line, 'UTF-8')) + outbuf.write(bytes("\r\n ", 'UTF-8')) + except Exception: + # fall back on py2 syntax + outbuf.write(line) + outbuf.write("\r\n ") written += offset - start start = offset - outbuf.write("\r\n") + try: + outbuf.write(bytes("\r\n", 'UTF-8')) + except Exception: + # fall back on py2 syntax + outbuf.write("\r\n") + def defaultSerialize(obj, buf, lineLength): - """Encode and fold obj and its children, write to buf or return a string.""" + """ + Encode and fold obj and its children, write to buf or return a string. + """ - outbuf = buf or cStringIO.StringIO() + outbuf = buf or six.StringIO() if isinstance(obj, Component): if obj.group is None: @@ -941,37 +960,36 @@ def defaultSerialize(obj, buf, lineLength): else: groupString = obj.group + '.' if obj.useBegin: - foldOneLine(outbuf, str(groupString + u"BEGIN:" + obj.name), lineLength) + foldOneLine(outbuf, "{0}BEGIN:{1}".format(groupString, obj.name), lineLength) for child in obj.getSortedChildren(): - #validate is recursive, we only need to validate once + # validate is recursive, we only need to validate once child.serialize(outbuf, lineLength, validate=False) + # print('child serialized', str(child)) if obj.useBegin: - foldOneLine(outbuf, str(groupString + u"END:" + obj.name), lineLength) - + foldOneLine(outbuf, "{0}END:{1}".format(groupString, obj.name), lineLength) + elif isinstance(obj, ContentLine): startedEncoded = obj.encoded - if obj.behavior and not startedEncoded: obj.behavior.encode(obj) - s=codecs.getwriter('utf-8')(cStringIO.StringIO()) #unfolded buffer + if obj.behavior and not startedEncoded: + obj.behavior.encode(obj) + + #s = codecs.getwriter('utf-8')(six.StringIO()) #unfolded buffer + s = six.StringIO() + if obj.group is not None: s.write(obj.group + '.') s.write(obj.name.upper()) - keys = sorted(obj.params.iterkeys()) + keys = sorted(obj.params.keys()) for key in keys: - paramvals = obj.params[key] - s.write(';' + key + '=' + ','.join(dquoteEscape(p) for p in paramvals)) - s.write(':' + obj.value) - if obj.behavior and not startedEncoded: obj.behavior.decode(obj) + paramstr = ','.join(dquoteEscape(p) for p in obj.params[key]) + s.write(";{}={}".format(key, paramstr)) + s.write(":{}".format(str_(obj.value))) + if obj.behavior and not startedEncoded: + obj.behavior.decode(obj) foldOneLine(outbuf, s.getvalue(), lineLength) - - return buf or outbuf.getvalue() + return buf or outbuf.getvalue() -testVCalendar=""" -BEGIN:VCALENDAR -BEGIN:VEVENT -SUMMARY;blah=hi!:Bastille Day Party -END:VEVENT -END:VCALENDAR""" class Stack: def __init__(self): @@ -991,27 +1009,22 @@ def modifyTop(self, item): else: new = Component() self.push(new) - new.add(item) #add sets behavior for item and children - def push(self, obj): self.stack.append(obj) - def pop(self): return self.stack.pop() + new.add(item) # add sets behavior for item and children + + def push(self, obj): + self.stack.append(obj) + + def pop(self): + return self.stack.pop() def readComponents(streamOrString, validate=False, transform=True, - findBegin=True, ignoreUnreadable=False, - allowQP=False): - """Generate one Component at a time from a stream. - - >>> import StringIO - >>> f = StringIO.StringIO(testVCalendar) - >>> cal=readComponents(f).next() - >>> cal - ]>]> - >>> cal.vevent.summary - - + findBegin=True, ignoreUnreadable=False, allowQP=False): + """ + Generate one Component at a time from a stream. """ if isinstance(streamOrString, basestring): - stream = StringIO.StringIO(streamOrString) + stream = six.StringIO(str_(streamOrString)) else: stream = streamOrString @@ -1023,46 +1036,50 @@ def readComponents(streamOrString, validate=False, transform=True, if ignoreUnreadable: try: vline = textLineToContentLine(line, n) - except VObjectError, e: + except VObjectError as e: if e.lineNumber is not None: msg = "Skipped line %(lineNumber)s, message: %(msg)s" else: msg = "Skipped a line, message: %(msg)s" - logger.error(msg % {'lineNumber' : e.lineNumber, - 'msg' : e.message}) + logger.error(msg % {'lineNumber' : e.lineNumber, 'msg' : str(e)}) continue else: vline = textLineToContentLine(line, n) - if vline.name == "VERSION": + if vline.name == "VERSION": versionLine = vline stack.modifyTop(vline) elif vline.name == "BEGIN": stack.push(Component(vline.value, group=vline.group)) elif vline.name == "PROFILE": - if not stack.top(): stack.push(Component()) + if not stack.top(): + stack.push(Component()) stack.top().setProfile(vline.value) elif vline.name == "END": if len(stack) == 0: - err = "Attempted to end the %s component, \ - but it was never opened" % vline.value + err = "Attempted to end the %s component but it was never opened" % vline.value raise ParseError(err, n) - if vline.value.upper() == stack.topName(): #START matches END + + if vline.value.upper() == stack.topName(): # START matches END if len(stack) == 1: - component=stack.pop() + component = stack.pop() if versionLine is not None: component.setBehaviorFromVersionLine(versionLine) else: behavior = getBehavior(component.name) if behavior: component.setBehavior(behavior) - if validate: component.validate(raiseException=True) - if transform: component.transformChildrenToNative() - yield component #EXIT POINT - else: stack.modifyTop(stack.pop()) + if validate: + component.validate(raiseException=True) + if transform: + component.transformChildrenToNative() + yield component # EXIT POINT + else: + stack.modifyTop(stack.pop()) else: - err = "%s component wasn't closed" + err = "%s component wasn't closed" raise ParseError(err % stack.topName(), n) - else: stack.modifyTop(vline) #not a START or END line + else: + stack.modifyTop(vline) # not a START or END line if stack.top(): if stack.topName() is None: logger.warning("Top level component was never named") @@ -1070,29 +1087,32 @@ def readComponents(streamOrString, validate=False, transform=True, raise ParseError("Component %s was never closed" % (stack.topName()), n) yield stack.pop() - except ParseError, e: + except ParseError as e: e.input = streamOrString raise -def readOne(stream, validate=False, transform=True, findBegin=True, - ignoreUnreadable=False, allowQP=False): - """Return the first component from stream.""" - return readComponents(stream, validate, transform, findBegin, - ignoreUnreadable, allowQP).next() +def readOne(stream, validate=False, transform=True, findBegin=True, ignoreUnreadable=False, allowQP=False): + """ + Return the first component from stream. + """ + return next(readComponents(stream, validate, transform, findBegin, ignoreUnreadable, allowQP)) + #--------------------------- version registry ---------------------------------- __behaviorRegistry={} def registerBehavior(behavior, name=None, default=False, id=None): """Register the given behavior. - - If default is True (or if this is the first version registered with this + + If default is True (or if this is the first version registered with this name), the version will be the default if no id is given. - + """ - if not name: name=behavior.name.upper() - if id is None: id=behavior.versionString + if not name: + name=behavior.name.upper() + if id is None: + id=behavior.versionString if name in __behaviorRegistry: if default: __behaviorRegistry[name].insert(0, (id, behavior)) @@ -1103,9 +1123,9 @@ def registerBehavior(behavior, name=None, default=False, id=None): def getBehavior(name, id=None): """Return a matching behavior if it exists, or None. - + If id is None, return the default for name. - + """ name=name.upper() if name in __behaviorRegistry: @@ -1118,7 +1138,9 @@ def getBehavior(name, id=None): return None def newFromBehavior(name, id=None): - """Given a name, return a behaviored ContentLine or Component.""" + """ + Given a name, return a behaviored ContentLine or Component. + """ name = name.upper() behavior = getBehavior(name, id) if behavior is None: @@ -1134,10 +1156,6 @@ def newFromBehavior(name, id=None): #--------------------------- Helper function ----------------------------------- def backslashEscape(s): - s=s.replace("\\","\\\\").replace(";","\;").replace(",","\,") + s = s.replace("\\","\\\\").replace(";","\;").replace(",","\,") return s.replace("\r\n", "\\n").replace("\n","\\n").replace("\r","\\n") -#------------------- Testing and running functions ----------------------------- -if __name__ == '__main__': - import tests - tests._test() diff --git a/vobject/behavior.py b/vobject/behavior.py index 226c0cc..451cd82 100644 --- a/vobject/behavior.py +++ b/vobject/behavior.py @@ -1,17 +1,18 @@ -"""Behavior (validation, encoding, and transformations) for vobjects.""" - -import base +from . import base #------------------------ Abstract class for behavior -------------------------- class Behavior(object): - """Abstract class to describe vobject options, requirements and encodings. - + """ + Behavior (validation, encoding, and transformations) for vobjects. + + Abstract class to describe vobject options, requirements and encodings. + Behaviors are used for root components like VCALENDAR, for subcomponents like VEVENT, and for individual lines in components. - + Behavior subclasses are not meant to be instantiated, all methods should be classmethods. - + @cvar name: The uppercase name of the object described by the class, or a generic name if the class defines behavior for many objects. @@ -56,11 +57,11 @@ class Behavior(object): def __init__(self): err="Behavior subclasses are not meant to be instantiated" raise base.VObjectError(err) - + @classmethod def validate(cls, obj, raiseException=False, complainUnrecognized=False): """Check if the object satisfies this behavior's requirements. - + @param obj: The L{ContentLine} or L{Component} to be validated. @@ -73,7 +74,7 @@ def validate(cls, obj, raiseException=False, complainUnrecognized=False): """ if not cls.allowGroup and obj.group is not None: - err = str(obj) + " has a group, but this object doesn't support groups" + err = "{0} has a group, but this object doesn't support groups".format(obj) raise base.VObjectError(err) if isinstance(obj, base.ContentLine): return cls.lineValidate(obj, raiseException, complainUnrecognized) @@ -84,8 +85,8 @@ def validate(cls, obj, raiseException=False, complainUnrecognized=False): return False name=child.name.upper() count[name] = count.get(name, 0) + 1 - for key, val in cls.knownChildren.iteritems(): - if count.get(key,0) < val[0]: + for key, val in cls.knownChildren.items(): + if count.get(key,0) < val[0]: if raiseException: m = "%s components must contain at least %i %s" raise base.ValidateError(m % (cls.name, val[0], key)) @@ -97,9 +98,9 @@ def validate(cls, obj, raiseException=False, complainUnrecognized=False): return False return True else: - err = str(obj) + " is not a Component or Contentline" + err = "{0} is not a Component or Contentline".format(obj) raise base.VObjectError(err) - + @classmethod def lineValidate(cls, line, raiseException, complainUnrecognized): """Examine a line's parameters and values, return True if valid.""" @@ -108,57 +109,62 @@ def lineValidate(cls, line, raiseException, complainUnrecognized): @classmethod def decode(cls, line): if line.encoded: line.encoded=0 - + @classmethod def encode(cls, line): if not line.encoded: line.encoded=1 @classmethod def transformToNative(cls, obj): - """Turn a ContentLine or Component into a Python-native representation. - + """ + Turn a ContentLine or Component into a Python-native representation. + If appropriate, turn dates or datetime strings into Python objects. Components containing VTIMEZONEs turn into VtimezoneComponents. - + """ return obj - + @classmethod def transformFromNative(cls, obj): - """Inverse of transformToNative.""" + """ + Inverse of transformToNative. + """ raise base.NativeError("No transformFromNative defined") - + @classmethod def generateImplicitParameters(cls, obj): """Generate any required information that don't yet exist.""" pass - + @classmethod def serialize(cls, obj, buf, lineLength, validate=True): - """Set implicit parameters, do encoding, return unicode string. - + """ + Set implicit parameters, do encoding, return unicode string. + If validate is True, raise VObjectError if the line doesn't validate after implicit parameters are generated. - + Default is to call base.defaultSerialize. - + """ - + cls.generateImplicitParameters(obj) if validate: cls.validate(obj, raiseException=True) - + if obj.isNative: transformed = obj.transformFromNative() undoTransform = True else: transformed = obj undoTransform = False - + out = base.defaultSerialize(transformed, buf, lineLength) - if undoTransform: obj.transformToNative() + if undoTransform: + obj.transformToNative() return out - + @classmethod def valueRepr( cls, line ): """return the representation of the given content line value""" - return line.value \ No newline at end of file + return line.value diff --git a/vobject/change_tz.py b/vobject/change_tz.py index 4f9ae1e..3ecdc66 100644 --- a/vobject/change_tz.py +++ b/vobject/change_tz.py @@ -1,8 +1,10 @@ """Translate an ics file's events to a different timezone.""" +import sys + from optparse import OptionParser from vobject import icalendar, base -import sys + try: import PyICU except: @@ -11,6 +13,18 @@ from datetime import datetime def change_tz(cal, new_timezone, default, utc_only=False, utc_tz=icalendar.utc): + """Change the timezone of the specified component. + + Args: + cal (Component): the component to change + new_timezone (tzinfo): the timezone to change to + default (tzinfo): a timezone to assume if the dtstart or dtend in cal + doesn't have an existing timezone + utc_only (bool): only convert dates that are in utc + utc_tz (tzinfo): the tzinfo to compare to for UTC when processing + utc_only=True + """ + for vevent in getattr(cal, 'vevent_list', []): start = getattr(vevent, 'dtstart', None) end = getattr(vevent, 'dtend', None) @@ -18,7 +32,7 @@ def change_tz(cal, new_timezone, default, utc_only=False, utc_tz=icalendar.utc): if node: dt = node.value if (isinstance(dt, datetime) and - (not utc_only or dt.tzinfo == utc_tz)): + (not utc_only or dt.tzinfo == utc_tz)): if dt.tzinfo is None: dt = dt.replace(tzinfo = default) node.value = dt.astimezone(new_timezone) @@ -26,31 +40,32 @@ def change_tz(cal, new_timezone, default, utc_only=False, utc_tz=icalendar.utc): def main(): options, args = get_options() if PyICU is None: - print "Failure. change_tz requires PyICU, exiting" + print("Failure. change_tz requires PyICU, exiting") elif options.list: for tz_string in PyICU.TimeZone.createEnumeration(): - print tz_string + print(tz_string) elif args: utc_only = options.utc if utc_only: which = "only UTC" else: which = "all" - print "Converting %s events" % which + print("Converting %s events" % which) ics_file = args[0] if len(args) > 1: timezone = PyICU.ICUtzinfo.getInstance(args[1]) else: timezone = PyICU.ICUtzinfo.default - print "... Reading %s" % ics_file - cal = base.readOne(file(ics_file)) + print("... Reading %s" % ics_file) + cal = base.readOne(open(ics_file)) change_tz(cal, timezone, PyICU.ICUtzinfo.default, utc_only) out_name = ics_file + '.converted' - print "... Writing %s" % out_name + print("... Writing %s" % out_name) + out = file(out_name, 'wb') cal.serialize(out) - print "Done" + print("Done") version = "0.1" @@ -70,9 +85,9 @@ def get_options(): (cmdline_options, args) = parser.parse_args() if not args and not cmdline_options.list: - print "error: too few arguments given" - print - print parser.format_help() + print("error: too few arguments given") + print() + print(parser.format_help()) return False, False return cmdline_options, args @@ -81,4 +96,4 @@ def get_options(): try: main() except KeyboardInterrupt: - print "Aborted" + print("Aborted") diff --git a/vobject/hcalendar.py b/vobject/hcalendar.py index 93614ab..1520f42 100644 --- a/vobject/hcalendar.py +++ b/vobject/hcalendar.py @@ -20,7 +20,7 @@ - Web 2.0 Conference: + Web 2.0 Conference: October 5- 7, at the Argent Hotel, San Francisco, CA @@ -28,39 +28,42 @@ """ -from base import foldOneLine, CRLF, registerBehavior -from icalendar import VCalendar2_0 +import six + from datetime import date, datetime, timedelta -import StringIO + +from .base import CRLF, registerBehavior +from .icalendar import VCalendar2_0 + class HCalendar(VCalendar2_0): name = 'HCALENDAR' - + @classmethod def serialize(cls, obj, buf=None, lineLength=None, validate=True): """ Serialize iCalendar to HTML using the hCalendar microformat (http://microformats.org/wiki/hcalendar) """ - - outbuf = buf or StringIO.StringIO() - level = 0 # holds current indentation level + + outbuf = buf or six.StringIO() + level = 0 # holds current indentation level tabwidth = 3 - + def indent(): return ' ' * level * tabwidth - + def out(s): outbuf.write(indent()) outbuf.write(s) - + # not serializing optional vcalendar wrapper - + vevents = obj.vevent_list - + for event in vevents: out('' + CRLF) level += 1 - + # URL url = event.getChildValue("url") if url: @@ -70,7 +73,7 @@ def out(s): summary = event.getChildValue("summary") if summary: out('' + summary + ':' + CRLF) - + # DTSTART dtstart = event.getChildValue("dtstart") if dtstart: @@ -83,10 +86,10 @@ def out(s): #TODO: Handle non-datetime formats? #TODO: Spec says we should handle when dtstart isn't included - - out('%s\r\n' % + + out('%s\r\n' % (dtstart.strftime(machine), dtstart.strftime(timeformat))) - + # DTEND dtend = event.getChildValue("dtend") if not dtend: @@ -94,32 +97,32 @@ def out(s): if duration: dtend = duration + dtstart # TODO: If lacking dtend & duration? - + if dtend: human = dtend # TODO: Human readable part could be smarter, excluding repeated data if type(dtend) == date: human = dtend - timedelta(days=1) - - out('- %s\r\n' % - (dtend.strftime(machine), human.strftime(timeformat))) - # LOCATION + out('- %s\r\n' % + (dtend.strftime(machine), human.strftime(timeformat))) + + # LOCATION location = event.getChildValue("location") if location: out('at ' + location + '' + CRLF) - + description = event.getChildValue("description") if description: out('
' + description + '
' + CRLF) - + if url: level -= 1 out('
' + CRLF) - - level -= 1 + + level -= 1 out('' + CRLF) # close vevent return buf or outbuf.getvalue() - -registerBehavior(HCalendar) \ No newline at end of file + +registerBehavior(HCalendar) diff --git a/vobject/icalendar.py b/vobject/icalendar.py index e681a26..a69a0df 100644 --- a/vobject/icalendar.py +++ b/vobject/icalendar.py @@ -1,18 +1,20 @@ """Definitions and behavior for iCalendar, also known as vCalendar 2.0""" -import string -import behavior -import dateutil.rrule -import dateutil.tz -import StringIO, cStringIO +from __future__ import print_function + import datetime -import socket, random #for generating a UID -import itertools +import random #for generating a UID +import six +import socket +import string + +from dateutil import rrule, tz + +from . import behavior +from .base import (VObjectError, NativeError, ValidateError, ParseError, + Component, ContentLine, logger, registerBehavior, + backslashEscape, foldOneLine, str_) -from base import (VObjectError, NativeError, ValidateError, ParseError, - VBase, Component, ContentLine, logger, defaultSerialize, - registerBehavior, backslashEscape, foldOneLine, - newFromBehavior, CRLF, LF, ascii) #------------------------------- Constants ------------------------------------- DATENAMES = ("rdate", "exdate") @@ -27,12 +29,13 @@ zeroDelta = datetime.timedelta(0) twoHours = datetime.timedelta(hours=2) + #---------------------------- TZID registry ------------------------------------ __tzidMap={} def toUnicode(s): """Take a string or unicode, turn it into unicode, decoding as utf-8""" - if isinstance(s, str): + if isinstance(s, six.binary_type): s = s.decode('utf-8') return s @@ -55,26 +58,28 @@ def getTzid(tzid, smart=True): pass return tz -utc = dateutil.tz.tzutc() +utc = tz.tzutc() registerTzid("UTC", utc) + #-------------------- Helper subclasses ---------------------------------------- + class TimezoneComponent(Component): """A VTIMEZONE object. - - VTIMEZONEs are parsed by dateutil.tz.tzical, the resulting datetime.tzinfo + + VTIMEZONEs are parsed by tz.tzical, the resulting datetime.tzinfo subclass is stored in self.tzinfo, self.tzid stores the TZID associated with this timezone. - + @ivar name: The uppercased name of the object, in this case always 'VTIMEZONE'. @ivar tzinfo: A datetime.tzinfo subclass representing this timezone. @ivar tzid: The string used to refer to this timezone. - - """ + + """ def __init__(self, tzinfo=None, *args, **kwds): """Accept an existing Component or a tzinfo class.""" super(TimezoneComponent, self).__init__(*args, **kwds) @@ -101,7 +106,7 @@ def gettzinfo(self): good_lines = ('rdate', 'rrule', 'dtstart', 'tzname', 'tzoffsetfrom', 'tzoffsetto', 'tzid') # serialize encodes as utf-8, cStringIO will leave utf-8 alone - buffer = cStringIO.StringIO() + buffer = six.StringIO() # allow empty VTIMEZONEs if len(self.contents) == 0: return None @@ -116,13 +121,13 @@ def customSerialize(obj): foldOneLine(buffer, u"END:" + obj.name) customSerialize(self) buffer.seek(0) # tzical wants to read a stream - return dateutil.tz.tzical(buffer).get() + return tz.tzical(buffer).get() def settzinfo(self, tzinfo, start=2000, end=2030): """Create appropriate objects in self to represent tzinfo. - + Collapse DST transitions to rrules as much as possible. - + Assumptions: - DST <-> Standard transitions occur on the hour - never within a month of one another @@ -131,8 +136,8 @@ def settzinfo(self, tzinfo, start=2000, end=2030): - DST always moves offset exactly one hour later - tzinfo classes dst method always treats times that could be in either offset as being in the later regime - - """ + + """ def fromLastWeek(dt): """How many weeks from the end of the month dt is, starting from 1.""" weekDelta = datetime.timedelta(weeks=1) @@ -142,20 +147,20 @@ def fromLastWeek(dt): n += 1 current += weekDelta return n - + # lists of dictionaries defining rules which are no longer in effect completed = {'daylight' : [], 'standard' : []} - + # dictionary defining rules which are currently in effect working = {'daylight' : None, 'standard' : None} - + # rule may be based on the nth week of the month or the nth from the last - for year in xrange(start, end + 1): + for year in range(start, end + 1): newyear = datetime.datetime(year, 1, 1) for transitionTo in 'daylight', 'standard': transition = getTransition(transitionTo, year, tzinfo) oldrule = working[transitionTo] - + if transition == newyear: # transitionTo is in effect for the whole year rule = {'end' : None, @@ -173,7 +178,7 @@ def fromLastWeek(dt): working[transitionTo] = rule else: # transitionTo was already in effect - if (oldrule['offset'] != + if (oldrule['offset'] != tzinfo.utcoffset(newyear)): # old rule was different, it shouldn't continue oldrule['end'] = year - 1 @@ -197,14 +202,14 @@ def fromLastWeek(dt): 'name' : tzinfo.tzname(transition), 'plus' : (transition.day - 1)/ 7 + 1,#nth week of the month 'minus' : fromLastWeek(transition), #nth from last week - 'offset' : tzinfo.utcoffset(transition), + 'offset' : tzinfo.utcoffset(transition), 'offsetfrom' : old_offset} - - if oldrule is None: + + if oldrule is None: working[transitionTo] = rule else: - plusMatch = rule['plus'] == oldrule['plus'] - minusMatch = rule['minus'] == oldrule['minus'] + plusMatch = rule['plus'] == oldrule['plus'] + minusMatch = rule['minus'] == oldrule['minus'] truth = plusMatch or minusMatch for key in 'month', 'weekday', 'hour', 'offset': truth = truth and rule[key] == oldrule[key] @@ -219,18 +224,18 @@ def fromLastWeek(dt): oldrule['end'] = year - 1 completed[transitionTo].append(oldrule) working[transitionTo] = rule - + for transitionTo in 'daylight', 'standard': if working[transitionTo] is not None: completed[transitionTo].append(working[transitionTo]) - + self.tzid = [] self.daylight = [] self.standard = [] - + self.add('tzid').value = self.pickTzid(tzinfo, True) - - old = None + + # old = None # unused? for transitionTo in 'daylight', 'standard': for rule in completed[transitionTo]: comp = self.add(transitionTo) @@ -242,7 +247,7 @@ def fromLastWeek(dt): line.value = deltaToOffset(rule['offset']) line = comp.add('tzoffsetfrom') line.value = deltaToOffset(rule['offsetfrom']) - + if rule['plus'] is not None: num = rule['plus'] elif rule['minus'] is not None: @@ -258,8 +263,8 @@ def fromLastWeek(dt): # all year offset, with no rule endDate = datetime.datetime(rule['end'], 1, 1) else: - weekday = dateutil.rrule.weekday(rule['weekday'], num) - du_rule = dateutil.rrule.rrule(dateutil.rrule.YEARLY, + weekday = rrule.weekday(rule['weekday'], num) + du_rule = rrule.rrule(rrule.YEARLY, bymonth = rule['month'],byweekday = weekday, dtstart = datetime.datetime( rule['end'], 1, 1, rule['hour']) @@ -269,10 +274,9 @@ def fromLastWeek(dt): endString = ";UNTIL="+ dateTimeToString(endDate) else: endString = '' - rulestring = "FREQ=YEARLY%s;BYMONTH=%s%s" % \ - (dayString, str(rule['month']), endString) - - comp.add('rrule').value = rulestring + new_rule = "FREQ=YEARLY%s;BYMONTH=%s%s" % (dayString, rule['month'], endString) + + comp.add('rrule').value = new_rule tzinfo = property(gettzinfo, settzinfo) # prevent Component's __setattr__ from overriding the tzinfo property @@ -289,7 +293,7 @@ def pickTzid(tzinfo, allowUTC=False): # try PyICU's tzid key if hasattr(tzinfo, 'tzid'): return toUnicode(tzinfo.tzid) - + # try pytz zone key if hasattr(tzinfo, 'zone'): return toUnicode(tzinfo.zone) @@ -300,32 +304,34 @@ def pickTzid(tzinfo, allowUTC=False): else: # return tzname for standard (non-DST) time notDST = datetime.timedelta(0) - for month in xrange(1,13): + for month in range(1, 13): dt = datetime.datetime(2000, month, 1) if tzinfo.dst(dt) == notDST: return toUnicode(tzinfo.tzname(dt)) # there was no standard time in 2000! - raise VObjectError("Unable to guess TZID for tzinfo %s" % str(tzinfo)) + raise VObjectError("Unable to guess TZID for tzinfo %s" % tzinfo) def __str__(self): - return "" - + return "" % getattr(self, 'tzid', 'No TZID') + def __repr__(self): return self.__str__() - + def prettyPrint(self, level, tabwidth): pre = ' ' * level * tabwidth - print pre, self.name - print pre, "TZID:", self.tzid - print + print(pre, self.name) + print(pre, "TZID:", self.tzid) + print('') + class RecurringComponent(Component): - """A vCalendar component like VEVENT or VTODO which may recur. - + """ + A vCalendar component like VEVENT or VTODO which may recur. + Any recurring component can have one or multiple RRULE, RDATE, EXRULE, or EXDATE lines, and one or zero DTSTART lines. It can also have a - variety of children that don't have any recurrence information. - + variety of children that don't have any recurrence information. + In the example below, note that dtstart is included in the rruleset. This is not the default behavior for dateutil's rrule implementation unless dtstart would already have been a member of the recurrence rule, and as a @@ -333,49 +339,27 @@ class RecurringComponent(Component): adjusting count down by one if an rrule has a count and dtstart isn't in its result set, but by default, the rruleset property doesn't do this work around, to access it getrruleset must be called with addRDate set True. - - >>> import dateutil.rrule, datetime - >>> vevent = RecurringComponent(name='VEVENT') - >>> vevent.add('rrule').value =u"FREQ=WEEKLY;COUNT=2;INTERVAL=2;BYDAY=TU,TH" - >>> vevent.add('dtstart').value = datetime.datetime(2005, 1, 19, 9) - - When creating rrule's programmatically it should be kept in - mind that count doesn't necessarily mean what rfc2445 says. - - >>> list(vevent.rruleset) - [datetime.datetime(2005, 1, 20, 9, 0), datetime.datetime(2005, 2, 1, 9, 0)] - >>> list(vevent.getrruleset(addRDate=True)) - [datetime.datetime(2005, 1, 19, 9, 0), datetime.datetime(2005, 1, 20, 9, 0)] - - Also note that dateutil will expand all-day events (datetime.date values) to - datetime.datetime value with time 0 and no timezone. - - >>> vevent.dtstart.value = datetime.date(2005,3,18) - >>> list(vevent.rruleset) - [datetime.datetime(2005, 3, 29, 0, 0), datetime.datetime(2005, 3, 31, 0, 0)] - >>> list(vevent.getrruleset(True)) - [datetime.datetime(2005, 3, 18, 0, 0), datetime.datetime(2005, 3, 29, 0, 0)] - + @ivar rruleset: A U{rruleset}. """ def __init__(self, *args, **kwds): super(RecurringComponent, self).__init__(*args, **kwds) - self.isNative=True - #self.clobberedRDates=[] + self.isNative=True def getrruleset(self, addRDate = False): - """Get an rruleset created from self. - + """ + Get an rruleset created from self. + If addRDate is True, add an RDATE for dtstart if it's not included in an RRULE, and count is decremented if it exists. - + Note that for rules which don't match DTSTART, DTSTART may not appear in list(rruleset), although it should. By default, an RDATE is not created in these cases, and count isn't updated, so dateutil may list a spurious occurrence. - + """ rruleset = None for name in DATESANDRULES: @@ -383,9 +367,9 @@ def getrruleset(self, addRDate = False): for line in self.contents.get(name, ()): # don't bother creating a rruleset unless there's a rule if rruleset is None: - rruleset = dateutil.rrule.rruleset() + rruleset = rrule.rruleset() if addfunc is None: - addfunc=getattr(rruleset, name) + addfunc = getattr(rruleset, name) if name in DATENAMES: if type(line.value[0]) == datetime.datetime: @@ -399,34 +383,34 @@ def getrruleset(self, addRDate = False): elif name in RULENAMES: try: dtstart = self.dtstart.value - except AttributeError, KeyError: + except (AttributeError, KeyError): # Special for VTODO - try DUE property instead try: if self.name == "VTODO": dtstart = self.due.value else: # if there's no dtstart, just return None + print('failed to get dtstart with VTODO') return None - except AttributeError, KeyError: + except (AttributeError, KeyError): # if there's no due, just return None + print('failed to find DUE at all.') return None - # rrulestr complains about unicode, so cast to str # a Ruby iCalendar library escapes semi-colons in rrules, # so also remove any backslashes - value = str(line.value).replace('\\', '') - rule = dateutil.rrule.rrulestr(value, dtstart=dtstart) - until = rule._until - if until is not None and \ - isinstance(dtstart, datetime.datetime) and \ - (until.tzinfo != dtstart.tzinfo): + value = str_(line.value).replace('\\', '') + rule = rrule.rrulestr(value, dtstart=dtstart) + until = rule._until + + if until is not None and isinstance(dtstart, datetime.datetime) and \ + (until.tzinfo != dtstart.tzinfo): # dateutil converts the UNTIL date to a datetime, # check to see if the UNTIL parameter value was a date vals = dict(pair.split('=') for pair in line.value.upper().split(';')) if len(vals.get('UNTIL', '')) == 8: - until = datetime.datetime.combine(until.date(), - dtstart.time()) + until = datetime.datetime.combine(until.date(), dtstart.time()) # While RFC2445 says UNTIL MUST be UTC, Chandler allows # floating recurring events, and uses floating UNTIL values. # Also, some odd floating UNTIL but timezoned DTSTART values @@ -437,7 +421,7 @@ def getrruleset(self, addRDate = False): if dtstart.tzinfo is not None: until = until.astimezone(dtstart.tzinfo) - + # RFC2445 actually states that UNTIL must be a UTC value. Whilst the # changes above work OK, one problem case is if DTSTART is floating but # UNTIL is properly specified as UTC (or with a TZID). In that case dateutil @@ -451,10 +435,10 @@ def getrruleset(self, addRDate = False): until = until.replace(tzinfo=None) rule._until = until - + # add the rrule or exrule to the rruleset addfunc(rule) - + if name == 'rrule' and addRDate: try: # dateutils does not work with all-day (datetime.date) items @@ -477,16 +461,16 @@ def getrruleset(self, addRDate = False): return rruleset def setrruleset(self, rruleset): - + # Get DTSTART from component (or DUE if no DTSTART in a VTODO) try: dtstart = self.dtstart.value - except AttributeError, KeyError: + except (AttributeError, KeyError): if self.name == "VTODO": dtstart = self.due.value else: raise - + isDate = datetime.date == type(dtstart) if isDate: dtstart = datetime.datetime(dtstart.year,dtstart.month, dtstart.day) @@ -509,19 +493,19 @@ def setrruleset(self, rruleset): self.add(name).value = setlist elif name in RULENAMES: for rule in setlist: - buf = StringIO.StringIO() + buf = six.StringIO() buf.write('FREQ=') buf.write(FREQUENCIES[rule._freq]) - + values = {} - + if rule._interval != 1: values['INTERVAL'] = [str(rule._interval)] if rule._wkst != 0: # wkst defaults to Monday values['WKST'] = [WEEKDAYS[rule._wkst]] if rule._bysetpos is not None: values['BYSETPOS'] = [str(i) for i in rule._bysetpos] - + if rule._count is not None: values['COUNT'] = [str(rule._count)] elif rule._until is not None: @@ -529,22 +513,21 @@ def setrruleset(self, rruleset): days = [] if (rule._byweekday is not None and ( - dateutil.rrule.WEEKLY != rule._freq or - len(rule._byweekday) != 1 or + rrule.WEEKLY != rule._freq or + len(rule._byweekday) != 1 or rule._dtstart.weekday() != rule._byweekday[0])): # ignore byweekday if freq is WEEKLY and day correlates - # with dtstart because it was automatically set by - # dateutil - days.extend(WEEKDAYS[n] for n in rule._byweekday) - + # with dtstart because it was automatically set by dateutil + days.extend(WEEKDAYS[n] for n in rule._byweekday) + if rule._bynweekday is not None: - days.extend(str(n) + WEEKDAYS[day] for day, n in rule._bynweekday) - + days.extend(n + WEEKDAYS[day] for day, n in rule._bynweekday) + if len(days) > 0: - values['BYDAY'] = days - + values['BYDAY'] = days + if rule._bymonthday is not None and len(rule._bymonthday) > 0: - if not (rule._freq <= dateutil.rrule.MONTHLY and + if not (rule._freq <= rrule.MONTHLY and len(rule._bymonthday) == 1 and rule._bymonthday[0] == rule._dtstart.day): # ignore bymonthday if it's generated by dateutil @@ -556,7 +539,7 @@ def setrruleset(self, rruleset): if rule._bymonth is not None and len(rule._bymonth) > 0: if (rule._byweekday is not None or len(rule._bynweekday or ()) > 0 or - not (rule._freq == dateutil.rrule.YEARLY and + not (rule._freq == rrule.YEARLY and len(rule._bymonth) == 1 and rule._bymonth[0] == rule._dtstart.month)): # ignore bymonth if it's generated by dateutil @@ -569,8 +552,7 @@ def setrruleset(self, rruleset): # byhour, byminute, bysecond are always ignored for now - - for key, paramvals in values.iteritems(): + for key, paramvals in values.items(): buf.write(';') buf.write(key) buf.write('=') @@ -578,8 +560,6 @@ def setrruleset(self, rruleset): self.add(name).value = buf.getvalue() - - rruleset = property(getrruleset, setrruleset) def __setattr__(self, name, value): @@ -589,15 +569,16 @@ def __setattr__(self, name, value): else: super(RecurringComponent, self).__setattr__(name, value) + class TextBehavior(behavior.Behavior): """Provide backslash escape encoding/decoding for single valued properties. - + TextBehavior also deals with base64 encoding if the ENCODING parameter is explicitly set to BASE64. - + """ base64string = 'BASE64' # vCard uses B - + @classmethod def decode(cls, line): """Remove backslash escaping from line.value.""" @@ -608,7 +589,7 @@ def decode(cls, line): else: line.value = stringToTextValues(line.value)[0] line.encoded=False - + @classmethod def encode(cls, line): """Backslash escape line.value.""" @@ -617,47 +598,54 @@ def encode(cls, line): if encoding and encoding.upper() == cls.base64string: line.value = line.value.encode('base64').replace('\n', '') else: - line.value = backslashEscape(line.value) + line.value = backslashEscape(str_(line.value)) line.encoded=True + class VCalendarComponentBehavior(behavior.Behavior): defaultBehavior = TextBehavior isComponent = True + class RecurringBehavior(VCalendarComponentBehavior): - """Parent Behavior for components which should be RecurringComponents.""" + """ + Parent Behavior for components which should be RecurringComponents. + """ hasNative = True - + @staticmethod def transformToNative(obj): - """Turn a recurring Component into a RecurringComponent.""" + """ + Turn a recurring Component into a RecurringComponent. + """ if not obj.isNative: object.__setattr__(obj, '__class__', RecurringComponent) obj.isNative = True return obj - + @staticmethod def transformFromNative(obj): if obj.isNative: object.__setattr__(obj, '__class__', Component) obj.isNative = False return obj - - @staticmethod + + @staticmethod def generateImplicitParameters(obj): - """Generate a UID if one does not exist. - + """ + Generate a UID if one does not exist. + This is just a dummy implementation, for now. - + """ if not hasattr(obj, 'uid'): - rand = str(int(random.random() * 100000)) + rand = int(random.random() * 100000) now = datetime.datetime.now(utc) now = dateTimeToString(now) host = socket.gethostname() - obj.add(ContentLine('UID', [], now + '-' + rand + '@' + host)) - - + obj.add(ContentLine('UID', [], "{0} - {1}@{2}".format(now, rand, host))) + + class DateTimeBehavior(behavior.Behavior): """Parent Behavior for ContentLines containing one DATE-TIME.""" hasNative = True @@ -675,7 +663,7 @@ def transformToNative(obj): if obj.isNative: return obj obj.isNative = True if obj.value == '': return obj - obj.value=str(obj.value) + obj.value=obj.value #we're cheating a little here, parseDtstart allows DATE obj.value=parseDtstart(obj) if obj.value.tzinfo is None: @@ -689,6 +677,7 @@ def transformToNative(obj): @classmethod def transformFromNative(cls, obj): """Replace the datetime in obj.value with an ISO 8601 string.""" + # print('transforming from native') if obj.isNative: obj.isNative = False tzid = TimezoneComponent.registerTzinfo(obj.value.tzinfo) @@ -702,10 +691,12 @@ def transformFromNative(cls, obj): return obj + class UTCDateTimeBehavior(DateTimeBehavior): """A value which must be specified in UTC.""" forceUTC = True + class DateOrDateTimeBehavior(behavior.Behavior): """Parent Behavior for ContentLines containing one DATE or DATE-TIME.""" hasNative = True @@ -716,7 +707,7 @@ def transformToNative(obj): if obj.isNative: return obj obj.isNative = True if obj.value == '': return obj - obj.value=str(obj.value) + obj.value=obj.value obj.value=parseDtstart(obj, allowSignatureMismatch=True) if getattr(obj, 'value_param', 'DATE-TIME').upper() == 'DATE-TIME': if hasattr(obj, 'tzid_param'): @@ -735,11 +726,12 @@ def transformFromNative(obj): return obj else: return DateTimeBehavior.transformFromNative(obj) + class MultiDateBehavior(behavior.Behavior): """ Parent Behavior for ContentLines containing one or more DATE, DATE-TIME, or PERIOD. - + """ hasNative = True @@ -748,7 +740,7 @@ def transformToNative(obj): """ Turn obj.value into a list of dates, datetimes, or (datetime, timedelta) tuples. - + """ if obj.isNative: return obj @@ -772,7 +764,7 @@ def transformFromNative(obj): """ Replace the date, datetime or period tuples in obj.value with appropriate strings. - + """ if obj.value and type(obj.value[0]) == datetime.date: obj.isNative = False @@ -794,11 +786,12 @@ def transformFromNative(obj): obj.value = ','.join(transformed) return obj + class MultiTextBehavior(behavior.Behavior): """Provide backslash escape encoding/decoding of each of several values. - + After transformation, value is a list of strings. - + """ listSeparator = "," @@ -809,19 +802,22 @@ def decode(cls, line): line.value = stringToTextValues(line.value, listSeparator=cls.listSeparator) line.encoded=False - + @classmethod def encode(cls, line): """Backslash escape line.value.""" if not line.encoded: line.value = cls.listSeparator.join(backslashEscape(val) for val in line.value) line.encoded=True - + class SemicolonMultiTextBehavior(MultiTextBehavior): listSeparator = ";" + #------------------------ Registered Behavior subclasses ----------------------- + + class VCalendar2_0(VCalendarComponentBehavior): """vCalendar 2.0 behavior. With added VAVAILABILITY support.""" name = 'VCALENDAR' @@ -839,14 +835,14 @@ class VCalendar2_0(VCalendarComponentBehavior): 'VFREEBUSY': (0, None, None), 'VAVAILABILITY': (0, None, None), } - + @classmethod def generateImplicitParameters(cls, obj): """Create PRODID, VERSION, and VTIMEZONEs if needed. - + VTIMEZONEs will need to exist whenever TZID parameters exist or when datetimes with tzinfo exist. - + """ for comp in obj.components(): if comp.behavior is not None: @@ -877,7 +873,7 @@ def findTzids(obj, table): for child in obj.getChildren(): if obj.name != 'VTIMEZONE': findTzids(child, table) - + findTzids(obj, tzidsUsed) oldtzids = [toUnicode(x.tzid.value) for x in getattr(obj, 'vtimezone_list', [])] for tzid in tzidsUsed.keys(): @@ -886,6 +882,7 @@ def findTzids(obj, table): obj.add(TimezoneComponent(tzinfo=getTzid(tzid))) registerBehavior(VCalendar2_0) + class VTimezone(VCalendarComponentBehavior): """Timezone behavior.""" name = 'VTIMEZONE' @@ -905,8 +902,8 @@ def validate(cls, obj, raiseException, *args): if raiseException: m = "VTIMEZONE components must contain a valid TZID" raise ValidateError(m) - return False - if obj.contents.has_key('standard') or obj.contents.has_key('daylight'): + return False + if 'standard' in obj.contents or 'daylight' in obj.contents: return super(VTimezone, cls).validate(obj, raiseException, *args) else: if raiseException: @@ -929,9 +926,10 @@ def transformFromNative(obj): return obj registerBehavior(VTimezone) + class TZID(behavior.Behavior): """Don't use TextBehavior for TZID. - + RFC2445 only allows TZID lines to be paramtext, so they shouldn't need any encoding or decoding. Unfortunately, some Microsoft products use commas in TZIDs which should NOT be treated as a multi-valued text property, nor @@ -940,6 +938,7 @@ class TZID(behavior.Behavior): """ registerBehavior(TZID) + class DaylightOrStandard(VCalendarComponentBehavior): hasNative = False knownChildren = {'DTSTART': (1, 1, None),#min, max, behaviorRegistry id @@ -958,22 +957,22 @@ class VEvent(RecurringBehavior): "VALARM" calendar components, that represents a scheduled \ amount of time on a calendar.' knownChildren = {'DTSTART': (0, 1, None),#min, max, behaviorRegistry id - 'CLASS': (0, 1, None), + 'CLASS': (0, 1, None), 'CREATED': (0, 1, None), - 'DESCRIPTION': (0, 1, None), - 'GEO': (0, 1, None), + 'DESCRIPTION': (0, 1, None), + 'GEO': (0, 1, None), 'LAST-MODIFIED':(0, 1, None), - 'LOCATION': (0, 1, None), - 'ORGANIZER': (0, 1, None), - 'PRIORITY': (0, 1, None), + 'LOCATION': (0, 1, None), + 'ORGANIZER': (0, 1, None), + 'PRIORITY': (0, 1, None), 'DTSTAMP': (0, 1, None), - 'SEQUENCE': (0, 1, None), - 'STATUS': (0, 1, None), - 'SUMMARY': (0, 1, None), - 'TRANSP': (0, 1, None), - 'UID': (1, 1, None), - 'URL': (0, 1, None), - 'RECURRENCE-ID':(0, 1, None), + 'SEQUENCE': (0, 1, None), + 'STATUS': (0, 1, None), + 'SUMMARY': (0, 1, None), + 'TRANSP': (0, 1, None), + 'UID': (1, 1, None), + 'URL': (0, 1, None), + 'RECURRENCE-ID':(0, 1, None), 'DTEND': (0, 1, None), #NOTE: Only one of DtEnd or 'DURATION': (0, 1, None), # Duration can appear 'ATTACH': (0, None, None), @@ -993,7 +992,7 @@ class VEvent(RecurringBehavior): @classmethod def validate(cls, obj, raiseException, *args): - if obj.contents.has_key('dtend') and obj.contents.has_key('duration'): + if 'dtend' in obj.contents and 'duration' in obj.contents: if raiseException: m = "VEVENT components cannot contain both DTEND and DURATION\ components" @@ -1001,7 +1000,7 @@ def validate(cls, obj, raiseException, *args): return False else: return super(VEvent, cls).validate(obj, raiseException, *args) - + registerBehavior(VEvent) @@ -1015,20 +1014,20 @@ class VTodo(RecurringBehavior): 'CLASS': (0, 1, None), 'COMPLETED': (0, 1, None), 'CREATED': (0, 1, None), - 'DESCRIPTION': (0, 1, None), - 'GEO': (0, 1, None), + 'DESCRIPTION': (0, 1, None), + 'GEO': (0, 1, None), 'LAST-MODIFIED':(0, 1, None), - 'LOCATION': (0, 1, None), - 'ORGANIZER': (0, 1, None), - 'PERCENT': (0, 1, None), - 'PRIORITY': (0, 1, None), + 'LOCATION': (0, 1, None), + 'ORGANIZER': (0, 1, None), + 'PERCENT': (0, 1, None), + 'PRIORITY': (0, 1, None), 'DTSTAMP': (0, 1, None), - 'SEQUENCE': (0, 1, None), - 'STATUS': (0, 1, None), + 'SEQUENCE': (0, 1, None), + 'STATUS': (0, 1, None), 'SUMMARY': (0, 1, None), - 'UID': (0, 1, None), - 'URL': (0, 1, None), - 'RECURRENCE-ID':(0, 1, None), + 'UID': (0, 1, None), + 'URL': (0, 1, None), + 'RECURRENCE-ID':(0, 1, None), 'DUE': (0, 1, None), #NOTE: Only one of Due or 'DURATION': (0, 1, None), # Duration can appear 'ATTACH': (0, None, None), @@ -1048,7 +1047,7 @@ class VTodo(RecurringBehavior): @classmethod def validate(cls, obj, raiseException, *args): - if obj.contents.has_key('due') and obj.contents.has_key('duration'): + if 'due' in obj.contents and 'duration' in obj.contents: if raiseException: m = "VTODO components cannot contain both DUE and DURATION\ components" @@ -1056,7 +1055,7 @@ def validate(cls, obj, raiseException, *args): return False else: return super(VTodo, cls).validate(obj, raiseException, *args) - + registerBehavior(VTodo) @@ -1064,18 +1063,18 @@ class VJournal(RecurringBehavior): """Journal entry behavior.""" name='VJOURNAL' knownChildren = {'DTSTART': (0, 1, None),#min, max, behaviorRegistry id - 'CLASS': (0, 1, None), + 'CLASS': (0, 1, None), 'CREATED': (0, 1, None), - 'DESCRIPTION': (0, 1, None), + 'DESCRIPTION': (0, 1, None), 'LAST-MODIFIED':(0, 1, None), - 'ORGANIZER': (0, 1, None), + 'ORGANIZER': (0, 1, None), 'DTSTAMP': (0, 1, None), - 'SEQUENCE': (0, 1, None), - 'STATUS': (0, 1, None), - 'SUMMARY': (0, 1, None), - 'UID': (0, 1, None), - 'URL': (0, 1, None), - 'RECURRENCE-ID':(0, 1, None), + 'SEQUENCE': (0, 1, None), + 'STATUS': (0, 1, None), + 'SUMMARY': (0, 1, None), + 'UID': (0, 1, None), + 'URL': (0, 1, None), + 'RECURRENCE-ID':(0, 1, None), 'ATTACH': (0, None, None), 'ATTENDEE': (0, None, None), 'CATEGORIES': (0, None, None), @@ -1092,37 +1091,22 @@ class VJournal(RecurringBehavior): class VFreeBusy(VCalendarComponentBehavior): - """Free/busy state behavior. - - >>> vfb = newFromBehavior('VFREEBUSY') - >>> vfb.add('uid').value = 'test' - >>> vfb.add('dtstart').value = datetime.datetime(2006, 2, 16, 1, tzinfo=utc) - >>> vfb.add('dtend').value = vfb.dtstart.value + twoHours - >>> vfb.add('freebusy').value = [(vfb.dtstart.value, twoHours / 2)] - >>> vfb.add('freebusy').value = [(vfb.dtstart.value, vfb.dtend.value)] - >>> print vfb.serialize() - BEGIN:VFREEBUSY - UID:test - DTSTART:20060216T010000Z - DTEND:20060216T030000Z - FREEBUSY:20060216T010000Z/PT1H - FREEBUSY:20060216T010000Z/20060216T030000Z - END:VFREEBUSY - + """ + Free/busy state behavior. """ name='VFREEBUSY' description='A grouping of component properties that describe either a \ request for free/busy time, describe a response to a request \ for free/busy time or describe a published set of busy time.' sortFirst = ('uid', 'dtstart', 'duration', 'dtend') - knownChildren = {'DTSTART': (0, 1, None),#min, max, behaviorRegistry id + knownChildren = {'DTSTART': (0, 1, None), #min, max, behaviorRegistry id 'CONTACT': (0, 1, None), 'DTEND': (0, 1, None), 'DURATION': (0, 1, None), - 'ORGANIZER': (0, 1, None), - 'DTSTAMP': (0, 1, None), - 'UID': (0, 1, None), - 'URL': (0, 1, None), + 'ORGANIZER': (0, 1, None), + 'DTSTAMP': (0, 1, None), + 'UID': (0, 1, None), + 'URL': (0, 1, None), 'ATTENDEE': (0, None, None), 'COMMENT': (0, None, None), 'FREEBUSY': (0, None, None), @@ -1137,7 +1121,7 @@ class VAlarm(VCalendarComponentBehavior): description='Alarms describe when and how to provide alerts about events \ and to-dos.' knownChildren = {'ACTION': (1, 1, None),#min, max, behaviorRegistry id - 'TRIGGER': (1, 1, None), + 'TRIGGER': (1, 1, None), 'DURATION': (0, 1, None), 'REPEAT': (0, 1, None), 'DESCRIPTION': (0, 1, None) @@ -1236,40 +1220,14 @@ def validate(cls, obj, raiseException, *args): return super(VEvent, cls).validate(obj, raiseException, *args) """ return True - registerBehavior(VAlarm) + class VAvailability(VCalendarComponentBehavior): - """Availability state behavior. - - >>> vav = newFromBehavior('VAVAILABILITY') - >>> vav.add('uid').value = 'test' - >>> vav.add('dtstamp').value = datetime.datetime(2006, 2, 15, 0, tzinfo=utc) - >>> vav.add('dtstart').value = datetime.datetime(2006, 2, 16, 0, tzinfo=utc) - >>> vav.add('dtend').value = datetime.datetime(2006, 2, 17, 0, tzinfo=utc) - >>> vav.add('busytype').value = "BUSY" - >>> av = newFromBehavior('AVAILABLE') - >>> av.add('uid').value = 'test1' - >>> av.add('dtstamp').value = datetime.datetime(2006, 2, 15, 0, tzinfo=utc) - >>> av.add('dtstart').value = datetime.datetime(2006, 2, 16, 9, tzinfo=utc) - >>> av.add('dtend').value = datetime.datetime(2006, 2, 16, 12, tzinfo=utc) - >>> av.add('summary').value = "Available in the morning" - >>> ignore = vav.add(av) - >>> print vav.serialize() - BEGIN:VAVAILABILITY - UID:test - DTSTART:20060216T000000Z - DTEND:20060217T000000Z - BEGIN:AVAILABLE - UID:test1 - DTSTART:20060216T090000Z - DTEND:20060216T120000Z - DTSTAMP:20060215T000000Z - SUMMARY:Available in the morning - END:AVAILABLE - BUSYTYPE:BUSY - DTSTAMP:20060215T000000Z - END:VAVAILABILITY + """ + Availability state behavior. + + Used to represent user's available time slots. """ name='VAVAILABILITY' @@ -1295,33 +1253,34 @@ class VAvailability(VCalendarComponentBehavior): @classmethod def validate(cls, obj, raiseException, *args): - if obj.contents.has_key('dtend') and obj.contents.has_key('duration'): + if 'dtend' in obj.contents and 'duration' in obj.contents: if raiseException: - m = "VAVAILABILITY components cannot contain both DTEND and DURATION\ - components" + m = "VAVAILABILITY components cannot contain both DTEND and DURATION components" raise ValidateError(m) return False else: return super(VAvailability, cls).validate(obj, raiseException, *args) - registerBehavior(VAvailability) + class Available(RecurringBehavior): - """Event behavior.""" + """ + Event behavior. + """ name='AVAILABLE' sortFirst = ('uid', 'recurrence-id', 'dtstart', 'duration', 'dtend') description='Defines a period of time in which a user is normally available.' - knownChildren = {'DTSTAMP': (1, 1, None),#min, max, behaviorRegistry id + knownChildren = {'DTSTAMP': (1, 1, None), # min, max, behaviorRegistry id 'DTSTART': (1, 1, None), - 'UID': (1, 1, None), - 'DTEND': (0, 1, None), #NOTE: One of DtEnd or - 'DURATION': (0, 1, None), # Duration must appear, but not both + 'UID': (1, 1, None), + 'DTEND': (0, 1, None), # NOTE: One of DtEnd or + 'DURATION': (0, 1, None), # Duration must appear, but not both 'CREATED': (0, 1, None), 'LAST-MODIFIED':(0, 1, None), - 'RECURRENCE-ID':(0, 1, None), + 'RECURRENCE-ID':(0, 1, None), 'RRULE': (0, 1, None), - 'SUMMARY': (0, 1, None), + 'SUMMARY': (0, 1, None), 'CATEGORIES': (0, None, None), 'COMMENT': (0, None, None), 'CONTACT': (0, None, None), @@ -1331,8 +1290,8 @@ class Available(RecurringBehavior): @classmethod def validate(cls, obj, raiseException, *args): - has_dtend = obj.contents.has_key('dtend') - has_duration = obj.contents.has_key('duration') + has_dtend = 'dtend' in obj.contents + has_duration = 'duration' in obj.contents if has_dtend and has_duration: if raiseException: m = "AVAILABLE components cannot contain both DTEND and DURATION\ @@ -1347,9 +1306,9 @@ def validate(cls, obj, raiseException, *args): return False else: return super(Available, cls).validate(obj, raiseException, *args) - registerBehavior(Available) + class Duration(behavior.Behavior): """Behavior for Duration ContentLines. Transform to datetime.timedelta.""" name = 'DURATION' @@ -1360,7 +1319,7 @@ def transformToNative(obj): """Turn obj.value into a datetime.timedelta.""" if obj.isNative: return obj obj.isNative = True - obj.value=str(obj.value) + obj.value=obj.value if obj.value == '': return obj else: @@ -1380,9 +1339,9 @@ def transformFromNative(obj): obj.isNative = False obj.value = timedeltaToString(obj.value) return obj - registerBehavior(Duration) + class Trigger(behavior.Behavior): """DATE-TIME or DURATION""" name='TRIGGER' @@ -1404,7 +1363,7 @@ def transformToNative(obj): try: return Duration.transformToNative(obj) except ParseError: - logger.warn("TRIGGER not recognized as DURATION, trying " + logger.warning("TRIGGER not recognized as DURATION, trying " "DATE-TIME, because iCal sometimes exports " "DATE-TIMEs without setting VALUE=DATE-TIME") try: @@ -1420,7 +1379,7 @@ def transformToNative(obj): #that fact, for now we take it on faith. return DateTimeBehavior.transformToNative(obj) else: - raise ParseError("VALUE must be DURATION or DATE-TIME") + raise ParseError("VALUE must be DURATION or DATE-TIME") @staticmethod def transformFromNative(obj): @@ -1431,28 +1390,21 @@ def transformFromNative(obj): return Duration.transformFromNative(obj) else: raise NativeError("Native TRIGGER values must be timedelta or datetime") - registerBehavior(Trigger) + class PeriodBehavior(behavior.Behavior): - """A list of (date-time, timedelta) tuples. - - >>> line = ContentLine('test', [], '', isNative=True) - >>> line.behavior = PeriodBehavior - >>> line.value = [(datetime.datetime(2006, 2, 16, 10), twoHours)] - >>> line.transformFromNative().value - '20060216T100000/PT2H' - >>> line.transformToNative().value - [(datetime.datetime(2006, 2, 16, 10, 0), datetime.timedelta(0, 7200))] - >>> line.value.append((datetime.datetime(2006, 5, 16, 10), twoHours)) - >>> print line.serialize().strip() - TEST:20060216T100000/PT2H,20060516T100000/PT2H + """ + A list of (date-time, timedelta) tuples. + """ hasNative = True - + @staticmethod def transformToNative(obj): - """Convert comma separated periods into tuples.""" + """ + Convert comma separated periods into tuples. + """ if obj.isNative: return obj obj.isNative = True @@ -1462,7 +1414,7 @@ def transformToNative(obj): tzinfo = getTzid(getattr(obj, 'tzid_param', None)) obj.value = [stringToPeriod(x, tzinfo) for x in obj.value.split(",")] return obj - + @classmethod def transformFromNative(cls, obj): """Convert the list of tuples in obj.value to strings.""" @@ -1475,16 +1427,18 @@ def transformFromNative(cls, obj): tzid = TimezoneComponent.registerTzinfo(tup[0].tzinfo) if not cls.forceUTC and tzid is not None: obj.tzid_param = tzid - + obj.value = ','.join(transformed) return obj + class FreeBusy(PeriodBehavior): """Free or busy period of time, must be specified in UTC.""" name = 'FREEBUSY' forceUTC = True -registerBehavior(FreeBusy) +registerBehavior(FreeBusy, 'FREEBUSY') + class RRule(behavior.Behavior): """ @@ -1494,28 +1448,28 @@ class RRule(behavior.Behavior): registerBehavior(RRule, 'RRULE') registerBehavior(RRule, 'EXRULE') + #------------------------ Registration of common classes ----------------------- + utcDateTimeList = ['LAST-MODIFIED', 'CREATED', 'COMPLETED', 'DTSTAMP'] -map(lambda x: registerBehavior(UTCDateTimeBehavior, x), utcDateTimeList) +list(map(lambda x: registerBehavior(UTCDateTimeBehavior, x), utcDateTimeList)) dateTimeOrDateList = ['DTEND', 'DTSTART', 'DUE', 'RECURRENCE-ID'] -map(lambda x: registerBehavior(DateOrDateTimeBehavior, x), - dateTimeOrDateList) - +list(map(lambda x: registerBehavior(DateOrDateTimeBehavior, x), dateTimeOrDateList)) + registerBehavior(MultiDateBehavior, 'RDATE') registerBehavior(MultiDateBehavior, 'EXDATE') -textList = ['CALSCALE', 'METHOD', 'PRODID', 'CLASS', 'COMMENT', 'DESCRIPTION', - 'LOCATION', 'STATUS', 'SUMMARY', 'TRANSP', 'CONTACT', 'RELATED-TO', - 'UID', 'ACTION', 'BUSYTYPE'] -map(lambda x: registerBehavior(TextBehavior, x), textList) +textList = ['CALSCALE', 'METHOD', 'PRODID', 'CLASS', 'COMMENT', 'DESCRIPTION', 'LOCATION', + 'STATUS', 'SUMMARY', 'TRANSP', 'CONTACT', 'RELATED-TO', 'UID', 'ACTION', 'BUSYTYPE'] +list(map(lambda x: registerBehavior(TextBehavior, x), textList)) -multiTextList = ['CATEGORIES', 'RESOURCES'] -map(lambda x: registerBehavior(MultiTextBehavior, x), multiTextList) +list(map(lambda x: registerBehavior(MultiTextBehavior, x), ['CATEGORIES', 'RESOURCES'])) registerBehavior(SemicolonMultiTextBehavior, 'REQUEST-STATUS') + #------------------------ Serializing helper functions ------------------------- def numToDigits(num, places): @@ -1529,37 +1483,45 @@ def numToDigits(num, places): return s def timedeltaToString(delta): - """Convert timedelta to an rfc2445 DURATION.""" - if delta.days == 0: sign = 1 - else: sign = delta.days / abs(delta.days) + """ + Convert timedelta to an ical DURATION. + """ + if delta.days == 0: + sign = 1 + else: + sign = delta.days / abs(delta.days) delta = abs(delta) days = delta.days - hours = delta.seconds / 3600 - minutes = (delta.seconds % 3600) / 60 - seconds = delta.seconds % 60 - out = '' - if sign == -1: out = '-' - out += 'P' - if days: out += str(days) + 'D' - if hours or minutes or seconds: out += 'T' - elif not days: #Deal with zero duration - out += 'T0S' - if hours: out += str(hours) + 'H' - if minutes: out += str(minutes) + 'M' - if seconds: out += str(seconds) + 'S' - return out + hours = int(delta.seconds / 3600) + minutes = int((delta.seconds % 3600) / 60) + seconds = int(delta.seconds % 60) + + output = '' + if sign == -1: + output += '-' + output += 'P' + if days: + output += '{}D'.format(days) + if hours or minutes or seconds: + output += 'T' + elif not days: # Deal with zero duration + output += 'T0S' + if hours: + output += '{}H'.format(hours) + if minutes: + output += '{}M'.format(minutes) + if seconds: + output += '{}S'.format(seconds) + return output def timeToString(dateOrDateTime): """ Wraps dateToString and dateTimeToString, returning the results of either based on the type of the argument """ - # Didn't use isinstance here as date and datetime sometimes evalutes as both - if (type(dateOrDateTime) == datetime.date): - return dateToString(dateOrDateTime) - elif(type(dateOrDateTime) == datetime.datetime): + if hasattr(dateOrDateTime, 'hour'): return dateTimeToString(dateOrDateTime) - + return dateToString(dateOrDateTime) def dateToString(date): year = numToDigits( date.year, 4 ) @@ -1568,24 +1530,27 @@ def dateToString(date): return year + month + day def dateTimeToString(dateTime, convertToUTC=False): - """Ignore tzinfo unless convertToUTC. Output string.""" + """ + Ignore tzinfo unless convertToUTC. Output string. + """ if dateTime.tzinfo and convertToUTC: dateTime = dateTime.astimezone(utc) - if tzinfo_eq(dateTime.tzinfo, utc): utcString = "Z" - else: utcString = "" - - year = numToDigits( dateTime.year, 4 ) - month = numToDigits( dateTime.month, 2 ) - day = numToDigits( dateTime.day, 2 ) - hour = numToDigits( dateTime.hour, 2 ) - mins = numToDigits( dateTime.minute, 2 ) - secs = numToDigits( dateTime.second, 2 ) - return year + month + day + "T" + hour + mins + secs + utcString + datestr = "{}{}{}T{}{}{}".format( + numToDigits( dateTime.year, 4 ), + numToDigits( dateTime.month, 2 ), + numToDigits( dateTime.day, 2 ), + numToDigits( dateTime.hour, 2 ), + numToDigits( dateTime.minute, 2 ), + numToDigits( dateTime.second, 2 ), + ) + if tzinfo_eq(dateTime.tzinfo, utc): + datestr += "Z" + return datestr def deltaToOffset(delta): absDelta = abs(delta) - hours = absDelta.seconds / 3600 + hours = int(absDelta.seconds / 3600) hoursString = numToDigits(hours, 2) minutesString = '00' if absDelta == delta: @@ -1602,11 +1567,13 @@ def periodToString(period, convertToUTC=False): txtend = dateTimeToString(period[1], convertToUTC) return txtstart + "/" + txtend + #----------------------- Parsing functions ------------------------------------- + def isDuration(s): - s = string.upper(s) - return (string.find(s, "P") != -1) and (string.find(s, "P") < 2) + s = s.upper() + return (s.find("P") != -1) and (s.find("P") < 2) def stringToDate(s): year = int( s[0:4] ) @@ -1638,7 +1605,7 @@ def stringToDateTime(s, tzinfo=None): def stringToTextValues(s, listSeparator=',', charList=None, strict=False): """Returns list of strings.""" - + if charList is None: charList = escapableCharList @@ -1650,7 +1617,7 @@ def error(msg): raise ParseError(msg) else: #logger.error(msg) - print msg + print(msg) #vars which control state machine charIterator = enumerate(s) @@ -1661,7 +1628,7 @@ def error(msg): while True: try: - charIndex, char = charIterator.next() + charIndex, char = next(charIterator) except: char = "eof" @@ -1682,7 +1649,7 @@ def error(msg): elif state == "read escaped char": if escapableChar(char): state = "read normal" - if char in 'nN': + if char in 'nN': current.append('\n') else: current.append(char) @@ -1722,7 +1689,7 @@ def error(msg): else: raise ParseError(msg) #logger.error(msg) - + #vars which control state machine charIterator = enumerate(s) state = "start" @@ -1738,7 +1705,7 @@ def error(msg): while True: try: - charIndex, char = charIterator.next() + charIndex, char = next(charIterator) except: charIndex += 1 char = "eof" @@ -1760,13 +1727,13 @@ def error(msg): current = current + char #update this part when updating "read field" else: state = "error" - print "got unexpected character %s reading in duration: %s" % (char, s) - error("got unexpected character %s reading in duration: %s" % (char, s)) + # print("got unexpected character {} reading in duration: {}".format(char, s)) + error("got unexpected character {} reading in duration: {}".format(char, s)) elif state == "read field": if (char in string.digits): state = "read field" - current = current + char #update part above when updating "read field" + current = current + char #update part above when updating "read field" elif char.upper() == 'T': state = "read field" elif char.upper() == 'W': @@ -1798,16 +1765,14 @@ def error(msg): day = None hour = None minute = None - sec = None + sec = None elif char == "eof": state = "end" else: state = "error" error("got unexpected character reading in duration: " + s) - - elif state == "end": #an end state - #print "stuff: %s, durations: %s" % ([current, sign, week, day, hour, minute, sec], durations) + elif state == "end": #an end state if (sign or week or day or hour or minute or sec): durations.append( makeTimedelta(sign, week, day, hour, minute, sec) ) return durations @@ -1821,12 +1786,13 @@ def error(msg): error("error: unknown state: '%s' reached in %s" % (state, s)) def parseDtstart(contentline, allowSignatureMismatch=False): - """Convert a contentline's value into a date or date-time. - + """ + Convert a contentline's value into a date or date-time. + A variety of clients don't serialize dates with the appropriate VALUE parameter, so rather than failing on these (technically invalid) lines, if allowSignatureMismatch is True, try to parse both varieties. - + """ tzinfo = getTzid(getattr(contentline, 'tzid_param', None)) valueParam = getattr(contentline, 'value_param', 'DATE-TIME').upper() @@ -1842,7 +1808,7 @@ def parseDtstart(contentline, allowSignatureMismatch=False): raise def stringToPeriod(s, tzinfo=None): - values = string.split(s, "/") + values = s.split("/") start = stringToDateTime(values[0], tzinfo) valEnd = values[1] if isDuration(valEnd): #period-start = date-time "/" dur-value @@ -1912,12 +1878,14 @@ def test(dt): return tzinfo.dst(dt) == zeroDelta return uncorrected + datetime.timedelta(hours=1) def tzinfo_eq(tzinfo1, tzinfo2, startYear = 2000, endYear=2020): - """Compare offsets and DST transitions from startYear to endYear.""" + """ + Compare offsets and DST transitions from startYear to endYear. + """ if tzinfo1 == tzinfo2: return True elif tzinfo1 is None or tzinfo2 is None: return False - + def dt_test(dt): if dt is None: return True @@ -1925,7 +1893,7 @@ def dt_test(dt): if not dt_test(datetime.datetime(startYear, 1, 1)): return False - for year in xrange(startYear, endYear): + for year in range(startYear, endYear): for transitionTo in 'daylight', 'standard': t1=getTransition(transitionTo, year, tzinfo1) t2=getTransition(transitionTo, year, tzinfo2) diff --git a/vobject/ics_diff.py b/vobject/ics_diff.py index 4aaaef9..be91570 100644 --- a/vobject/ics_diff.py +++ b/vobject/ics_diff.py @@ -1,28 +1,35 @@ -"""Compare VTODOs and VEVENTs in two iCalendar sources.""" -from base import Component, getBehavior, newFromBehavior +from __future__ import print_function + +from optparse import OptionParser + +from .base import Component, getBehavior, newFromBehavior, readOne + +""" +Compare VTODOs and VEVENTs in two iCalendar sources. +""" def getSortKey(component): def getUID(component): return component.getChildValue('uid', '') - - # it's not quite as simple as getUID, need to account for recurrenceID and + + # it's not quite as simple as getUID, need to account for recurrenceID and # sequence def getSequence(component): sequence = component.getChildValue('sequence', 0) return "%05d" % int(sequence) - + def getRecurrenceID(component): recurrence_id = component.getChildValue('recurrence_id', None) if recurrence_id is None: return '0000-00-00' else: return recurrence_id.isoformat() - + return getUID(component) + getSequence(component) + getRecurrenceID(component) def sortByUID(components): - return sorted(components, key=getSortKey) + return sorted(components, key=getSortKey) def deleteExtraneous(component, ignore_dtstamp=False): """ @@ -41,21 +48,21 @@ def diff(left, right): """ Take two VCALENDAR components, compare VEVENTs and VTODOs in them, return a list of object pairs containing just UID and the bits - that didn't match, using None for objects that weren't present in one + that didn't match, using None for objects that weren't present in one version or the other. - + When there are multiple ContentLines in one VEVENT, for instance many - DESCRIPTION lines, such lines original order is assumed to be + DESCRIPTION lines, such lines original order is assumed to be meaningful. Order is also preserved when comparing (the unlikely case of) multiple parameters of the same type in a ContentLine - - """ - + + """ + def processComponentLists(leftList, rightList): output = [] rightIndex = 0 rightListSize = len(rightList) - + for comp in leftList: if rightIndex >= rightListSize: output.append((comp, None)) @@ -67,12 +74,12 @@ def processComponentLists(leftList, rightList): output.append((None, rightComp)) rightIndex += 1 if rightIndex >= rightListSize: - output.append((comp, None)) + output.append((comp, None)) break else: rightComp = rightList[rightIndex] rightKey = getSortKey(rightComp) - + if leftKey < rightKey: output.append((comp, None)) elif leftKey == rightKey: @@ -80,7 +87,7 @@ def processComponentLists(leftList, rightList): matchResult = processComponentPair(comp, rightComp) if matchResult is not None: output.append(matchResult) - + return output def newComponent(name, body): @@ -96,14 +103,14 @@ def processComponentPair(leftComp, rightComp): """ Return None if a match, or a pair of components including UIDs and any differing children. - - """ + + """ leftChildKeys = leftComp.contents.keys() rightChildKeys = rightComp.contents.keys() - + differentContentLines = [] differentComponents = {} - + for key in leftChildKeys: rightList = rightComp.contents.get(key, []) if isinstance(leftComp.contents[key][0], Component): @@ -111,18 +118,18 @@ def processComponentPair(leftComp, rightComp): rightList) if len(compDifference) > 0: differentComponents[key] = compDifference - + elif leftComp.contents[key] != rightList: differentContentLines.append((leftComp.contents[key], rightList)) - + for key in rightChildKeys: if key not in leftChildKeys: if isinstance(rightComp.contents[key][0], Component): differentComponents[key] = ([], rightComp.contents[key]) else: differentContentLines.append(([], rightComp.contents[key])) - + if len(differentContentLines) == 0 and len(differentComponents) == 0: return None else: @@ -134,8 +141,8 @@ def processComponentPair(leftComp, rightComp): if uid is not None: left.add( 'uid').value = uid right.add('uid').value = uid - - for name, childPairList in differentComponents.iteritems(): + + for name, childPairList in differentComponents.items(): leftComponents, rightComponents = zip(*childPairList) if len(leftComponents) > 0: # filter out None @@ -143,7 +150,7 @@ def processComponentPair(leftComp, rightComp): if len(rightComponents) > 0: # filter out None right.contents[name] = filter(None, rightComponents) - + for leftChildLine, rightChildLine in differentContentLines: nonEmpty = leftChildLine or rightChildLine name = nonEmpty[0].name @@ -151,42 +158,37 @@ def processComponentPair(leftComp, rightComp): left.contents[name] = leftChildLine if rightChildLine is not None: right.contents[name] = rightChildLine - + return left, right vevents = processComponentLists(sortByUID(getattr(left, 'vevent_list', [])), sortByUID(getattr(right, 'vevent_list', []))) - + vtodos = processComponentLists(sortByUID(getattr(left, 'vtodo_list', [])), sortByUID(getattr(right, 'vtodo_list', []))) - + return vevents + vtodos def prettyDiff(leftObj, rightObj): for left, right in diff(leftObj, rightObj): - print "<<<<<<<<<<<<<<<" + print("<<<<<<<<<<<<<<<") if left is not None: left.prettyPrint() - print "===============" + print("===============") if right is not None: right.prettyPrint() - print ">>>>>>>>>>>>>>>" + print(">>>>>>>>>>>>>>>") print - - -from optparse import OptionParser -import icalendar, base -import os -import codecs + def main(): options, args = getOptions() if args: ignore_dtstamp = options.ignore ics_file1, ics_file2 = args - cal1 = base.readOne(file(ics_file1)) - cal2 = base.readOne(file(ics_file2)) + cal1 = readOne(file(ics_file1)) + cal2 = readOne(file(ics_file2)) deleteExtraneous(cal1, ignore_dtstamp=ignore_dtstamp) deleteExtraneous(cal2, ignore_dtstamp=ignore_dtstamp) prettyDiff(cal1, cal2) @@ -205,9 +207,9 @@ def getOptions(): (cmdline_options, args) = parser.parse_args() if len(args) < 2: - print "error: too few arguments given" + print("error: too few arguments given") print - print parser.format_help() + print(parser.format_help()) return False, False return cmdline_options, args @@ -216,4 +218,4 @@ def getOptions(): try: main() except KeyboardInterrupt: - print "Aborted" + print("Aborted") diff --git a/vobject/vcard.py b/vobject/vcard.py index 068ce29..cdef6ce 100644 --- a/vobject/vcard.py +++ b/vobject/vcard.py @@ -1,12 +1,16 @@ """Definitions and behavior for vCard 3.0""" -import behavior -import itertools +from . import behavior -from base import VObjectError, NativeError, ValidateError, ParseError, \ - VBase, Component, ContentLine, logger, defaultSerialize, \ - registerBehavior, backslashEscape, ascii -from icalendar import stringToTextValues +from .base import ContentLine, registerBehavior, backslashEscape +from .icalendar import stringToTextValues + + +# Python 3 no longer has a basestring type, so.... +try: + basestring = basestring +except NameError: + basestring = (str,bytes) #------------------------ vCard structs ---------------------------------------- @@ -19,7 +23,7 @@ def __init__(self, family = '', given = '', additional = '', prefix = '', self.additional = additional self.prefix = prefix self.suffix = suffix - + @staticmethod def toString(val): """Turn a string or array value into a string.""" @@ -30,7 +34,7 @@ def toString(val): def __str__(self): eng_order = ('prefix', 'given', 'additional', 'family', 'suffix') out = ' '.join(self.toString(getattr(self, val)) for val in eng_order) - return ascii(out) + return out def __repr__(self): return "" % self.__str__() @@ -45,10 +49,13 @@ def __eq__(self, other): except: return False + class Address(object): def __init__(self, street = '', city = '', region = '', code = '', country = '', box = '', extended = ''): - """Each name attribute can be a string or a list of strings.""" + """ + Each name attribute can be a string or a list of strings. + """ self.box = box self.extended = extended self.street = street @@ -56,10 +63,12 @@ def __init__(self, street = '', city = '', region = '', code = '', self.region = region self.code = code self.country = country - + @staticmethod def toString(val, join_char='\n'): - """Turn a string or array value into a string.""" + """ + Turn a string or array value into a string. + """ if type(val) in (list, tuple): return join_char.join(val) return val @@ -73,10 +82,10 @@ def __str__(self): lines += "\n%s, %s %s" % one_line if self.country: lines += '\n' + self.toString(self.country) - return ascii(lines) + return lines def __repr__(self): - return "" % repr(str(self))[1:-1] + return "" % self def __eq__(self, other): try: @@ -89,20 +98,20 @@ def __eq__(self, other): self.country == other.country) except: False - + #------------------------ Registered Behavior subclasses ----------------------- class VCardTextBehavior(behavior.Behavior): """Provide backslash escape encoding/decoding for single valued properties. - + TextBehavior also deals with base64 encoding if the ENCODING parameter is explicitly set to BASE64. - + """ allowGroup = True base64string = 'B' - + @classmethod def decode(cls, line): """Remove backslash escaping from line.valueDecode line, either to remove @@ -121,7 +130,7 @@ def decode(cls, line): else: line.value = stringToTextValues(line.value)[0] line.encoded=False - + @classmethod def encode(cls, line): """Backslash escape line.value.""" @@ -138,8 +147,11 @@ class VCardBehavior(behavior.Behavior): allowGroup = True defaultBehavior = VCardTextBehavior + class VCard3_0(VCardBehavior): - """vCard 3.0 behavior.""" + """ + vCard 3.0 behavior. + """ name = 'VCARD' description = 'vCard 3.0, defined in rfc2426' versionString = '3.0' @@ -156,19 +168,21 @@ class VCard3_0(VCardBehavior): 'PHOTO': (0, None, None), 'CATEGORIES':(0, None, None) } - + @classmethod def generateImplicitParameters(cls, obj): - """Create PRODID, VERSION, and VTIMEZONEs if needed. - + """ + Create PRODID, VERSION, and VTIMEZONEs if needed. + VTIMEZONEs will need to exist whenever TZID parameters exist or when datetimes with tzinfo exist. - + """ if not hasattr(obj, 'version'): obj.add(ContentLine('VERSION', [], cls.versionString)) registerBehavior(VCard3_0, default=True) + class FN(VCardTextBehavior): name = "FN" description = 'Formatted name' @@ -182,6 +196,7 @@ class Label(VCardTextBehavior): wacky_apple_photo_serialize = True REALLY_LARGE = 1E50 + class Photo(VCardTextBehavior): name = "Photo" description = 'Photograph' @@ -219,21 +234,25 @@ def toList(stringOrList): def serializeFields(obj, order=None): """Turn an object's fields into a ';' and ',' seperated string. - + If order is None, obj should be a list, backslash escape each field and return a ';' separated string. """ fields = [] + print("Inside serializeFields") if order is None: fields = [backslashEscape(val) for val in obj] else: for field in order: escapedValueList = [backslashEscape(val) for val in toList(getattr(obj, field))] - fields.append(','.join(escapedValueList)) + fields.append(','.join(escapedValueList)) return ';'.join(fields) + NAME_ORDER = ('family', 'given', 'additional', 'prefix', 'suffix') +ADDRESS_ORDER = ('box', 'extended', 'street', 'city', 'region', 'code', 'country') + class NameBehavior(VCardBehavior): """A structured name.""" @@ -255,29 +274,35 @@ def transformFromNative(obj): return obj registerBehavior(NameBehavior, 'N') -ADDRESS_ORDER = ('box', 'extended', 'street', 'city', 'region', 'code', - 'country') class AddressBehavior(VCardBehavior): - """A structured address.""" + """ + A structured address. + """ hasNative = True @staticmethod def transformToNative(obj): - """Turn obj.value into an Address.""" - if obj.isNative: return obj + """ + Turn obj.value into an Address. + """ + if obj.isNative: + return obj obj.isNative = True obj.value = Address(**dict(zip(ADDRESS_ORDER, splitFields(obj.value)))) return obj @staticmethod def transformFromNative(obj): - """Replace the Address in obj.value with a string.""" + """ + Replace the Address in obj.value with a string. + """ obj.isNative = False obj.value = serializeFields(obj.value, ADDRESS_ORDER) return obj registerBehavior(AddressBehavior, 'ADR') - + + class OrgBehavior(VCardBehavior): """A list of organization values and sub-organization values.""" hasNative = True @@ -287,7 +312,7 @@ def transformToNative(obj): """Turn obj.value into a list.""" if obj.isNative: return obj obj.isNative = True - obj.value = splitFields(obj.value) + # obj.value = splitFields(obj.value) return obj @staticmethod @@ -298,4 +323,4 @@ def transformFromNative(obj): obj.value = serializeFields(obj.value) return obj registerBehavior(OrgBehavior, 'ORG') - +