Пример #1
0
def import_contacts():
    db = app.get_feature('document_storage').default_db
    sm = _get_state_machine()
    memory = 'ME'    # TODO: allow importing from SIM memory, too

    # NOTE: GetNextMemory is not implemented as of python-gammu 1.28.0, so we
    # cannot reuse the iteration code from _iterate_results.
    #
    # Also, we have to iterate the whole lot of slots despite there can be
    # actually a very few records at the very beginning of the list. The import
    # process may seem too long because of this.
    seen_cnt = saved_cnt = 0
    location = 0
    while True:
        location += 1
        try:
            item = sm.GetMemory(Type=memory, Location=location)
        except gammu.ERR_EMPTY:
            # empty records are not always at the end
            continue
        except gammu.ERR_INVALIDLOCATION:
            # aha, looks like there are no more slots
            break
        else:
            seen_cnt += 1
            elems = [(x['Type'], x['Value']) for x in item['Entries']]
            person, contacts = GammuContact.from_raw_elems(elems)

            def _contact_exists(contact):
                conditions = {'kind': contact.kind, 'value': contact.value}
                duplicates = GammuContact.objects(db).where(**conditions)
                return bool(duplicates.count())

            contacts = [c for c in contacts if not _contact_exists(c)]

            if not contacts:
                # even the Person instance is not saved if there's no new
                # contact information (the contacts could be moved btw)
                continue

            # this could be improved so that details don't matter, etc.
            person, created = db.get_or_create(type(person), **person)
            for contact in contacts:
                contact.person = person
                contact.save(db)

    print 'Imported {saved_cnt} of {seen_cnt}.'.format(**locals())
Пример #2
0
 def _contact_exists(contact):
     conditions = {'kind': contact.kind, 'value': contact.value}
     duplicates = GammuContact.objects(db).where(**conditions)
     return bool(duplicates.count())