#!/usr/bin/env python

from os.path import expanduser
from time import sleep
import subprocess, json, sys, os

messagesDbPath = '%s/Library/Messages/chat.db' % expanduser('~')

# manually parse the QUERY_STRING because "+" is being weirdly decoded via FieldStorage
queryParameters = {}
keyValues = os.environ['QUERY_STRING'].split('&')
for pair in keyValues:
  key, value = pair.split('=')
  queryParameters[key] = value

body = queryParameters['body'] or ''
messageTo = queryParameters['messageTo'] or ''
payload = {'body': body, 'messageTo': messageTo}

sendExitCode = subprocess.call(['./SendImessage.applescript', messageTo, body])

verificationError = None

# monitor send status of message
if sendExitCode == 0:
  iterations = 0
  whereClause = 'handle.id = "%s" AND message.text = "%s"' % (messageTo, body)
  query = 'SELECT message.ROWID, message.error, message.is_delivered, datetime(message.date + 978307200, "unixepoch", "localtime") FROM message JOIN handle ON message.handle_id = handle.ROWID WHERE %s ORDER BY message.date DESC LIMIT 1'
  chatId = None
  while iterations < 5:
    if chatId is not None:
      builtQuery = query % ('message.ROWID = %s' % chatId)
    else:
      builtQuery = query % whereClause
    #builtQuery = 'select * from message limit 1'
    try:
      output = subprocess.check_output(['sqlite3', messagesDbPath, builtQuery], stderr=subprocess.STDOUT)
      #print >> sys.stderr, builtQuery
      #print >> sys.stderr, output
    except subprocess.CalledProcessError as e:
      print >> sys.stderr, e.output
      verificationError = e.output
      break

    if output:
      chatId, verificationError, isDelivered, date = output.split('|')

      verificationError = int(verificationError)
      if int(isDelivered) == 1 or verificationError != 0:
        break
    iterations += 1
    sleep(1)

payload['ok'] = sendExitCode == 0 and verificationError == 0
if payload['ok'] is False:
  if verificationError == 22:
    payload['error'] = 'invalid handle'
  elif sendExitCode != 0:
    payload['error'] = 'message not sent'
  else:
    payload['error'] = 'imessage error `%d`' % verificationError

print 'Content-Type: application/json'
print ''
print json.dumps(payload)

@@ -76,16 +76,21 @@
 p%0Aimport
+ cgi,
  subproc
@@ -108,16 +108,16 @@
 sys, os%0A
-
 %0Amessage
@@ -179,289 +179,76 @@
 ')%0A%0A
-# manually parse the QUERY_STRING because %22+%22 is being weirdly decoded via FieldStorage%0AqueryParameters = %7B%7D%0AkeyValues = os.environ%5B'QUERY_STRING'%5D.split('&')%0Afor pair in keyValues:%0A  key, value = pair.split('=')%0A  queryParameters%5Bkey%5D = value%0A%0Abody = queryParameters%5B
+arguments = cgi.FieldStorage()%0Abody = arguments.getvalue(
 'body'
-%5D or
+,
  ''
+)
 %0Ames
@@ -260,24 +260,27 @@
 o = 
-queryParameters%5B
+arguments.getvalue(
 'mes
@@ -290,15 +290,13 @@
 eTo'
-%5D or
+,
  ''
+)
 %0Apay

Revert back to FieldStorage