'Fetches the inbound SMS from Mobile Commons API
http://www.mobilecommons.com/mobile-commons-api/rest/#ListIncomingMessages'

@staticmethod
def poll_mcommons(channel_id):

    db = current.db
    s3db = current.s3db
    table = s3db.msg_mcommons_channel
    query = (table.channel_id == channel_id)
    channel = db(query).select(table.url, table.campaign_id, table.username, table.password, table.query, table.timestmp, limitby=(0, 1)).first()
    if (not channel):
        return ('No    Such    MCommons    Channel:    %s' % channel_id)
    url = channel.url
    username = channel.username
    password = channel.password
    _query = channel.query
    timestamp = channel.timestmp
    url = ('%s?campaign_id=%s' % (url, channel.campaign_id))
    if timestamp:
        url = ('%s&start_time=%s' % (url, timestamp))
    if _query:
        url = ('%s&query=%s' % (url, _query))
    passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
    passman.add_password(None, url, username, password)
    authhandler = urllib2.HTTPBasicAuthHandler(passman)
    opener = urllib2.build_opener(authhandler)
    urllib2.install_opener(opener)
    db(query).update(timestmp=current.request.utcnow)
    try:
        _response = urllib2.urlopen(url)
    except urllib2.HTTPError as e:
        return ('Error:    %s' % e.code)
    else:
        sms_xml = _response.read()
        tree = etree.XML(sms_xml)
        messages = tree.findall('.//message')
        mtable = s3db.msg_sms
        minsert = mtable.insert
        update_super = s3db.update_super
        decode = s3_decode_iso_datetime
        parser = s3db.msg_parser_enabled(channel_id)
        if parser:
            ptable = db.msg_parsing_status
            pinsert = ptable.insert
        for message in messages:
            sender_phone = message.find('phone_number').text
            body = message.find('body').text
            received_on = decode(message.find('received_at').text)
            _id = minsert(channel_id=channel_id, sender_phone=sender_phone, body=body, received_on=received_on)
            record = dict(id=_id)
            update_super(mtable, record)
            if parser:
                pinsert(message_id=record['message_id'], channel_id=channel_id)
    return 'OK'
