/*
 *  Written by Niklas Ekström (niek8151@student.uu.se) in 2001
 *
 *  You're free to use this code in any way you wish;
 *  only note that I take absolutely no responsibility for
 *  anything you might do with it.
 *
 *  Use a tabwidth of 2 spaces!
 */

import java.net.*;
import java.io.*;
import java.util.*;

// ############################################################################
// ## Cookies
// ############################################################################

class Cookies {
	private Hashtable cookieTable;

	// ## Cookies
	public Cookies() {
		cookieTable = new Hashtable();
	}

	// ## set
	public void set( String cookie ) {
		int equalIndex = cookie.indexOf( "=" );
		if ( equalIndex == -1 )
			return;

		int colonIndex = cookie.indexOf( ";", equalIndex );
		if ( colonIndex == -1 )
			return;

		String key = cookie.substring( 0, equalIndex );
		String value = cookie.substring( equalIndex + 1, colonIndex );
		cookieTable.put( key, value );
	}

	// ## toString	
	public String toString() {
		StringBuffer sb = new StringBuffer();

		Enumeration keys = cookieTable.keys();
		Enumeration elements = cookieTable.elements();
		
		while ( keys.hasMoreElements() )
		{
			if ( sb.length() != 0 )
				sb.append( "; " );

			sb.append( (String)keys.nextElement() );
			sb.append( "=" );
			sb.append( (String)elements.nextElement() );
		}

		return sb.toString();
	}
}

// ############################################################################
// ## SMS
// ############################################################################

public class SMS
{
	private String username;
	private String password;

	private boolean loggedOn;
	private Cookies cookies;

	private String	host;

	private int			firstLength;
	private int			sysLength;

	// ## SMS
	public SMS( String v_username, String v_password )
	{
		username = URLEncoder.encode( v_username );
		password = URLEncoder.encode( v_password );
		
		HttpURLConnection.setFollowRedirects( false );
		
		loggedOn = false;
	}

	// ## addCookies
	private void addCookies( HttpURLConnection uc, Cookies cookies )
	{
		for ( int i = 0; ; i++ )
		{
			String key = uc.getHeaderFieldKey( i );
			String value = uc.getHeaderField( i );
			if ( value == null )
				break;

			if ( key != null && key.equalsIgnoreCase( "Set-Cookie" ) )
				cookies.set( value );
		}
	}

	// ## retrievePage
	private String retrievePage( URL url, Cookies cookies )
	{
		try {
			HttpURLConnection uc = (HttpURLConnection)url.openConnection();
			uc.setRequestMethod( "GET" );
			uc.setRequestProperty( "Cookie", cookies.toString() );
			uc.connect();

			addCookies( uc, cookies );

			int cl = uc.getContentLength();
			byte ba[] = new byte[ cl ];

			InputStream is = uc.getInputStream();
			for ( int read = 0; read != cl; )
				read += is.read( ba, read, cl - read );

			is.close();

			uc.disconnect();

			return new String( ba );
		} catch ( IOException e ) {
			return null;
		}
	}

	// ## login
	public boolean login()
	{
		if ( loggedOn )
			return false;

		cookies = new Cookies();

		try {
			URL url = new URL( "http://www.mtnsms.com/session.asp" );
			HttpURLConnection uc = (HttpURLConnection)url.openConnection();
			uc.setRequestMethod( "POST" );
			uc.setDoOutput( true );

			String loginCmd =	"username=" + username
											+ "&password=" + password
											+ "&email="
											+ "&joinusclick=no"
											+ "&returl="
											+ "&x=1&y=1";

			OutputStream os = uc.getOutputStream();
			os.write( loginCmd.getBytes() );
			os.flush();
			os.close();

			uc.connect();

			if ( uc.getResponseCode() != 302 )
				throw new Exception();

			host = uc.getHeaderField( "Location" );
			url = new URL( host );
			host = url.getHost();

			addCookies( uc, cookies );

			uc.disconnect();

			int begIndex, endIndex;
			String s;

			String sendPage = retrievePage( new URL( "http", host, "/sms/xsms.asp" ), cookies );

			begIndex = sendPage.lastIndexOf( "lenSSig" );
			begIndex = sendPage.indexOf( "value=\"", begIndex ) + 7;
			endIndex = sendPage.indexOf( "\"", begIndex );
			s = sendPage.substring( begIndex, endIndex );
			firstLength = Integer.parseInt( s );

			begIndex = sendPage.lastIndexOf( "lenSysSig" );
			begIndex = sendPage.indexOf( "value=\"", begIndex ) + 7;
			endIndex = sendPage.indexOf( "\"", begIndex );
			s = sendPage.substring( begIndex, endIndex );
			sysLength = Integer.parseInt( s );

			retrievePage( new URL( "http", host, "/members/tz.asp?to=2" ), cookies );

			loggedOn = true;
		} catch ( Exception e ) {}

		return loggedOn;
	}

	// ## logout
	public void logout()
	{
		if ( !loggedOn )
			return;
		
		try {
			retrievePage( new URL( "http", host, "/logout.asp" ), cookies );
		} catch ( Exception e ) {}

		cookies = null;
		loggedOn = false;
	}

	// ## send
	public boolean send( String from, String number,  String message )
	{
		if ( !loggedOn )
			return false;

		try {
			URL url = new URL( "http", host, "/sms/xsms.asp" );
			HttpURLConnection uc = (HttpURLConnection)url.openConnection();
			uc.setRequestMethod( "POST" );
			uc.setRequestProperty( "Cookie", cookies.toString() );
			uc.setDoOutput( true );

			String sms_msg =	"smsToNumbers=" + URLEncoder.encode( number )
											+ "&smsMessage=" + URLEncoder.encode( message )
											+ "&smsSig=1"
											+ "&smsSigDyna=" + URLEncoder.encode( from )
											+ "&lenSSig=" + firstLength
											+ "&lenLSig=" + (from.length() + 1)
											+ "&lenSysSig=" + sysLength;

			OutputStream os = uc.getOutputStream();
			os.write( sms_msg.getBytes() );
			os.flush();
			os.close();

			uc.connect();

			if ( uc.getResponseCode() != 200 )
				throw new Exception();

			addCookies( uc, cookies );

			uc.disconnect();
		} catch ( Exception e ) {
			return false;
		}
		return true;
	}
}

