<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def add(envelope):
 """ Take a dict-like fedmsg envelope and store the headers and message in the table. """

    message = envelope['body']
    timestamp = message.get('timestamp', None)
    try:
        if timestamp:
            timestamp = datetime.datetime.utcfromtimestamp(timestamp)
        else:
            timestamp = datetime.datetime.utcnow()
    except Exception:
        pass

    headers = envelope.get('headers', None)
    msg_id = message.get('msg_id', None)
    if not msg_id and headers:
        msg_id = headers.get('message-id', None)
    if not msg_id:
        msg_id = six.text_type(timestamp.year) + six.u('-') + six.text_type(uuid.uuid4())
    obj = Message(
        i=message.get('i', 0),
        msg_id=msg_id,
        topic=message['topic'],
        timestamp=timestamp,
        username=message.get('username', None),
        crypto=message.get('crypto', None),
        certificate=message.get('certificate', None),
        signature=message.get('signature', None),
    )

    obj.msg = message['msg']
    obj.headers = headers

    try:
        session.add(obj)
        session.flush()
    except IntegrityError:
        log.warning('Skipping message from %s with duplicate id: %s',
                    message['topic'], msg_id)
        session.rollback()
        return

    usernames = fedmsg.meta.msg2usernames(message)
    packages = fedmsg.meta.msg2packages(message)

    # Do a little sanity checking on fedmsg.meta results
    if None in usernames:
        # Notify developers so they can fix msg2usernames
        log.error('NoneType found in usernames of %r' % msg_id)
        # And prune out the bad value
        usernames = [name for name in usernames if name is not None]

    if None in packages:
        # Notify developers so they can fix msg2packages
        log.error('NoneType found in packages of %r' % msg_id)
        # And prune out the bad value
        packages = [pkg for pkg in packages if pkg is not None]

    # If we've never seen one of these users before, then:
    # 1) make sure they exist in the db (create them if necessary)
    # 2) mark an in memory cache so we can remember that they exist without
    #    having to hit the db.
    for username in usernames:
        if username not in _users_seen:
            # Create the user in the DB if necessary
            User.get_or_create(username)
            # Then just mark an in memory cache noting that we've seen them.
            _users_seen.add(username)

    for package in packages:
        if package not in _packages_seen:
            Package.get_or_create(package)
            _packages_seen.add(package)

    session.flush()

    # These two blocks would normally be a simple "obj.users.append(user)" kind
    # of statement, but here we drop down out of sqlalchemy's ORM and into the
    # sql abstraction in order to gain a little performance boost.
    values = [{'username': username, 'msg': obj.id} for username in usernames]
    if values:
        session.execute(user_assoc_table.insert(), values)

    values = [{'package': package, 'msg': obj.id} for package in packages]
    if values:
        session.execute(pack_assoc_table.insert(), values)

    # TODO -- can we avoid committing every time?
    session.flush()
    session.commit()