def _choose_existing_thread_for_gmail(message, db_session):
 prior_threads = db_session.query(ImapThread).filter_by(g_thrid=message.g_thrid, namespace_id=message.namespace_id).order_by(desc(ImapThread.recentdate)).all()
 if (not prior_threads):
  return None
 if (len(prior_threads) == 1):
  return prior_threads[0]
 if (not message.in_reply_to):
  return prior_threads[0]
 for prior_thread in prior_threads:
  prior_message_ids = [m.message_id_header for m in prior_thread.messages]
  if (message.in_reply_to in prior_message_ids):
   return prior_thread
 return prior_threads[0]

def _choose_existing_thread_for_gmail ( message , db_session ) : prior_threads = db_session . query ( ImapThread ) . filter_by ( g_thrid = message . g_thrid , namespace_id = message . namespace_id ) . order_by ( desc ( ImapThread . recentdate ) ) . all ( ) if ( not prior_threads ) : return None if ( len ( prior_threads ) == 1 ) : return prior_threads [ 0 ] if ( not message . in_reply_to ) : return prior_threads [ 0 ] for prior_thread in prior_threads : prior_message_ids = [ m . message_id_header for m in prior_thread . messages ] if ( message . in_reply_to in prior_message_ids ) : return prior_thread return prior_threads [ 0 ]
for gmail .