Thursday, November 5, 2009

Google Account API

This post isn't directly related to PowerShell, but I figured it is better to put it here than nowhere at all. I was looking at my Send-Email and Send-SMS cmdlets the other day, and I figured that the ability to send email or SMS through Gmail and Google Voice might be useful in environments other than PowerShell.

I created a C# class library that provides an API for sending an email through Gmail or an SMS through Google Voice. I added to it a very simple class for dealing with Google Contacts. Google's Contacts API is much more powerful, but I didn't want to add a dependency to my project. This is also partly inspired by my genius little brother, who has developed some similar APIs for Python.

All of the classes in this library use a custom HttpRequester class to make their requests to Google's services. This class keeps track of cookies between requests, handles redirection, and also provides a method for determining the MIME type of a file.

The Gmail class provides a simple way to create an email message and sent it, with full attachment support. Here is the updated code from my Send-Email cmdlet, which, as you can see, is much simpler than the old code:

private void SendGmailMessage()

{

    IntPtr bstr = Marshal.SecureStringToBSTR( googlePassword );

    string plainGooglePassword = Marshal.PtrToStringAuto( bstr );

    Marshal.ZeroFreeBSTR( bstr );

 

    GoogleAccount.Gmail gmailMessage = new GoogleAccount.Gmail( googleUsername, plainGooglePassword );

 

    gmailMessage.OnStatus += new GoogleAccount.Gmail.StatusEventHandler( HandleGmailStatus );

    gmailMessage.OnError += new GoogleAccount.Gmail.ErrorEventHandler( HandleGmailError );

 

    foreach ( string recipient in toArray )

    {

        gmailMessage.To.Add( recipient );

    }

 

    foreach ( string recipient in ccArray )

    {

        gmailMessage.Cc.Add( recipient );

    }

 

    foreach ( string recipient in bccArray )

    {

        gmailMessage.Bcc.Add( recipient );

    }

 

    if ( !string.IsNullOrEmpty( subject ) )

    {

        gmailMessage.Subject = subject;

    }

 

    if ( !string.IsNullOrEmpty( body ) )

    {

        gmailMessage.Body = body;

    }

 

    gmailMessage.BodyIsHtml = bodyIsHtml.IsPresent;

    gmailMessage.Timeout = timeout;

 

    foreach ( FileInfo attachment in inputAttachments )

    {

        gmailMessage.Attachments.Add( attachment );

    }

 

    if ( ShouldProcess( gmailMessage.Subject ) )

    {

        gmailMessage.Send();

    }

}


You might notice the OnStatus and OnError event handlers being set up at the beginning of the function. These are used to report errors and status messages during the several requests necessary to send an email. These handlers are used by the Send-Email cmdlet to provide proper support for the -Verbose parameter.

The SMS class is used in a very similar way. This is how I use it in my Send-SMS cmdlet:

protected override void EndProcessing()

{

    IntPtr bstr = Marshal.SecureStringToBSTR( googlePassword );

    string plainGooglePassword = Marshal.PtrToStringAuto( bstr );

    Marshal.ZeroFreeBSTR( bstr );

 

    GoogleAccount.SMS sms = new GoogleAccount.SMS( googleUsername, plainGooglePassword );

 

    sms.OnStatus += new GoogleAccount.SMS.StatusEventHandler( HandleGoogleVoiceStatus );

    sms.OnError += new GoogleAccount.SMS.ErrorEventHandler( HandleGoogleVoiceError );

 

    sms.Number = this.number;

    sms.Text = this.text;

 

    if ( ShouldProcess( sms.Text ) )

    {

        sms.Send();

    }

}


The Contacts class provides read-only access to each of your Google contacts through a Contact class that has fields for first name, last name, email address, mobile phone, and groups. I create this list by downloading a CSV file and parsing it. Yes, I know I shouldn't parse the CSV data myself, but .NET doesn't have a built-in CSV parser, and I didn't want to add a dependency to a 3rd-party library. It seems to work just fine for its simple purpose.

I wrote a small application to test the Contacts and SMS classes. It is called Mass SMS, and it allows you to choose several contacts to send one SMS message to, a service not provided on the Google Voice site. Here's how it works. First, you log in using your Google username and password:

A pretty self-explanatory dialog for choosing contacts is then displayed. This dialog allows you to filter your contacts by group, such as Family:
Once you have selected the contacts you want to receive your SMS, a dialog is displayed that allows you to specify the message:
The final dialog displays the status of each message as it is being sent:
Pretty simple, but it gets the job done. It was a fun little project to put together, and maybe I will actually use it someday! If you think you might be able to use it, please feel free.


Friday, July 17, 2009

PowerShell and Google Voice

After a long wait, I finally got my invitation to Google Voice this week. I haven't completely converted to it, but it looks very useful. My brother got his Google Voice number about a week earlier, and he posted a Python script on his blog that sends an SMS using his account.

I decided to create a PowerShell Cmdlet that does the same thing. It is mostly just a translation of my brother's script, but it includes code from my Send-Email Cmdlet that uses a Gmail account.

Here is the code:

using System;

using System.Text;

using System.Management.Automation;

using System.Net;

using System.IO;

using System.Web;

using System.Text.RegularExpressions;

using System.Runtime.InteropServices;

using System.Security;

 

namespace CustomCmdlets

{

    [Cmdlet( VerbsCommunications.Send, "SMS", SupportsShouldProcess = true )]

    public class SendSMS : PSCmdlet

    {

        private const string GOOGLE_VOICE_ADDRESS = "https://www.google.com/voice/";

        private const string GOOGLE_VOICE_AUTHENTICATION_ADDRESS = "https://www.google.com/accounts/ServiceLoginAuth";

        private const string GOOGLE_VOICE_SMS_ADDRESS = "https://www.google.com/voice/sms/send/";

        private CookieCollection cookieCollection;

 

        #region Parameters

 

        private string googleUsername;

 

        [ValidateNotNullOrEmpty]

        public string GoogleUsername

        {

            get

            {

                return googleUsername;

            }

            set

            {

                googleUsername = value;

            }

        }

 

        private SecureString googlePassword;

 

        [ValidateNotNullOrEmpty]

        public SecureString GooglePassword

        {

            get

            {

                return googlePassword;

            }

            set

            {

                googlePassword = value;

            }

        }

 

        private string number;

 

        [Parameter( Position = 0, Mandatory = true )]

        [ValidateNotNullOrEmpty]

        public string Number

        {

            get

            {

                return number;

            }

            set

            {

                number = value;

            }

        }

 

        private string text;

 

        [Parameter( Position = 1, Mandatory = true )]

        public string Text

        {

            get

            {

                return text;

            }

            set

            {

                text = value;

            }

        }

 

        #endregion

 

        protected override void BeginProcessing()

        {

            if ( googleUsername == null )

            {

                googleUsername = (string)GetVariableValue( "GoogleUsername", null );

            }

 

            if ( googlePassword == null )

            {

                googlePassword = (SecureString)GetVariableValue( "GooglePassword", null );

            }

 

            if ( string.IsNullOrEmpty( googleUsername ) || googlePassword == null )

            {

                this.WriteError( new ErrorRecord(

                    new Exception( "You must provide a username and password." ),

                    "Send-SMS", ErrorCategory.PermissionDenied, this ) );

            }

        }

 

        protected override void EndProcessing()

        {

            IntPtr bstr = Marshal.SecureStringToBSTR( googlePassword );

            string plainGmailPassword = Marshal.PtrToStringAuto( bstr );

            Marshal.ZeroFreeBSTR( bstr );

 

            string postDataString = "&continue=" + HttpUtility.UrlEncode( GOOGLE_VOICE_ADDRESS ) +

                                    "&Email=" + HttpUtility.UrlEncode( googleUsername ) +

                                    "&Passwd=" + HttpUtility.UrlEncode( plainGmailPassword );

 

            this.cookieCollection = new CookieCollection();

 

            this.WriteVerbose( "Sending Google Voice login request..." );

 

            MakeHttpWebRequest( GOOGLE_VOICE_AUTHENTICATION_ADDRESS, true, Encoding.UTF8.GetBytes( postDataString ) );

 

            // if we don't have this cookie, something went wrong

            if ( this.cookieCollection[ "GAUSR" ] == null )

            {

                this.WriteError( new ErrorRecord(

                    new Exception( "Could not log in to Gmail.  Please check your username and password." ),

                    "Send-SMS", ErrorCategory.PermissionDenied, this ) );

            }

            else

            {

                this.WriteVerbose( "Sending Google Voice home page request..." );

 

                string googleVoiceHomePage = MakeHttpWebRequest( GOOGLE_VOICE_ADDRESS, false, null );

 

                Match rnrSeMatch = Regex.Match( googleVoiceHomePage, @"name=""_rnr_se"".*?value=""(?<Value>[^""]+)""" );

 

                if ( rnrSeMatch.Success )

                {

                    postDataString = "&_rnr_se=" + HttpUtility.UrlEncode( rnrSeMatch.Groups[ "Value" ].Value ) +

                                    "&phoneNumber=" + HttpUtility.UrlEncode( number ) +

                                    "&text=" + HttpUtility.UrlEncode( text );

 

                    this.WriteVerbose( "Sending Google Voice SMS request..." );

 

                    string sendResult = MakeHttpWebRequest( GOOGLE_VOICE_SMS_ADDRESS, true, Encoding.UTF8.GetBytes( postDataString ) );

 

                    Match resultMatch = Regex.Match( sendResult, @"\{""ok"":(?<Success>[^,]+),""data"":\{""code"":(?<Code>\d+)\}\}" );

 

                    if ( resultMatch.Success )

                    {

                        if ( bool.Parse( resultMatch.Groups[ "Success" ].Value ) )

                        {

                            this.WriteObject( "Your SMS has been sent." );

                        }

                        else

                        {

                            this.WriteError( new ErrorRecord(

                                new Exception( "Your SMS was not sent." ),

                                "Send-SMS", ErrorCategory.NotSpecified, this ) );

                        }

                    }

                }

            }

        }

 

        private string MakeHttpWebRequest( string requestUrl, bool post, byte[] postData )

        {

            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create( new Uri( requestUrl ) );

 

            // we need to do this ourselves

            webRequest.AllowAutoRedirect = false;

            webRequest.KeepAlive = false;

            webRequest.Credentials = CredentialCache.DefaultNetworkCredentials;

 

            webRequest.CookieContainer = new CookieContainer();

            webRequest.CookieContainer.Add( this.cookieCollection );

 

            if ( post )

            {

                webRequest.Method = "POST";

                webRequest.ContentType = "application/x-www-form-urlencoded";

 

                webRequest.ContentLength = postData.Length;

 

                Stream requestStream = null;

 

                try

                {

                    requestStream = webRequest.GetRequestStream();

                    requestStream.Write( postData, 0, postData.Length );

                }

                catch ( Exception ex )

                {

                    this.WriteError( new ErrorRecord( ex, "Send-SMS", ErrorCategory.InvalidData, this ) );

                }

                finally

                {

                    if ( requestStream != null )

                    {

                        requestStream.Close();

                    }

                }

            }

            else

            {

                webRequest.Method = "GET";

                webRequest.ContentType = "text/html";

            }

 

            HttpWebResponse webResponse = null;

            string responseString = "";

 

            try

            {

                webResponse = (HttpWebResponse)webRequest.GetResponse();

 

                cookieCollection.Add( webResponse.Cookies );

 

                StreamReader streamReader = new StreamReader( webResponse.GetResponseStream() );

 

                responseString = streamReader.ReadToEnd();

 

                streamReader.Close();

 

                // redirect if we have a Location header

                if ( webResponse.Headers[ "Location" ] != null )

                {

                    responseString = MakeHttpWebRequest( webResponse.Headers[ "Location" ], false, null );

                }

            }

            catch ( Exception ex )

            {

                this.WriteError( new ErrorRecord( ex, "Send-SMS", ErrorCategory.InvalidResult, this ) );

            }

            finally

            {

                if ( webResponse != null )

                {

                    webResponse.Close();

                }

            }

 

            return responseString;

        }

    }

}


This Cmdlet can use the Init-Gmail PowerShell function (renamed Init-Google) I wrote for the Send-Email Cmdlet, as well as a shortcut hash I created to make sending texts easier:

function Init-Google
{
    [string]$global:GoogleUsername = Read-Host "Google username"
    [System.Security.SecureString]$global:GooglePassword = Read-Host "Google password" -AsSecureString 
}

$sms = @{ "Jeff"    = "8015551234";
          "Mindy"   = "8015552345";
          "Dad"     = "8015553456";
          "Jason"   = "8015554567";
          "Scott"   = "8015555678";
          "Nate"    = "8015556789";
          "Branden" = "8015557890" }

Using the Cmdlet is very easy:

C:\
PSH$ send-sms $sms.jeff "PowerShell + Google = Awesome."
Your SMS has been sent.

This is another one that I did just for fun, but it is already turning out to be pretty useful. I can type using a real keyboard a lot faster than I can on any phone, and not having to pull my phone out of my pocket to send a quick text to my wife is very handy.

Enjoy!