def __init__(self, address_book, filename=None): self.vcard = None self.address_book = address_book self.filename = filename if self.filename is None: # create new vcard object self.vcard = vobject.vCard() # uid choice = string.ascii_uppercase + string.digits uid_obj = self.vcard.add('uid') uid_obj.value = ''.join([random.choice(choice) for _ in range(36)]) # use uid for vcard filename self.filename = os.path.join(address_book.get_path(), self.vcard.uid.value + ".vcf") else: # create vcard from .vcf file try: file = open(self.filename, "r") contents = file.read() file.close() except IOError as e: raise # create vcard object try: self.vcard = vobject.readOne(contents) except vobject.base.ParseError as e: # if creation fails, try to repair vcard contents try: self.vcard = vobject.readOne( self.filter_invalid_tags(contents)) self.write_to_file(overwrite=True) except vobject.base.ParseError as e: raise
def main(argv=None): print 'Command line: ', sys.argv print confn_src if os.path.exists(user_dir): logging.debug('Clearing user directory: %s', user_dir) shutil.rmtree(user_dir) else: logging.debug('Creating user directory: %s', user_dir) os.makedirs(user_dir) shutil.copyfile(state_src, state_dest) shutil.copyfile(confn_src, confn_dest) global config config = Config(asynk_base_dir=asynk_base_dir, user_dir=user_dir) data = None with open(sys.argv[1], "r") as f: data = f.read() print print data vco = vobject.readOne(data) print vco print vco.prettyPrint() con = CDContact(None, vco=vobject.readOne(data), debug_vcf=True) print unicode(con) print "Display Name: ", con.get_disp_name() print "VCO: ", con.init_vco_from_props().serialize()
def ical2text(ical_string): import vobject result = [] if isinstance(ical_string, unicode): parsedCal = vobject.readOne(ical_string) else: try: parsedCal = vobject.readOne(ical_string) except: parsedCal = vobject.readOne(ical_string.decode('utf-8', 'ignore')) for event in parsedCal.getChildren(): if event.name == 'VEVENT': if hasattr(event, 'dtstart'): start = event.dtstart.value.strftime('%F %H:%M') else: start = 'unknown start date' if hasattr(event, 'dtend'): end = event.dtend.value.strftime('%F %H:%M') else: end = start if start == end: date_str = start else: date_str = '%s -- %s' % (start, end) result.append('%s: %s' % (date_str, event.summary.value)) return '\n'.join(result)
def put(cls, uri, data, content_type, cache=None): import vobject Party = Pool().get('party.party') party_id = cls.vcard(uri) if party_id is None: vcard = vobject.readOne(data) values = Party().vcard2values(vcard) try: party_id, = Party.create([values]) except (ConcurrencyException, UserError, UserWarning): logger.debug('Create party failed', exc_info=True) raise DAV_Forbidden except Exception: logger.error('Create party failed', exc_info=True) raise DAV_Forbidden party = Party(party_id) return (Transaction().database.name + '/Contacts/' + party.uuid + '.vcf') if party_id: party = Party(party_id) vcard = vobject.readOne(data) values = party.vcard2values(vcard) try: Party.write([party], values) except (ConcurrencyException, UserError, UserWarning): logger.debug('Write party failed', exc_info=True) raise DAV_Forbidden except Exception: logger.error('Write party failed', exc_info=True) raise DAV_Forbidden return return super(Collection, cls).put(uri, data, content_type, cache=cache)
def ical2text(ical_string): import vobject result = [] if isinstance(ical_string, str): parsedCal = vobject.readOne(ical_string) else: try: parsedCal = vobject.readOne(ical_string) except Exception: parsedCal = vobject.readOne(ical_string.decode('utf-8', 'ignore')) for event in parsedCal.getChildren(): if event.name == 'VEVENT': if hasattr(event, 'dtstart'): start = event.dtstart.value.strftime('%F %H:%M') else: start = 'unknown start date' if hasattr(event, 'dtend'): end = event.dtend.value.strftime('%F %H:%M') else: end = start if start == end: date_str = start else: date_str = '%s -- %s' % (start, end) result.append('%s: %s' % (date_str, event.summary.value)) return '\n'.join(result)
def testMatches(self): strErik = """BEGIN:VCARD VERSION:3.0 FN:null N:;;;; EMAIL;TYPE=INTERNET:[email protected] END:VCARD """ erikcard = vCardWithMatches( parsevCard(vobject.readOne(StringIO.StringIO(strErik)))) strErik2 = """BEGIN:VCARD VERSION:3.0 FN:Lars Erik Gewalli N:Gewalli hotml;Lars;Erik;; EMAIL;TYPE=INTERNET:[email protected] NOTE:Phone\\:\\nUser 2\\: [email protected]\\n END:VCARD """ erikcard2 = vCardWithMatches( parsevCard(vobject.readOne(StringIO.StringIO(strErik2)))) self.assertFalse(erikcard2.matches(erikcard)) strErik3 = """BEGIN:VCARD VERSION:3.0 FN:Erik M N:Erik;M;;; END:VCARD""" erikcard3 = vCardWithMatches( parsevCard(vobject.readOne(StringIO.StringIO(strErik3)))) #higher similarity is better self.assertFalse(erikcard3.matches(erikcard)) pass
def put(cls, uri, data, content_type, cache=None): pool = Pool() Event = pool.get('calendar.event') Calendar = pool.get('calendar.calendar') calendar_id = cls.calendar(uri) if calendar_id: if not (uri[10:].split('/', 1) + [None])[1]: raise DAV_Forbidden event_id = cls.event(uri, calendar_id=calendar_id) if not event_id: ical = vobject.readOne(data) values = Event.ical2values(None, ical, calendar_id) event, = Event.create([values]) calendar = Calendar(calendar_id) return (Transaction().cursor.database_name + '/Calendars/' + calendar.name + '/' + event.uuid + '.ics') else: ical = vobject.readOne(data) values = Event.ical2values(event_id, ical, calendar_id) Event.write([Event(event_id)], values) return calendar_ics_id = cls.calendar(uri, ics=True) if calendar_ics_id: raise DAV_Forbidden return super(Collection, cls).put(uri, data, content_type)
def __init__(self, addressbook_name, addressbook_path, filename=""): self.addressbook_name = addressbook_name if filename == "": # create new vcard self.vcard = vobject.vCard() choice = string.ascii_uppercase + string.digits uid_obj = self.vcard.add('uid') uid_obj.value = ''.join([random.choice(choice) for _ in range(36)]) self.vcard_full_filename = os.path.join(addressbook_path, self.vcard.uid.value + ".vcf") else: # create vcard from file self.vcard_full_filename = filename # open .vcf file try: file = open(filename, "r") contents = file.read() file.close() except IOError as e: raise CarddavObject.VCardParseError(e) # create vcard object try: self.vcard = vobject.readOne(contents) except vobject.base.ParseError as e: # if creation fails, try to repair vcard contents try: self.vcard = vobject.readOne( self.filter_invalid_tags(contents)) self.write_to_file(overwrite=True) except vobject.base.ParseError as e: raise CarddavObject.VCardParseError(e)
async def test_create_todo_from_vobject_2(backend, principal, todo_fixtures): vtodo = vobject.readOne(todo_fixtures) try: _ = vtodo.vtodo.status except AttributeError: # no status if backend.get("name") == "radicale": pytest.skip() cal_id = uuid.uuid4().hex cal = await principal.make_calendar(name="Yep", cal_id=cal_id) # add event from vobject data vtodo_fixtures = vobject.readOne(todo_fixtures) await cal.add_todo(vtodo_fixtures) todos = await cal.todos(include_completed=False) try: _ = vtodo.vtodo.completed except (AttributeError, KeyError): # no completed, should be in the list assert len(todos) == 1 else: assert len(todos) == 0 events = await cal.events() assert len(events) == 0 journals = await cal.journals() assert len(journals) == 0
def __init__(self, address_book, filename = None): self.vcard = None self.address_book = address_book self.filename = filename if self.filename is None: # create new vcard object self.vcard = vobject.vCard() # uid choice = string.ascii_uppercase + string.digits uid_obj = self.vcard.add('uid') uid_obj.value = ''.join([random.choice(choice) for _ in range(36)]) # use uid for vcard filename self.filename = os.path.join(address_book.get_path(), self.vcard.uid.value + ".vcf") else: # create vcard from .vcf file try: file = open(self.filename, "r") contents = file.read() file.close() except IOError as e: raise # create vcard object try: self.vcard = vobject.readOne(contents) except vobject.base.ParseError as e: # if creation fails, try to repair vcard contents try: self.vcard = vobject.readOne( self.filter_invalid_tags(contents)) self.write_to_file(overwrite=True) except vobject.base.ParseError as e: raise
def put(cls, uri, data, content_type, cache=None): import vobject Party = Pool().get('party.party') party_id = cls.vcard(uri) if party_id is None: vcard = vobject.readOne(data) values = Party().vcard2values(vcard) try: party_id, = Party.create([values]) except Exception: raise DAV_Forbidden party = Party(party_id) return (Transaction().cursor.database_name + '/Contacts/' + party.uuid + '.vcf') if party_id: party = Party(party_id) vcard = vobject.readOne(data) values = party.vcard2values(vcard) try: Party.write([party], values) except Exception: raise DAV_Forbidden return return super(Collection, cls).put(uri, data, content_type, cache=cache)
def put(cls, uri, data, content_type, cache=None): import vobject Party = Pool().get('party.party') party_id = cls.vcard(uri) if party_id is None: vcard = vobject.readOne(data) values = Party().vcard2values(vcard) try: party_id, = Party.create([values]) except Exception: raise DAV_Forbidden party = Party(party_id) return (Transaction().database.name + '/Contacts/' + party.uuid + '.vcf') if party_id: party = Party(party_id) vcard = vobject.readOne(data) values = party.vcard2values(vcard) try: Party.write([party], values) except Exception: raise DAV_Forbidden return return super(Collection, cls).put(uri, data, content_type, cache=cache)
def testMatches(self): strErik = """BEGIN:VCARD VERSION:3.0 FN:null N:;;;; EMAIL;TYPE=INTERNET:[email protected] END:VCARD """ erikcard=vCardWithMatches(parsevCard(vobject.readOne(StringIO.StringIO(strErik)))) strErik2 = """BEGIN:VCARD VERSION:3.0 FN:Lars Erik Gewalli N:Gewalli hotml;Lars;Erik;; EMAIL;TYPE=INTERNET:[email protected] NOTE:Phone\\:\\nUser 2\\: [email protected]\\n END:VCARD """ erikcard2=vCardWithMatches(parsevCard(vobject.readOne(StringIO.StringIO(strErik2)))) self.assertFalse(erikcard2.matches(erikcard)) strErik3="""BEGIN:VCARD VERSION:3.0 FN:Erik M N:Erik;M;;; END:VCARD""" erikcard3=vCardWithMatches(parsevCard(vobject.readOne(StringIO.StringIO(strErik3)))) #higher similarity is better self.assertFalse(erikcard3.matches(erikcard)) pass
def __init__(self, address_book, filename = None): self.vcard = None self.address_book = address_book self.filename = filename self.old_vobject_version = False # at the moment khard must support two different behavior of the vobject module # the versions < 0.8.2 are still widely in use and expect unicode strings for non-ascii characters # all newer versions use utf-8 encoded strings directly # so we must determine, which version is installed try: # try to compare the version numbers if parse_version(get_distribution("vobject").version) < parse_version("0.8.2"): self.old_vobject_version = True except Exception as e: # if something goes wrong during vobject version comparison, try to serialize a # minimal vcard object with umlauts # if that fails, khard still uses a vobject version < 0.8.2 v = vobject.vCard() o = v.add("fn") o.value = "Markus Schröder" o = v.add("n") o.value = vobject.vcard.Name(family="Schröder", given="Markus") try: v.serialize() except UnicodeDecodeError as e: self.old_vobject_version = True # load vcard if self.filename is None: # create new vcard object self.vcard = vobject.vCard() # uid choice = string.ascii_uppercase + string.digits uid_obj = self.vcard.add('uid') uid_obj.value = ''.join([random.choice(choice) for _ in range(36)]) # use uid for vcard filename self.filename = os.path.join(address_book.get_path(), self.vcard.uid.value + ".vcf") else: # create vcard from .vcf file try: file = open(self.filename, "r") contents = file.read() file.close() except IOError as e: raise # create vcard object try: self.vcard = vobject.readOne(contents) except vobject.base.ParseError as e: # if creation fails, try to repair vcard contents try: self.vcard = vobject.readOne( self.filter_invalid_tags(contents)) self.write_to_file(overwrite=True) except vobject.base.ParseError as e: raise
def read_ics(): try: with warnings.catch_warnings(): warnings.simplefilter("ignore") invitation = vobject.readOne(sys.stdin, ignoreUnreadable=True) except AttributeError: invitation = vobject.readOne(sys.stdin, ignoreUnreadable=True) return invitation
def get_invitation_from_path(path): with open(path) as f: try: # vobject uses deprecated Exceptions with warnings.catch_warnings(): warnings.simplefilter("ignore") return vobject.readOne(f, ignoreUnreadable=True) except AttributeError: return vobject.readOne(f, ignoreUnreadable=True)
def openics(invitation_file): with open(invitation_file) as f: try: with warnings.catch_warnings(): #vobject uses deprecated Exception stuff warnings.simplefilter("ignore") invitation = vobject.readOne(f, ignoreUnreadable=True) except AttributeError: invitation = vobject.readOne(f, ignoreUnreadable=True) return invitation
def merge(filenames, timezone_file): combined_calendar = vobject.iCalendar() with codecs.open(timezone_file, encoding='utf-8') as f: merge_timezones(combined_calendar, vobject.readOne(f)) for filename in filenames: with codecs.open(filename, 'r', encoding='utf-8') as f: merge_events(combined_calendar, vobject.readOne(f)) return combined_calendar.serialize()
def _get(self, href): """Fetch a single item.""" if self.is_fake: return try: href_mapper = HrefMapper.get(HrefMapper.href == href) uid = href_mapper.content.uid except HrefMapper.DoesNotExist: return None etesync_item = self.collection.get(uid) if etesync_item is None: return None try: item = vobject.readOne(etesync_item.content) # XXX Hack: fake transform 4.0 vCards to 3.0 as 4.0 is not yet widely supported if item.name == 'VCARD' and item.contents['version'][ 0].value == '4.0': # Don't do anything for groups as transforming them won't help anyway. if hasattr(item, 'kind') and item.kind.value.lower() == 'group': pass else: # XXX must be first because we are editing the content and reparsing if 'photo' in item.contents: content = etesync_item.content content = VCARD_4_TO_3_PHOTO_URI_REGEX.sub( r'\1;VALUE=uri:', content) content = VCARD_4_TO_3_PHOTO_INLINE_REGEX.sub( r'\1;ENCODING=b;TYPE=\2:', content) item = vobject.readOne(content) if content == etesync_item.content: # Delete the PHOTO if we haven't managed to convert it del item.contents['photo'] item.contents['version'][0].value = '3.0' except Exception as e: raise RuntimeError("Failed to parse item %r in %r" % (href, self.path)) from e last_modified = '' return EteSyncItem(collection=self, vobject_item=item, href=href, last_modified=last_modified, etesync_item=etesync_item)
def parse_ics_file(source_type, event_name, filename, color, symbol): print "Parsing file for " + event_name + ":", filename ics_file = file(filename) ical = vobject.readOne(ics_file) #add each event to calendar for event in ical.vevent_list: date = event.dtstart.value if isinstance(date, datetime.datetime): date = date.date() #fetch leap day if date.month == 2 and date.day == 29 and not calendar.isleap(this_year): continue # calculate anniversaries if event_name == "anniversary": age = this_year - date.year event.summary.value += " " + str(age) #check if events not belonging to current year are recurrent and should be applied anyway if date.year != this_year: if recurring_event(event): date = date.replace(year=this_year) else: continue #create a new field, content is taken from the event summary new_event = my_class.event(event_name, event.summary.value, color, symbol) my_container.get_day_by_date(date).add_event(new_event) return 0
def vcard_updated(self, href, vcard): if href in self.key_from_href: (key,iter) = self.key_from_href[href] vcard = vobject.readOne(vcard) self.update_treeview_values(vcard, iter) (href, etag, _, _) = self.card_list_sql[key] self.card_list_sql[key] = (href, etag, vcard, 0)
def parse_vcf(self,response): v=vobject.readOne(response.body) print v item=response.meta['item'] item['first_name']=v.n.value.given.strip() item['second_name']=v.n.value.family.strip() yield item
def read_vcard(vcard_url) -> Union[Component, None]: try: vcard = requests.get(vcard_url).text return vobject.readOne(vcard) # pylint: disable=bare-except except: return None
def get_all_vcards(self, parse=True): """ Get all the contacts as a list of vcards. The vcards are parsed from plain text into vobject.vCard form (a python wrapper class) by default. :param parse: set this to False to return just the raw text :return: list of vcards :rtype: list """ resp, data = self.conn.get("contacts.vcf") data = data.replace("END:VCARDBEGIN:VCARD", "END:VCARD\nBEGIN:VCARD") data = data.strip() vcards = [] while True: i = data.find("END:VCARD") if i > -1: i += len("END:VCARD") text = data[:i] data = data[i:] if parse: vcard = vobject.readOne(text.strip()) vcards.append(vcard) else: vcards.append(text.strip()) else: # no more left, we're done break return vcards
def update_document(data): remote = urllib2.urlopen(config.get(CONFIG_KEY, 'url'), timeout=config.getint(CONFIG_KEY, 'timeout')) current_date = datetime.datetime.now() if not data.get('events'): data['events'] = [] components = vobject.readOne(remote) for event in components.contents['vevent']: # could be datetime or just date e_date = event.dtstart.value if type(e_date) is datetime.date: e_date = datetime.datetime.combine(e_date, datetime.time(0, 0)) else: e_date = e_date.replace(tzinfo=None) # compare with timezone data removed if e_date < current_date: continue data['events'].append({ 'name': event.summary.value, 'type': 'calendarevent', 'timestamp': int(time.mktime((event.dtstart.value.timetuple()))), 'extra': event.description.value, }) return data
def _clean_private(cls, record, transp): ''' Clean private record ''' summary = cls.raise_user_error(transp, raise_exception=False) if 'summary' in record: record['summary'] = summary vevent = None if 'vevent' in record: vevent = record['vevent'] if vevent: vevent = vobject.readOne(str(vevent)) if hasattr(vevent, 'summary'): vevent.summary.value = summary for field, value in ( ('description', ''), ('categories', []), ('location', None), ('status', ''), ('organizer', ''), ('attendees', []), ('alarms', [])): if field in record: record[field] = value if field + '.rec_name' in record: record[field + '.rec_name'] = '' if vevent: if hasattr(vevent, field): delattr(vevent, field) if vevent: record['vevent'] = vevent.serialize()
def define_BSWEvent( self, start, end, summary, location, description, anzteilnehmer=None, organizer=None, ): dtstart = ("DTSTART;TZID=Europe/Berlin:" + start.strftime("%Y%m%dT%H%M%S") + "\n") dtend = ("DTEND;TZID=Europe/Berlin:" + end.strftime("%Y%m%dT%H%M%S") + "\n") categories = "CATEGORIES:BSW-ANFRAGE" if anzteilnehmer is not None: categories += ",Bedarf=" + str(anzteilnehmer) categories += "\n" bswtemp = vobject.readOne(BSWEventStart + dtstart + dtend + categories + BSWEventEnd) bswtemp.vevent.add("summary").value = summary bswtemp.vevent.add("description").value = description bswtemp.vevent.add("location").value = location if organizer is not None: tname, tmail = organizer tparams = {"CN": [tname]} bswtemp.vevent.add("organizer").value = "mailto:" + tmail bswtemp.vevent.contents["organizer"][0].params = tparams return bswtemp.serialize()
def get_info_list(vcard_filepath): vcard = collections.OrderedDict() for column in column_order: vcard[column] = None name = cell = work = home = email = note = None with open(vcard_filepath) as fp: vCard_text = fp.read() vCard = vobject.readOne(vCard_text) vCard.validate() for key, val in list(vCard.contents.items()): if key == 'fn': vcard['Full name'] = vCard.fn.value elif key == 'n': name = str(vCard.n.valueRepr()).replace(' ', ' ').strip() vcard['Name'] = name elif key == 'tel': cell, home, work = get_phone_numbers(vCard) vcard['Cell phone'] = cell vcard['Home phone'] = home vcard['Work phone'] = work elif key == 'email': email = str(vCard.email.value).strip() vcard['Email'] = email elif key == 'note': note = str(vCard.note.value) vcard['Note'] = note else: # An unused key, like `adr`, `title`, `url`, etc. pass if name is None: logging.warning("no name for file `{}'".format(vcard_filepath)) if all(telephone_number is None for telephone_number in [cell, work, home]): logging.warning("no telephone numbers for file `{}' with name `{}'".format(vcard_filepath, name)) return vcard
def serialize(self): if not os.path.exists(self._filesystem_path): return None items = [] for href in os.listdir(self._filesystem_path): if not is_safe_filesystem_path_component(href): self.logger.debug("Skipping component: %s", href) continue path = os.path.join(self._filesystem_path, href) if os.path.isfile(path): self.logger.debug("Read object: %s", path) with open(path, encoding=self.encoding, newline="") as fd: items.append(vobject.readOne(fd.read())) if self.get_meta("tag") == "VCALENDAR": collection = vobject.iCalendar() for item in items: for content in ("vevent", "vtodo", "vjournal"): if content in item.contents: for item_part in getattr(item, "%s_list" % content): collection.add(item_part) break return collection.serialize() elif self.get_meta("tag") == "VADDRESSBOOK": return "".join([item.serialize() for item in items]) return ""
def parse_vcard(filepath): with open(filepath, 'r') as vcard_file: text = vcard_file.read() vcard = vobject.readOne(text) name = vcard.getChildValue('fn') numbers = [x.value for x in vcard.tel_list] return name, numbers
def _get_vcard(self, session, url_vcard, settings, debug=False): if debug: print("_get_vcard(%s)" % url_vcard) response = session.get(url_vcard, headers=[], **settings) self._raise_for_status_code(response) #if debug: print("Response: %s" % response.content) ret = vobject.readOne(response.content) return ret
def getWakeUpTimes(self): retrive_iCal.retrive() self.lastRetrived = datetime.datetime.now() if os.path.exists("calender.ical") and \ self.lastParsed == os.path.getmtime("calender.ical"): return else: self.lastParsed = os.path.getmtime("calender.ical") self.wakeUpTimes = [] iCalFile = open("calender.ical") parsedCal = vobject.readOne(iCalFile) for event in parsedCal.vevent_list: try: event.categories.value except: continue if event.categories.value == [u'WakeUp']: tz = event.dtstart.value.tzinfo start = event.dtstart.value.utctimetuple() end = event.dtend.value.utctimetuple() diff = event.dtend.value - event.dtstart.value now = datetime.datetime.utcnow().utctimetuple() #Reacuring event if event.rruleset: for date in event.rruleset: start = date.utctimetuple() end = date + diff end = end.utctimetuple() if end > now: break #alarm found #only append if alarm havent allready gone off if end > now: self.wakeUpTimes.append([start, end])
def vcard_added(self, href, etag, vcard): self.max_key += 1 vcard = vobject.readOne(vcard) self.card_list_sql[self.max_key] = (href,etag,vcard,0) treeiter = self.model.append( (self.max_key, '', '', '', 400, '') ) self.key_from_href[href] = (self.max_key, treeiter) self.update_treeview_values(vcard, treeiter)
def read_contacts_from_db(self, sqlFilepath, convert=False, sort=False): conn = sqlite3.connect(sqlFilepath) conn.execute('CREATE TABLE if not exists vcards (etag text primary key unique not null, href text unique not null, vcard text not null, local_status smallint default 0)') conn.commit() for self.max_key,(href,etag,vcard,local_status) in enumerate(conn.execute('select href,etag,vcard,local_status from vcards where local_status<>2').fetchall(), self.max_key): card = vobject.readOne(vcard) if not hasattr(card, 'fn'): card.add('fn') if not hasattr(card, 'n'): card.add('n') if not hasattr(card, 'version'): card.add('version') card.version.value = "2.1" if convert: if card.version.value == "2.1": vcard21_to_vcard30(card) if card.version.value != "3.0": raise exception.NotImplementedError if sort: for val in ('tel_list', 'email_list', 'adr_list'): if hasattr(card,val): getattr(card, val).sort(key=vcard_get_pref_value) # TODO: remove the next line(s) if hasattr(card, 'label'): print(card.label.value) iter = self.model.append( (self.max_key, '', '', '', 400, '') ) self.update_treeview_values(card, iter) self.card_list_sql[self.max_key] = (href,etag,card,local_status) self.key_from_href[href] = (self.max_key, iter)
def caldav_return(): cal = get_calendar() now = datetime.now(tz=home_tz) # timezone? timeMin = home_tz.localize(datetime(year=now.year, month=now.month, day=now.day, hour=now.hour, minute=now.minute, second=now.second )) timeMax = home_tz.localize(datetime(year=now.year, month=now.month, day=now.day, hour=now.hour, minute=now.minute, second=now.second ) + timedelta(minutes=1)) #print timeMax #print timeMin return_temp = 13.6654 evs = cal.date_search(timeMin, timeMax) for event in evs: try: cal = Calendar.from_ical(smart_str(event.data)) ev0 = cal.walk('vevent')[0] parsedCal = vobject.readOne(event.data) tempstring = str(ev0['SUMMARY']).replace("\\,",",") match = regex_temp.search(tempstring) if match: target_temp = float(match.group(1)) return_temp = target_temp except Exception, exc: return_temp = 13.6654 #print return_temp return return_temp
def Sync(self): flag = raw_input("Enter '0' to exit program or any other key to continue: ") if flag == '0': exit() vcf_path = os.path.dirname(os.path.abspath(__file__)) vcf_list = glob.glob(vcf_path + "\*.vcf") count = 0 for people in vcf_list: fp = open(people,"r") content = fp.read() fp.close() v = vobject.readOne(content) name=v.n.value number=v.tel.value new_contact = gdata.contacts.data.ContactEntry() new_contact.name = gdata.data.Name(full_name=gdata.data.FullName(text=name)) new_contact.phone_number.append(gdata.data.PhoneNumber(text=number,rel=gdata.data.WORK_REL,primary='true')) contact_entry = self.gd_client.CreateContact(new_contact) print "Contact's ID: ", contact_entry.id.text name ="" number = "" count = count + 1 print "\nUploaded Contacts: " + str(count) time.sleep(1)
def __init__(self, text, name=None): """Initialize object from ``text`` and different ``kwargs``.""" self.component = vobject.readOne(text) self._name = name if not self.component.name: # Header self._name = next(self.component.lines()).name.lower() return # We must synchronize the name in the text and in the object. # An item must have a name, determined in order by: # # - the ``name`` parameter # - the ``X-RADICALE-NAME`` iCal property (for Events, Todos, Journals) # - the ``UID`` iCal property (for Events, Todos, Journals) # - the ``TZID`` iCal property (for Timezones) if not self._name: for line in self.component.lines(): if line.name in ("X-RADICALE-NAME", "UID", "TZID"): self._name = line.value if line.name == "X-RADICALE-NAME": break if self._name: # Leading and ending brackets that may have been put by Outlook. # Slashes are mostly unwanted when saving collections on disk. self._name = self._name.strip("{}").replace("/", "_") else: self._name = uuid4().hex if not hasattr(self.component, "x_radicale_name"): self.component.add("X-RADICALE-NAME") self.component.x_radicale_name.value = self._name
def setUp(self): vcard_data = dict( nickname=u'x', mobile=u'3333308', name=u'NAME SURNAME', firstname=u'NAME', surname=u'SURNAME', email=u'*****@*****.**') self.vcard_data = namedtuple('Contact', vcard_data.keys())( **vcard_data) self.contact = Contact(alias=self.vcard_data.nickname, mobile=self.vcard_data.mobile, name=self.vcard_data.name) vcard_str = """ BEGIN:VCARD VERSION:3.0 FN:{name} N:{surname};{firstname};;; NICKNAME:{nickname} EMAIL;TYPE=INTERNET:{email} TEL;TYPE=CELL:{mobile} END:VCARD """.format( name=self.vcard_data.name, firstname=self.vcard_data.firstname, surname=self.vcard_data.surname, nickname=self.vcard_data.nickname, email=self.vcard_data.email, mobile=self.vcard_data.mobile) self.vcard_str = textwrap.dedent(vcard_str) self.vcard = vobject.readOne(self.vcard_str)
def put(cls, uri, data, content_type, cache=None): pool = Pool() Todo = pool.get('calendar.todo') Calendar = pool.get('calendar.calendar') calendar_id = cls.calendar(uri) if calendar_id: if not (uri[10:].split('/', 1) + [None])[1]: raise DAV_Forbidden todo_id = cls.todo(uri, calendar_id=calendar_id) ical = vobject.readOne(data) if not hasattr(ical, 'vtodo'): return super(Collection, cls).put(uri, data, content_type) if not todo_id: values = Todo.ical2values(None, ical, calendar_id) todo, = Todo.create([values]) calendar = Calendar(calendar_id) return Transaction().database.name + '/Calendars/' + \ calendar.name + '/' + todo.uuid + '.ics' else: values = Todo.ical2values(todo_id, ical, calendar_id) Todo.write([Todo(todo_id)], values) return return super(Collection, cls).put(uri, data, content_type)
def fetch(name): """ Perform an HTTP GET request to download the calendar specified by name. If the response we get is OK (200), the response text is parsed into a calendar object using the vobject library and returned. Otherwise, return None. """ # It may seem weird to have a random string hanging out at the top # of a function definition. In Python this is how you document code. # Python has a built-in help() function that will display the help- # string for whatever is passed. For example: `help(fetch)` in an # interactive Python interpreter will display the above text. # The full URL is formatted from the URL template and # the name of the file. response = requests.get(CALENDAR_URL_TEMPLATE.format(name)) if response.ok: # Server responded 200 (ok), we should have the requested # calendar file in the response text. # The response text is parsed into a calendar and returned. return vobject.readOne(response.text) else: # Something went wrong, return None (a null value). return None
def get_info_list(file): name = cell = work = home = email = note = None vCard_text = open(file).read() vCard = vobject.readOne(vCard_text) vCard.validate() for key, val in vCard.contents.iteritems(): if key == 'fn': name = vCard.fn.value elif key == 'n': if name is None: # May get overwritten if full name is available. name = str(vCard.n.valueRepr()).replace(' ', ' ').strip() elif key == 'tel': cell, home, work = get_phone_numbers(vCard) elif key == 'email': email = str(vCard.email.value).strip() elif key == 'note': note = str(vCard.note.value) else: # An unused key, like `adr`, `title`, `url`, etc. pass if name is None: print "Warning: no name for file `"+file+"`" if all(telephone_number is None for telephone_number in [cell, work, home]): print "Warning: no telephone number for file `"+file+"` with name `"+name+"`" return [name, cell, work, home, email, note]
def rcynic_gbr(gbr, obj): vcard = vobject.readOne(gbr.vcard) obj.full_name = vcard.fn.value if hasattr(vcard, 'fn') else None obj.email_address = vcard.email.value if hasattr(vcard, 'email') else None obj.telephone = vcard.tel.value if hasattr(vcard, 'tel') else None obj.organization = vcard.org.value[0] if hasattr(vcard, 'org') else None obj.save()
def _clean_confidential(cls, record, transp): ''' Clean confidential record ''' summary = cls.raise_user_error(transp, raise_exception=False) if 'summary' in record: record['summary'] = summary vevent = None if 'vevent' in record: vevent = record['vevent'] if vevent: vevent = vobject.readOne(str(vevent)) if hasattr(vevent, 'summary'): vevent.summary.value = summary for field, value in ( ('description', ''), ('categories', []), ('location', None), ('status', ''), ('organizer', ''), ('attendees', []), ('alarms', [])): if field in record: record[field] = value if field + '.rec_name' in record: record[field + '.rec_name'] = '' if vevent: if hasattr(vevent, field): delattr(vevent, field) if vevent: record['vevent'] = vevent.serialize()
def update_contact(self, contact, schema_out=None, user_session=None): """ ```in contact = (O) !threebot.calendar.contact.1 ``` ```out contact = (O) !threebot.calendar.contact.1 ``` """ contacts = self.contact_model.find(contact_id=contact.contact_id) if not contacts: raise j.exceptions.NotFound( f"Couldn't find contact with id: {contact.contact_id}") c = contacts[0] old = vobject.readOne(c.content) uid_ = old.uid.value vcard = self._get_vcard_from_contact(contact) # restore old UID vcard.uid.value = uid_ self.client.update_vcard( vcard.serialize(), f"/{self.user}/{c.addressbook_id}/{c.item_id}", None) return self.contact_model.find(item_id=c.item_id)[0]
def import_vcard(vin): """Convert a _single_ vcard (text) to a mfdict. Parameters: in - a string or a file object """ vcard = vobject.readOne(vin) mfd = uf_mfdict.mfdict() for child in vcard.getChildren(): if type(child.value) not in types.StringTypes: child.value = unicode(child.value) if child.name == "N": d = dict(zip(vobject.vcard.NAME_ORDER, vobject.vcard.splitFields(child.value))) elif child.name == "ADR": d = dict(zip(vobject.vcard.ADDRESS_ORDER, vobject.vcard.splitFields(child.value))) else: d = { "" : child.value } ctype = child.params.get("TYPE", []) for key, value in d.iteritems(): keys = filter(lambda s: s, [ child.name.lower(), key, ] + ctype) if type(value) == types.ListType: value = " ".join(value) value = clean_space(value) mfd.add(keys, value) return mfd
def get(self, href): """Fetch a single item.""" if self.is_fake: return try: href_mapper = HrefMapper.get(HrefMapper.href == href) uid = href_mapper.content.uid except HrefMapper.DoesNotExist: return None etesync_item = self.collection.get(uid) try: item = vobject.readOne(etesync_item.content) # XXX Hack: fake transform 4.0 vCards to 3.0 as 4.0 is not yet widely supported if item.name == 'VCARD' and item.contents['version'][0].value == '4.0': # Don't do anything for groups as transforming them won't help anyway. if hasattr(item, 'kind') and item.kind.value.lower() == 'group': pass else: item.contents['version'][0].value = '3.0' if 'photo' in item.contents: del item.contents['photo'] except Exception as e: raise RuntimeError("Failed to parse item %r in %r" % (href, self.path)) from e # FIXME: Make this sensible last_modified = time.strftime( "%a, %d %b %Y %H:%M:%S GMT", time.gmtime(time.time())) return EteSyncItem(self, item, href, last_modified=last_modified, etesync_item=etesync_item)
def fProcess_ics(self, file): """ Read an ics (ical) file and append it to the reminders file. """ try: src = open(self.get_inputdir() + '/' + file) dst = open(self.get_outputfile(),"a") try: tzinput = timezone('Etc/UTC') # ics files from http://www.mysportscal.com datefmt = '%b %d %Y' timefmt = '%H:%M' remfmt = 'REM %s AT %s +30 DURATION %s MSG %s' cal = vobject.readOne(src) for event in cal.vevent_list: text = event.summary.value dtstart = event.dtstart.value.astimezone(tzinput).astimezone(self.get_tzlocal()) dtend = event.dtend.value.astimezone(tzinput).astimezone(self.get_tzlocal()) duration = str(dtend - dtstart)[:-3] now = self.get_tzlocal().localize(datetime.now()) #if dtstart >= now: print >>dst, remfmt % ( dtstart.strftime(datefmt), dtstart.strftime(timefmt), duration, text ) finally: src.close() except IOError as (errno, strerror): print "Error {0}: {1} input:{2} output:{3}.".format(errno, strerror, self.get_inputdir() + '/' + file, self.get_outputfile())
def getBase(self, response): base = LomBase.getBase(self, response) response.selector.remove_namespaces() record = response.xpath("//OAI-PMH/GetRecord/record") base.add_value( "fulltext", record.xpath( "metadata/lom/general/description/string//text()" ).extract_first(), ) thumbnail = record.xpath( 'metadata/lom/relation/kind/value[text()="hasthumbnail"]/parent::*/parent::*/resource/description/string//text()' ).get() if thumbnail: base.add_value("thumbnail", thumbnail) # publisher contributers = record.xpath("metadata/lom/lifeCycle/contribute") for contributer in contributers: role = contributer.xpath("role/value//text()").extract_first() if role == "publisher": vcardStr = contributer.xpath("entity//text()").extract_first() vcard = vobject.readOne(vcardStr) if hasattr(vcard, "fn"): base.add_value("publisher", vcard.fn.value) return base
def __init__(self, file_path: str): file_path = os.path.abspath(file_path) self.file_location = '/'.join(file_path.split('/')[:-1]) self.file_name = file_path.split('/')[-1] self.contact_categories = dict() for _, entry in self.contact_categories_lookup.items(): self.contact_categories[entry] = list() self.final_contacts_list = list() self.raw_contacts_list = list() self.raw_contacts_modified_atleast_once = False with open(f"{self.file_location}/{self.file_name}") as vcf_file: individual_contacts = [] append_to_current_entry = False current_entry = "" for line in vcf_file: if line.startswith("BEGIN:VCARD"): append_to_current_entry = True elif line.startswith("END:VCARD"): current_entry += line append_to_current_entry = False if append_to_current_entry: current_entry += line else: individual_contacts.append(current_entry) current_entry = "" for contact in individual_contacts: v_contact = vobject.readOne(contact) self.raw_contacts_list.append(v_contact)
def guessFormat(stream): """ Currently, if vobject can parse it, it's ICALENDAR_FORMAT, if not, and it has a From header, it's an email. """ start = stream.tell() try: # this is potentially expensive, but vobject is much more picky than # email's parser, so false positives seem much less likely trying # vobject first vobj = vobject.readOne(stream, ignoreUnreadable=True) if vobj.behavior == vobject.icalendar.VCalendar2_0: return ICALENDAR_FORMAT # one day we could test if it's a VCARD... except: pass stream.seek(start) try: msg = email.message_from_file(stream) if msg['From'] is not None: return EMAIL_FORMAT except: pass stream.seek(start) try: stream.readline() msg = email.message_from_file(stream) if msg['From'] is not None: return EMAILX_FORMAT except: pass return None
def render_PUT(self, request): result = WebdavResource.render_PUT(self, request) if result is not None and result.has_key(request.path) and \ request.env['CONTENT_TYPE'].strip().find('text/calendar') == 0: user=request.env.get('user') stream = self.storageProvider.get(request.path, user=user) try: event = vobject.readOne(stream) self.calendarProvider.store(request.path, event, user=user) # generate the etag data and add it to the document. stream.seek(0) md5Sum = getMD5(stream) md5Sum.update(request.path) etag = md5Sum.hexdigest() request.setHeader("ETag", "%s" % etag) self.storageProvider.setMeta(request.path, {'{DAV:}getetag': "%s" % etag, '{DAV:}getcontenttype': 'text/calendar' }, user=user ) except Exception as ex: logging.getLogger().warn('Not a calendar object. Got error: %s' % ex) finally: stream.close() return result
def get(self, href): """Fetch a single item.""" if self.is_fake: return try: href_mapper = HrefMapper.get(HrefMapper.href == href) uid = href_mapper.content.uid except HrefMapper.DoesNotExist: return None etesync_item = self.collection.get(uid) try: item = vobject.readOne(etesync_item.content) # XXX Hack to remove photo until we fix its handling if 'photo' in item.contents: del item.contents['photo'] except Exception as e: raise RuntimeError("Failed to parse item %r in %r" % (href, self.path)) from e # FIXME: Make this sensible last_modified = time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(time.time())) return EteSyncItem(self, item, href, last_modified=last_modified, etesync_item=etesync_item)
def put(cls, uri, data, content_type, cache=None): pool = Pool() Todo = pool.get('calendar.todo') Calendar = pool.get('calendar.calendar') calendar_id = cls.calendar(uri) if calendar_id: if not (uri[10:].split('/', 1) + [None])[1]: raise DAV_Forbidden todo_id = cls.todo(uri, calendar_id=calendar_id) ical = vobject.readOne(data) if not hasattr(ical, 'vtodo'): return super(Collection, cls).put(uri, data, content_type) if not todo_id: values = Todo.ical2values(None, ical, calendar_id) todo, = Todo.create([values]) calendar = Calendar(calendar_id) return Transaction().cursor.database_name + '/Calendars/' + \ calendar.name + '/' + todo.uuid + '.ics' else: values = Todo.ical2values(todo_id, ical, calendar_id) Todo.write([Todo(todo_id)], values) return return super(Collection, cls).put(uri, data, content_type)
def main(argv): auth = HTTPBasicAuth(argv[2], argv[3]) url = argv[1] # connect to asterisk ami = manager.Manager() ami.connect(HOST) ami.login(USER, PASS) # get phone numbers from vcard for vurl in getAllVcardLinks(url, auth): r = requests.request("GET", vurl, auth=auth) vcard = vobject.readOne(r.content) if "tel" in vcard.contents: for telno in vcard.contents['tel']: num = tidyPhoneNumber(telno.value) if "fn" in vcard.contents: name = vcard.fn.value print("Adding/updating Number: " + num + " Name: " + name) ami.send_action({ "Action": "DBPut", "Family": "cidname", "Key": num, "Val": name }) ami.logoff() ami.close()
def schedule2json(inp, timestamp): result = list() date = None rooms = None topics = dict() hash = hashlib.sha256(inp) for record in vobject.readOne(inp).components(): print 80 * "-" print "IN:", record if record.name != "VEVENT": continue speaker, location, room, tags = parseDescription(record.description.value[len(record.summary.value):]) output = dict() output["type"] = "talk" output["date"] = record.dtstart.value.strftime("%Y-%m-%d") output["start"] = record.dtstart.value.strftime("%H:%M") output["end"] = record.dtend.value.strftime("%H:%M") output["room"] = room output["speaker"] = speaker output["topic"] = record.summary.value output["description"] = "N/A" output["tags"] = tags output["location"] = location output["timestamp"] = convertDate(record.dtstart.value.strftime("%Y-%m-%d %H:%M:%S")) output["timestamp_end"] = convertDate(record.dtend.value.strftime("%Y-%m-%d %H:%M:%S")) output["language"] = "CZ" print print "OUT:", output result.append(output) # sort schedule by timestamp (primary key) and room name (secondary key) result.sort(key = lambda a: a["room"]) result.sort(key = lambda a: a["timestamp"]) return dict(items = result, timestamp = timestamp, checksum = hash.hexdigest())