The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.

NAME

E2::Interface - A client interface to the everything2.com collaborative database

SYNOPSIS

        use E2::Interface;
        use E2::Message;

        # Login

        my $e2 = new E2::Interface;
        $e2->login( "username", "password" );

        # Print client information

        print "Info about " . $e2->client_name . "/" . $e2->version . ":";
        print "\n  domain:     " . $e2->domain";
        print "\n  cookie:     " . $e2->cookie";
        print "\n  parse links:" . ($e2->parse_links ? "yes" : "no");
        print "\n  username:   " . $e2->this_username;
        print "\n  user_id:    " . $e2->this_userid;

        # Load a page from e2   

        my $page = $e2->process_request( 
                node_id => 124,
                display_type => "xmltrue"
        );

        # Now send a chatterbox message using the current
        # settings of $e2

        my $msg = new E2::Message;
        $msg->clone( $e2 );

        $msg->send( "This is a message" ); # See E2::Message

        # Logout

        $e2->logout;

DESCRIPTION

Introduction

This module is the base class for e2interface, a set of modules that interface with everything2.com. It maintains an agent that connects to E2 via HTTP and that holds a persistent state (a cookie) that can be cloned to allow multiple descendants of E2::Interface to act a single, consistent client. It also contains a few convenience methods.

e2interface

The modules that compose e2interface are listed below and indented to show their inheritance structure.

        E2::Interface - The base module

                E2::Node        - Loads regular (non-ticker) nodes

                        E2::E2Node      - Loads and manipulates e2nodes
                        E2::Writeup     - Loads and manipulates writeups
                        E2::User        - Loads user information
                        E2::Superdoc    - Loads superdocs
                        E2::Room        - Loads room information
                        E2::Usergroup   - Loads usergroup information

                E2::Ticker      - Modules for loading ticker nodes

                        E2::Message     - Loads, stores, and posts msgs
                        E2::Search      - Title-based searches
                        E2::Usersearch  - Search for writeups by user
                        E2::Session     - Session information
                        E2::ClientVersion - Client version information

See the manpages of each module for information on how to use that particular module.

Error handling

e2interface uses Perl's exception-handling system, Carp::croak and eval. An example:

        my $e2 = new E2::Interface;

        print "Enter username:";
        my $name = <>; chomp $name;
        print "Enter password:";
        my $pass = <>; chomp $pass;

        eval {
                if( $e2->login( $name, $pass ) ) {
                        print "$name successfully logged in.";
                } else {
                        print "Unable to login.";
                }
        };
        if( $@ ) {
                if $@ =~ /Unable to process request/ {
                        print "Network exception: $@\n";
                } else {
                        print "Unknown exception: $@\n";
                }
        }

In this case, login may generate an "Unable to process request" exception if it's unable to communicate with or receives a server error from everything2.com. This exception may be raised by any method in any package in e2interface that attempts to communicate with the everything2.com server.

Common exceptions include the following (those ending in ':' contain more specific data after that ':'):

        'Unable to process request' - HTTP communication error.
        'Invalid document'          - Invalid document received.
        'Parse error:'              - Exception raised while parsing
                                      document (the error output of
                                      XML::Twig::parse is placed after
                                      the ':'
        'Usage:'                    - Usage error (method called with
                                      improper parameters)

I'd suggest not trying to catch 'Usage:' exceptions: they can be raised by any method in e2interface and if they are triggered it is almost certainly due to a bug in the calling code.

All methods list which exceptions (besides 'Usage:') that they may potentially throw.

Threading

Network access is slow. Methods that rely upon network access may hold control of your program for a number of seconds, perhaps even minutes. In an interactive program, this sort of wait may be unacceptable.

e2interface supports a limited form of multithreading (in versions of perl that support ithreads--i.e. 5.8.0 and later) that allows network-dependant members to be called in the background and their return values to be retrieved later on. This is turned on by calling use_threads on an instance of any class derived from E2::Interface. After doing so, any method that relies on network access will return -1 and be executed in the background.

The id of the background job can then be retrieved by calling job_id, and the return value can be retrieved by passing the id to finish. If the method has not yet completed, finish returns -1. If the method has completed, finish returns a list consisting of the job_id followed by the return value of the method.

A code reference can be also be attached to a background method. See thread_then.

A simple example of threading in e2interface:

        use E2::Message;

        my $catbox = new E2::Message;

        $catbox->use_threads;   # Turn on threading

        my @r = $catbox->list_public; # This will run in the background
        my $id = $catbox->job_id;

        while( $r[0] eq "-1" ) { # While method deferred (use a string
                                 # comparison--if $r[0] happens to be
                                 # a string, you'll get a warning when
                                 # using a numeric comparison)

                # Do stuff here........

                @r = $catbox->finish( $id );
        }

        # Once we're here, @r contains: ( job_id, return value )

        shift @r;                       # Discard the job_id

        foreach( @r ) { 
                print $_->{text};       # Print out each chatterbox message
        }

Or, the same thing could be done using thread_then:

        use E2::Message;

        my $catbox = new E2::Message;

        $catbox->use_threads;

        # Execute $catbox->list_public in the background

        $catbox->thread_then( [ \&E2::Message::list_public ],

                # This subroutine will be called when list_public finishes,
                # and will be passed its return value in @_

                sub {
                        foreach( @_ ) {
                                print $_->{text};
                        }

                        # If we were to return something here, it could
                        # be retrieved in the call to finish() below.
                }
        );

        my $id = $catbox->job_id;

        # Do stuff here.....

        # Discard the return value of the deferred method (this will be
        # the point where the above anonymous subroutine actually
        # gets executed, during a call to finish())

        while( $node->finish ) {} # Finish will not return a false
                                  # value until all deferred methods
                                  # have completed 

CONSTRUCTOR

new

new creates an E2::Interface object. It defaults to using 'Guest User' until either login or cookie is used to log in a user.

METHODS

$e2->login USERNAME, PASSWORD

This method attempts to login to Everything2.com with the specified USERNAME and PASSWORD.

This method returns true on success and undef on failure.

Exceptions: 'Unable to process request', 'Invalid document'

$e2->verify_login

This method can be called after setting cookie; it (1) verifies that the everything2 server accepted the cookie as valid, and (2) determines the user_id of the logged-in user, which would otherwise be unavailable.

$e2->logout

logout attempts to log the user out of Everything2.com.

Returns true on success and undef on failure.

$e2->process_request ATTR1 => VAL1 [, ATTR2 => VAL2 [, ...]]

process_request assembles a URL based upon the specified ATTR and VAL pairs (example: process_request( node_id => 124 ) would translate to "http://everything2.com/?node_id=124" (well, technically, a POST is used rather than a GET, but you get the idea)). It requests that page via HTTP and returns the text of the response (stripped of HTTP headers and with smart quotes and other MS weirdness replaced by the plaintext equivalents). It returns undef on failure.

For those pages that may be retrieved with or without link parsing (conversion of "[link]" to a markup tag), this method uses this object's parse_links setting.

All necessary character escaping is handled by process_request.

Exceptions: 'Unable to process request'

$e2->clone OBJECT

clone copies various members from the E2::Interface-derived object OBJECT to this object so that both objects will use the same agent to process requests to Everything2.com. This is useful if, for example, one wants to use both an E2::Node and an E2::Message object to communicate with Everything2.com as the same user. This would work as follows:

        $msg = new E2::Message;
        $msg->login( $username, $password );

        $node = new E2::Node;
        $node->clone( $msg )

clone copies the cookie, domain, parse_links value, and agentstring, and it does so in such a way that if any of the clones (or the original) change any of these values, the changes will be propogated to all the others.

clone returns $self if successful, otherwise returns undef.

$e2->client_name

client_name return the name of this client, "e2interface-perl".

$e2->version

version returns the version number of this client.

$e2->this_username

this_username returns the username currently being used by this agent.

$e2->this_user_id

this_user_id returns the user_id of the current user. This is only available after login or verify_login has been called (in this instance or another cloned instance).

$e2->domain [ DOMAIN ]

If DOMAIN is specified, domain sets the domain used to fetch pages to DOMAIN. DOMAIN should contain neither an "http://" or a trailing "/".

domain returns the currently-used domain.

cookie returns the current everything2.com cookie (used to maintain login). If COOKIE is specified, cookie sets everything2.com's cookie to "COOKIE" and returns that value.

"COOKIE" is a string value of the "userpass" cookie at everything2.com. Example: an account with the username "willie" and password "S3KRet" would have a cookie of "willie%257CwirQfxAfmq8I6". This is generated by the everything2 servers.

This is how cookie would normally be used:

        # Store the cookie so we can save it to a file

        if( $e2->login( $user, $pass ) ) {
                $cookies{$user} = $e2->cookie;
        }

        ...

        print CONFIG_FILE "[cookies]\n";
        foreach( keys %cookies ) {
                print CONFIG_FILE "$_ = $cookies{$_}\n";
        }

Or:

        # Load the appropriate cookie

        while( $_ = <CONFIG_FILE> ) {
                chomp;
                if( /^$username = (.*)$/ ) {
                        $e2->cookie( $1 );
                        last;
                }
        }

If COOKIE is not valid, this function returns undef and the login cookie remains unchanged.

$e2->agentstring

agentstring returns and optionally sets the value prependend to e2interface's agentstring, which is then used in HTTP requests.

$e2->document

document returns the text of the last document retrieved by this instance in a call to process_request.

Note: if threading is turned on, this is updated by a call to finish, and will refer to the document from the most recent method finished.

$e2->logged_in

logged_in returns a boolean value, true if the user is logged in and undef if not.

Exceptions: 'Unable to process request', 'Parse error:'

$e2->use_threads [ NUMBER ]

use_threads creates a background thread (or NUMBER background threads) to be used to execute network-dependant methods. These are specific to their particular instance (i.e. they can't be cloned). This method can only be called once for any instance, and once threading has been enabled, it can't be disabled again.

use_threads returns true on success and undef on failure.

$e2->>job_id

job_id returns the job_id of the most recently deferred method.

$e2->finish [ JOB_ID ]

finish handles all post-processing of deferred methods (see thread_then for information on adding post-processing to a method), and attempts to return the return value of a deferred method. If JOB_ID is specified, it attempts to return the return value of that method, otherwise it attempts to return the return value of the first completed method on its queue.

It returns a list consisting of the job_id of the deferred method followed by the return value of the method in list context. If JOB_ID is specified and the corresponding method is not yet completed, this method returns -1. If JOB_ID is not specified, and there are methods left on the deferred queue but none of them are completed, it returns -1. It returns undef if the deferred queue is empty.

$e2->thread_then METHOD, CODE

thread_then executes METHOD (which is a reference to an array that consists of a method and its parameters, e.g.: [ \&E2::Node::load, $title, $type ]), and sets up CODE (a code reference) to be passed the return value of METHOD when METHOD completes.

thread_then is named as a sort of mnemonic device: "thread this method, then do this..."

thread_then returns -1 if METHOD is deferred; if METHOD is not deferred, thread_then immediately passes its return value to CODE and then returns the return value of CODE. This allows code to be written that can be run as either threaded or unthreaded; indeed this is how e2interface is implemented internally.

SEE ALSO

E2::Node, E2::E2Node, E2::Writeup, E2::User, E2::Superdoc E2::Usergroup E2::Room E2::Ticker, E2::Message, E2::Search, E2::UserSearch, E2::ClientVersion, E2::Session http://everything2.com, http://everything2.com/?node=clientdev

AUTHOR

Jose M. Weeks <jose@joseweeks.com> (Simpleton on E2)

COPYRIGHT

This software is public domain.