User:Takat Su/Name2Key

From Second Life Wiki
< User:Takat Su
Revision as of 17:30, 24 January 2015 by ObviousAltIsObvious Resident (talk | contribs) (language tags to <source>)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Name2Key

This is an update to Maeva Anatine's excellent suggestion for an updated name2key function. Rather than overwrite all her work, I created this page. The idea is DEFINITELY hers - I just am creating an alternate implementation.

Still missing Name2Key functions in your code? Still relying on external databases that are not always up to date with latests SL subscribers?

Well now you can solve this by yourself, within your LSL script! All you have to do is to rely on LL Search engine!

I put a kind of "library" and a sample of usage for your convenience

To use, you make an llHttpRequest to the application running on the Google Application Server (a free service for moderate users). The URL looks like this: http://name2key.appspot.com/?name=firstname%20lastname i.e. the first name of the person you want to look up is separated from their last name by "%20" (this is how the space character is coded in URLs). The application doesn't care if you get the case correct. The application will format the body of the return as follows: firstname lastname:key, where firstname and lastname will be capitalized correctly and the key is either the key for the person or the null key (00000000-0000-0000-0000-000000000000) if the name doesn't exist. It really isn't much code if you prefer to code it into your main script rather than rely on an external script for the lookup.

DONE: Alter the python code so that it fails gracefully if the name given in the URL does not exist or if Linden Search is down.

Library

integer cmdName2Key = 19790;
integer cmdName2KeyResponse = 19791;

list gRequests;

key requestName2Key( string inName ) {
    list lNameParts = llParseString2List( inName, [" "], [] );
    string lFirstName = llList2String( lNameParts, 0 );
    string lLastName = llList2String( lNameParts, 1 );
    return llHTTPRequest( "http://name2key.appspot.com/?name=" + lFirstName + "%20" + lLastName, [], "" );
}

default {
    link_message( integer inFromPrim, integer inCommand, string inName, key inKey ) {
        if( inCommand == cmdName2Key )
            gRequests += [requestName2Key( inName ), inKey ];
    }
    
    http_response(key inKey, integer inStatus, list inMetaData, string inBody ) {
        integer lPosition = llListFindList( gRequests, [inKey]);
        if( lPosition != -1 ) {
            llMessageLinked( LINK_SET, cmdName2KeyResponse, inBody, llList2Key( gRequests, lPosition+1 ) );
            gRequests = llDeleteSubList( gRequests, lPosition, lPosition + 1 );
        }
    }
}

Usage sample

integer cmdName2Key = 19790;
integer cmdName2KeyResponse = 19791;

default {
    state_entry() {
        llMessageLinked( LINK_SET, cmdName2Key, "Test Name", NULL_KEY );
    }
    
    link_message( integer inFromPrim, integer inCommand, string inKeyData, key inReturnedKey ) {
        if( inCommand == cmdName2KeyResponse ) {
            list lParts = llParseString2List( inKeyData, [":"], [] );
            string lName = llList2String( lParts, 0 );
            key lKey = (key)llList2String(lParts, 1 );
        }
    }
}

Google App Python Code

#
#
# Updated by Kisamin Resident for the latest google app engine
#
#

import webapp2

import urllib
 
kURL = "http://vwrsearch.secondlife.com/client_search.php?session=00000000-0000-0000-0000-000000000000&q="
kProfile = "Resident profile"
kResult = "secondlife:///app/agent/"

class MainHandler( webapp2.RequestHandler ):
    def get(self):
        l_Name = self.request.get("name").upper()
        if not isinstance( l_Name, str):
            l_Name = l_Name.decode("utf-8")
        l_name = l_Name.replace (" ", "%20")
        l_foundName = l_Name
        l_key = '00000000-0000-0000-0000-000000000000'
        try:
            l_data = urllib.urlopen(kURL + l_name).read()
            l_start = l_data.index (kProfile)
            l_foundName = l_data[l_start+18:l_start+18+len(l_Name)]
            l_key = '00000000-0000-0000-0000-000000000000'
            if l_foundName.upper () == l_Name:
                l_start = l_data.index (kResult)
                l_key = l_data[l_start+len(kResult):l_start+len(kResult)+36]
            else:
                l_foundName = l_Name
        except:
            l_fFoundName = l_Name
        finally:
            self.response.out.write ("%s:%s" % (l_foundName, l_key))

app = webapp2.WSGIApplication([
    ('/', MainHandler)
], debug=True)

app.yaml file

application: avatarkeyfromname
version: 1
runtime: python27
api_version: 1
threadsafe: yes

handlers:
- url: .*
  script: main.app

libraries:
- name: webapp2
  version: "2.5.2"

Name2Key PHP Code

In case you wanted to use PHP instead

<?php
function findit ($in_RawName) {
	$kURL = 'http://vwrsearch.secondlife.com/client_search.php?session=00000000-0000-0000-0000-000000000000&q=';
	$kProfile = 'Resident profile';
	$kResult = 'secondlife:///app/agent/';

	$l_RawName = strtoupper($in_RawName);
	$l_URLName = str_replace (' ', '%20', $l_RawName);
	$l_FoundName = $l_RawName;
	$l_Key = '00000000-0000-0000-0000-000000000000';

	$l_HTML = file_get_contents ($kURL . $l_URLName);
	$l_Start = strpos ($l_HTML, $kProfile);
	$l_FoundName = substr($l_HTML, $l_Start+18, strlen($l_RawName));

	if (strtoupper($l_FoundName) == $l_RawName) {
		$l_Start = strpos($l_HTML, $kResult);
		$l_Key = substr ($l_HTML, $l_Start + strlen($kResult), 36);
	} else
		$l_FoundName = $l_RawName;
	return $l_FoundName . ":" . $l_Key;
}

parse_str ($_SERVER['QUERY_STRING']);
print findit ($name);
?>

Name2Key ASPX/VB.net Code

In case you wanted to use ASPX/VB.net instead. 25 March 2014 by Ohjiro Watanabe

Imports System.IO
Imports System.Net

Partial Class nameToKey
    Inherits System.Web.UI.Page


    Dim name As String



    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        name = Request("name")
        Response.Write(getKey(name))

    End Sub


Private Function getKey(name As String) As String

        Dim nullKey As String = "00000000-0000-0000-0000-000000000000"
        Dim strURL As String = "http://vwrsearch.secondlife.com/client_search.php?session=" & nullKey & "&q=" & name.Replace(" ", "%20")
        Dim strResult As String
        Dim keyLength As Integer = 36
        Dim objResponse As WebResponse
        Dim objRequest As WebRequest = HttpWebRequest.Create(strURL)

        objResponse = objRequest.GetResponse()

        'Get the web page (the result of the search)
        Using sr As New StreamReader(objResponse.GetResponseStream())
            strResult = sr.ReadToEnd()
            sr.Close()
        End Using

        'Check the lookup name has been found
        Dim namePositionfinder As String = "Resident profile: "
        Dim start As Integer = strResult.IndexOf(namePositionfinder) + namePositionfinder.Length
        Dim foundName As String = strResult.Substring(start, name.Trim().Length)

        ' if it is found get the key otherwise return nullKey
        If foundName.ToUpper() = name.ToUpper() Then
            Dim placeFinder As String = "secondlife:///app/agent/"
            start = strResult.IndexOf(placeFinder) + placeFinder.Length
            Return strResult.Substring(start, keyLength)
        Else
            Return nullKey
        End If

    End Function


End Class

Name2Key ASPX/CSharp Code

In case you wanted to use ASPX/CSharp instead. 25 March 2014 by Ohjiro Watanabe

using System.IO;
using System.Net;

public partial class nameToKey : System.Web.UI.Page
{


    string name;


    protected void Page_Load(object sender, System.EventArgs e)
    {
        name = Request["name"];
        Response.Write(getKey(name));

    }


    private string getKey(string name)
    {

        string nullKey = "00000000-0000-0000-0000-000000000000";
        string strURL = "http://vwrsearch.secondlife.com/client_search.php?session=" + nullKey + "&q=" + name.Replace(" ", "%20");
        string strResult = null;
        int keyLength = 36;
        WebResponse objResponse = null;
        WebRequest objRequest = HttpWebRequest.Create(strURL);

        objResponse = objRequest.GetResponse();

        //Get the web page (the result of the search)
        using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
        {
            strResult = sr.ReadToEnd();
            sr.Close();
        }

        //Check the lookup name has been found
        string namePositionfinder = "Resident profile: ";
        int start = strResult.IndexOf(namePositionfinder) + namePositionfinder.Length;
        string foundName = strResult.Substring(start, name.Trim().Length);

        // if it is found get the key otherwise return nullKey
        if (foundName.ToUpper() == name.ToUpper())
        {
            string placeFinder = "secondlife:///app/agent/";
            start = strResult.IndexOf(placeFinder) + placeFinder.Length;
            return strResult.Substring(start, keyLength);
        }
        else
        {
            return nullKey;
        }

    }
    public nameToKey()
    {
        Load += Page_Load;
    }



}

Comments

Updated 13-Jun-2013 for latest Google App-Engine. It also now properly handles non-existent account names, returning an all-upper-case name and a null-key. Also added PHP version for people who don't want to host on the Google App Engine

Kisamin Resident

The main difference is that I wrote an app for the google app engine that act as a relay. Since I was going that far, it also parses the return, strips out all the extraneous stuff and just returns you the name and key separated by a colon.

Takat Su