def session_device_check(config, session_id, device_code):
    if not ltoUtil.valid_chars(session_id):
        print 'Invalid characters used in session id.'
        print ltoUtil.get_script_name()+' script terminated.'
        sys.exit(2)
    if not ltoUtil.valid_chars(device_code):
        print 'Invalid characters used in device_code.'
        print ltoUtil.get_script_name()+' script terminated.'
        sys.exit(2)
    media_exists_for_session_device_qry = 'exists(/session[@id="'+session_id+'"]//device[@code="'+device_code+'"]/*)'
    if not db_session_id_exists(config, session_id):
        print 'session id: '+session_id+' does not yet exist.'
        print ltoUtil.get_script_name()+' script terminated.'
        sys.exit(2)
    if not db_device_code_exists(config, device_code):
        print 'device code: '+device_code+' does not exist.'
        print ltoUtil.get_script_name()+' script terminated.'
        sys.exit(2)
    xquery_result = ltoUtil.exec_url_xquery(config, ltoUtil.get_transcript_url(config)+'/data', media_exists_for_session_device_qry)   
    if ltoUtil.get_parsed_xquery_value(xquery_result) == ['true']:
        print 'At least one media item has already been associated with session: '+session_id+' and device: '+device_code
        print
        print 'To see the associated media items for this session open the following link in your browser:'
        print 'http://'+ltoUtil.get_host_port(config)+ltoUtil.get_transcript_url(config)+'/data?_query=/session[@id="'+session_id+'"]//mediaMetadata'
        print
        cont = raw_input('Are you sure you want to continue? [y/n]: ')
        if cont == 'y':
            return 
        else:
            print ltoUtil.get_script_name()+' script terminated.'
            sys.exit(2)
def db_device_code_exists(config, device_code):
    device_exists_qry = 'exists(//deviceCode[@id="'+device_code+'"])'
    xquery_result = ltoUtil.exec_url_xquery(config, ltoUtil.get_transcript_url(config)+'/reference', device_exists_qry)
    if ltoUtil.get_parsed_xquery_value(xquery_result) == ['true']:
        return True
    else:
        return False
def db_session_id_exists(config, session_id):
    session_exists_qry = 'exists(/session[@id="'+session_id+'"])'
    xquery_result = ltoUtil.exec_url_xquery(config, ltoUtil.get_transcript_url(config)+'/data', session_exists_qry)
    if ltoUtil.get_parsed_xquery_value(xquery_result) == ['true']:
        return True
    else:
        return False
def db_add_media_xml(config, db_media_xml_doc, username, password):  
    deviceElement = db_media_xml_doc.getElementsByTagName('device')[0]
    session_id = deviceElement.getAttribute('sessionId')
    device_code = deviceElement.getAttribute('code')
    base64string = base64.encodestring('%s:%s' % (username, password))[:-1]
    authheader =  "Basic %s" % base64string
    headers = {'Authorization': authheader}
    conn = httplib.HTTPConnection(ltoUtil.get_host_port(config))
   
    if len(deviceElement.childNodes) == 0:
        print 'Internal Error: No session-media xml nodes generated.'
        print ltoUtil.get_script_name()+' script terminated.'
        sys.exit(2)
    
    for mediaElem in deviceElement.childNodes:
        if mediaElem.nodeType == xml.dom.Node.ELEMENT_NODE:
            element_xml = str(mediaElem.toxml())
            #Hack to put id as the first attribute
            element_xml = string.replace(element_xml, '_id="', 'id="')
            params = urllib.urlencode({'sessionId': session_id, 'deviceCode': device_code, 'mediaXML': element_xml})
            try:
                conn.request('GET', ltoUtil.get_transcript_url(config)+'/xquery/import-media-element.xql?'+params, None, headers)
                response = conn.getresponse()
                data = response.read()
                if '<exception>' in data:
                    print ltoUtil.get_xquery_exception_msg(data)
                    print ltoUtil.get_script_name()+' script terminated.'
                    return False
                elif response.status == 401 and response.reason == 'Unauthorized':
                    print 'Authentication Failed.'
                    return False
            except Exception, e:
                print 'Unable to connect to database'
                return False
def db_media_id_exists(domain, id, config):
    media_id_exists_for_domain_qry = 'exists(/session//mediaMetadata//'+domain+'[@id="'+id+'"])'
    xquery_result = ltoUtil.exec_url_xquery(config, ltoUtil.get_transcript_url(config)+'/data', media_id_exists_for_domain_qry)
    if ltoUtil.get_parsed_xquery_value(xquery_result) == ['true']:
        return True
    else:
        return False
def create_referenced_items_file(config, session_id, device_code):
    tarMeta = open(os.path.join(ltoUtil.get_tar_build_dir(config), session_id+'-'+device_code+'-referenced-items.xml'),'w')
    params = urllib.urlencode({'sessionIds':session_id, 'deviceCodes':device_code})
    conn = httplib.HTTPConnection(ltoUtil.get_host_port(config))
    try:
        conn.request('GET', ltoUtil.get_transcript_url(config)+'/xquery/get-referenced-items.xql?'+params, None, {})
        response = conn.getresponse()
        tarMeta.writelines(response.read())
    except httplib.HTTPException, e:
        print 'Unable to connect to database'
def get_media_ids(config, session_ids, domain):
    list = []
    for s in session_ids:
        if ltoTarUtil.db_session_id_exists(config, s):
            media_ids_qry = '/session[@id="'+s+'"]//'+domain+'/xs:string(@id)'
            xquery_result = ltoUtil.exec_url_xquery(config, ltoUtil.get_transcript_url(config)+'/data', media_ids_qry)
            list.extend(ltoUtil.get_parsed_xquery_value(xquery_result))
        else:
            print s+' is not a recognised session id.'
            print ltoUtil.get_script_name()+' script terminated.'
            sys.exit(2)     
    return list
def get_session_full_name(config, sessionId):
    params = urllib.urlencode({'sessionId':sessionId})
    conn = httplib.HTTPConnection(ltoUtil.get_host_port(config))
    try:
        conn.request('GET', ltoUtil.get_transcript_url(config)+'/xquery/get-session-full-name.xql?'+params, None, {})
        response = conn.getresponse()
        data = response.read()
        if '<exception>' in data:
            print ltoUtil.get_xquery_exception_msg(data)
            print ltoUtil.get_script_name()+' script terminated.'
            sys.exit(2)
    except httplib.HTTPException, e:
        print 'Unable to connect to database'
def db_get_next_media_id(session_id, domain, config):
    event_type = session_id[:session_id.find('-')]
    params = urllib.urlencode({'domain': domain, 'eventType': event_type})
    conn = httplib.HTTPConnection(ltoUtil.get_host_port(config))
    try:
        conn.request('GET', ltoUtil.get_transcript_url(config)+'/xquery/get-next-media-id.xql?'+params, None, {})
        response = conn.getresponse()
        data = response.read()
        if '<exception>' in data:
            print ltoUtil.get_xquery_exception_msg(data)
            print ltoUtil.get_script_name()+' script terminated.'
            sys.exit(2)
        else:
            return data
    except httplib.HTTPException, e:
        print 'Unable to connect to database'