<s> import logging <EOL> from okcupyd . db import model , txn , with_txn <EOL> log = logging . getLogger ( __name__ ) <EOL> class UserAdapter ( object ) : <EOL> def __init__ ( self , profile ) : <EOL> self . profile = profile <EOL> def build ( self , session ) : <EOL> found = model . User . query_no_txn ( session , model . User . handle == <EOL> self . profile . username ) <EOL> if found : <EOL> return found [ <NUM_LIT:0> ] <EOL> else : <EOL> return model . User ( okc_id = self . profile . id , <EOL> handle = self . profile . username , <EOL> age = self . profile . age , <EOL> location = self . profile . location ) <EOL> def get_no_txn ( self , session ) : <EOL> return model . User . upsert_one_no_txn ( session , self . build ( session ) , <EOL> id_key = '<STR_LIT>' ) <EOL> get = with_txn ( get_no_txn ) <EOL> class ThreadAdapter ( object ) : <EOL> def __init__ ( self , thread ) : <EOL> self . thread = thread <EOL> def _get_thread ( self , session ) : <EOL> initiator = UserAdapter ( self . thread . initiator ) . get_no_txn ( session ) <EOL> respondent = UserAdapter ( self . thread . respondent ) . get_no_txn ( session ) <EOL> message_thread = model . MessageThread ( okc_id = self . thread . id , <EOL> initiator = initiator , <EOL> respondent = respondent ) <EOL> return model . MessageThread . upsert_one_no_txn ( session , message_thread , <EOL> id_key = '<STR_LIT>' ) <EOL> def _add_messages ( self , thread_model ) : <EOL> existing_message_ids = set ( [ m . okc_id for m in thread_model . messages ] ) <EOL> new_messages = [ message for message in self . thread . messages <EOL> if message . id not in existing_message_ids ] <EOL> new_message_models = [ ] <EOL> for new_message in new_messages : <EOL> from_initiator = thread_model . initiator . handle . lower ( ) == new_message . sender . username . lower ( ) <EOL> sender , recipient = ( thread_model . initiator , <EOL> thread_model . respondent ) if from_initiator else ( thread_model . respondent , <EOL> thread_model . initiator ) <EOL> new_message_model = model . Message ( okc_id = new_message . id , <EOL> text = new_message . content , <EOL> sender = sender , <EOL> recipient = recipient , <EOL> time_sent = new_message . time_sent ) <EOL> new_message_models . append ( new_message_model ) <EOL> thread_model . messages . append ( new_message_model ) <EOL> return new_message_models <EOL> def add_messages ( self ) : <EOL> with txn ( ) as session : <EOL> thread_model = model . MessageThread . find_no_txn ( session , <EOL> self . thread . id , <EOL> id_key = '<STR_LIT>' ) <EOL> return self . _add_messages ( thread_model ) <EOL> def get_thread ( self ) : <EOL> with txn ( ) as session : <EOL> thread_model = self . _get_thread ( session ) <EOL> return thread_model , self . _add_messages ( thread_model ) </s>
