Difference between revisions of "LSL HTTP server/examples/kurais stupid web status updater"

From Second Life Wiki
Jump to navigation Jump to search
m (language tags to <source>)
 
(One intermediate revision by one other user not shown)
Line 9: Line 9:
== index.html ==
== index.html ==
A simple webform that sends the input to our cgi.
A simple webform that sends the input to our cgi.
<html4strict><html>
<source lang="html4strict"><html>
   <body>
   <body>
       <div align="center">
       <div align="center">
Line 20: Line 20:
       </div>
       </div>
   <body>
   <body>
</html></html4strict>
</html></source>
== post.cgi ==
== post.cgi ==
* That file needs to be readable and writable by your cgi.  Depending on your setup something like this might work:
* That file needs to be readable and writable by your cgi.  Depending on your setup something like this might work:
Line 26: Line 26:
: chmod 600 my_url
: chmod 600 my_url


<python>
<source lang="python">
#!/usr/bin/python
#!/usr/bin/python


##############################################
##############################################
# Orginal written by Kelly Linden           #
# Original written by Kelly Linden           #
# Modified by Kuraiko Yoshikawa (2009/07/28) #
# Modified by Kuraiko Yoshikawa (2009/07/28) #
##############################################
##############################################
Line 49: Line 49:


# If we haven't a Message or URL let the user know it and redirect to the form
# If we haven't a Message or URL let the user know it and redirect to the form
if not form.has_key("Message") and not form.has_key("URL"):
if "Message" not in form and "URL" not in form:
          
          
         print "Content-Type: text/html"
         print "Content-Type: text/html"
Line 59: Line 59:


# If we have URL param then this is an URL update
# If we have URL param then this is an URL update
elif form.has_key("URL"):  
elif "URL" in form:  
         # Intercept errors
         # Intercept errors
         try:
         try:
Line 93: Line 93:
         # Make the request, giving the status to the script.
         # Make the request, giving the status to the script.
         response = urllib2.urlopen(base_url + args)
         response = urllib2.urlopen(base_url + args)
</python>
</source>


== status.lsl ==
== status.lsl ==
<lsl>
<source lang="lsl2">


////////////////////////////////////////////////
////////////////////////////////////////////////
// Orginal written by Kelly Linden           //
// Original written by Kelly Linden           //
// Modified by Kuraiko Yoshikawa (2009/07/28) //
// Modified by Kuraiko Yoshikawa (2009/07/28) //
////////////////////////////////////////////////
////////////////////////////////////////////////
Line 213: Line 213:
}
}


</lsl>
</source>

Latest revision as of 16:39, 24 January 2015

What

Kills me not, this is my first try with python xD
  • Uses html forms, python and LSL.
  • Fixed the cgi error bug with empty messages
  • Add status reports for write to file error und success URL update

index.html

A simple webform that sends the input to our cgi.

<html>
   <body>
      <div align="center">
         <br><br><br>
         <form ACTION="cgi-bin/post.cgi" METHOD="GET">
            <textarea name="Message" rows="5" cols="40" onfocus="this.value=''; this.onfocus=null;">Enter your status update here.</textarea>
            <P>
            <INPUT TYPE="submit" title="FOO">
         </form>
      </div>
   <body>
</html>

post.cgi

  • That file needs to be readable and writable by your cgi. Depending on your setup something like this might work:
touch my_url
chmod 600 my_url
#!/usr/bin/python

##############################################
# Original written by Kelly Linden           #
# Modified by Kuraiko Yoshikawa (2009/07/28) #
##############################################

import cgi, urllib2, urllib
import cgitb
cgitb.enable()

 
# This file needs to be readable and writable from this cgi
file_name = "my_url"

form = cgi.FieldStorage()

# Set the URL of your form
url = "enter your form url"


# If we haven't a Message or URL let the user know it and redirect to the form
if "Message" not in form and "URL" not in form:
        
        print "Content-Type: text/html"
        print
        print "<html><head><meta http-equiv=\"refresh\" content=\"5; URL=%s\"></head>" %url
        print "<body style=\"text-align: center; margin-top: 20px;\">"
        print "Please fill in the message field.<br><a href=\"%s\">Redirection to the form in 5 seconds</a>" %url
        print "</body></html>"

# If we have URL param then this is an URL update
elif "URL" in form: 
        # Intercept errors
        try:
                # Write the url to the file, overwriting the existing file. 
                f = open(file_name,'w')
                f.write(form["URL"].value)
 
                # Let the caller know it worked.
                print "Content-Type: text/html"
                print
                print "OK"
        except:
                # it has an error.
                print "Content-Type: text/html"
                print
                print "ERROR|%s" %file_name
 
# We have Message then this is a status update.
else:
        # Redirect back to the form
        print "Status: 302 Moved"
        print "Location: %s" %url
        print
 
        # Read in the url from the file
        f = open(file_name,'r')
        base_url = f.read()
 
        # Build the complete url with query args.
        message = form["Message"].value
        args = "?Message=%s" % urllib.quote(message)
 
        # Make the request, giving the status to the script.
        response = urllib2.urlopen(base_url + args)

status.lsl

////////////////////////////////////////////////
// Original written by Kelly Linden           //
// Modified by Kuraiko Yoshikawa (2009/07/28) //
////////////////////////////////////////////////

// Set this to whatever text you want above your status
string header = "My Status:\n";
// This is the url to the post.cgi from above
string updater_url = "<url to your python script>";
 
// The magic changed flags to know when to re-request an url
// CHANGED_REGION | CHANGED_REGION_START | CHANGED_TELEPORT
integer CHANGED_URL = 1792;

key request;
// Setup run anytime we think our url has been lost.
setup()
{
    llSetObjectName("HTTP Server: Status Updates");
    llRequestURL();
}
 
// Debug incoming requests to see all header information.
debug(key id, string method, string body)
{
    llOwnerSay(method + ": " + body);
    list headers = ["x-script-url","x-path-info","x-query-string","x-remote-ip","user-agent"];
    integer i;
    for (i=0;i<5;++i)
    {
        llOwnerSay(llList2String(headers,i) + ": " + llGetHTTPHeader(id,llList2String(headers,i)));
    }
}
 
default
{
    // These events mean we have lost any urls we had and need to run setup()
    state_entry() 
    { 
        setup(); 
    }
    on_rez(integer n) 
    { 
        setup(); 
    }
    changed(integer c) 
    { 
        if (c & (CHANGED_URL) ) setup(); 
    }
 
    http_request(key id, string method, string body)
    {
         //debug(id, method, body);
 
        if (method == URL_REQUEST_GRANTED)
        {
            // Register our url for new status updates.
            request = llHTTPRequest(updater_url + "?URL=" + body + "/",[],"");
        }
        else if (method == URL_REQUEST_DENIED)
        {
            // Might be good to have this email.
            llSay(0,"Something went wrong, no url. " + body);
        }
        else if (method == "GET")
        {
            // Process a status update by parsing the query string
            string t = llGetHTTPHeader(id,"x-query-string");
            list l = llParseString2List(t,["?","=","&"],[]);
            
            // We want the value after Message
            integer i = llListFindList(l,["Message"]) + 1;
 
            // If there was no Message argument then i = (-1) + 1 => 0.
            // As long as i > 0 we found Message so put up whatever came next as the status.
            if (i > 0)
            {
                llSetText(header + llUnescapeURL(llList2String(l,i)),<1,1,0>,1);
                llHTTPResponse(id,200,"OK");
            }
            else
            {
                llHTTPResponse(id,400,"Must Specify a message!");
            }
        }
        else
        {
            llHTTPResponse(id,405,"Method unsupported");
        }
    }
    
    http_response(key request_id, integer status, list meta, string body)
    {
        if(request_id == request)
        {
            list t = llParseString2List(body, ["|"], [""]);
            string t0 = llStringTrim(llList2String(t, 0), STRING_TRIM);
            string t1 = llStringTrim(llList2String(t, 1), STRING_TRIM);
            if(t0 == "OK")
            {
                llSay(0, "URL successfully updated.");
            }
            else if (t0 == "ERROR")
            {
                llSay(0, "Can't write the URL to the file '" + t1 + 
                "'. Please check if the file exists and the script has write permissions.");
            }
            else
            {
                llSay(0, "Something went wrong.\n" + body);
            }
        }
    }
}