2012-11-19

Retrieving Google Calendar Events with Python

I was looking for sample code to retrieve a set of events from Google Calendar via the google-api-python-client v3.  The information is scattered around different places.  Below I put everything together to remind my future self how to do it.

Note that the first time you run it, you will have to manually authorize the initial oauth credential through a web browser.

You can install google-api-python-client by:
sudo pip install google-api-python-client

man.py - test code
google_calendar.py - sample code provided by Google 
 
--[ main.py

calendarId = 'user@example.com'

import google_calendar
import pprint

def getEvents(pageToken=None):
    events = google_calendar.service.events().list(
        calendarId=calendarId,
        singleEvents=True,
        maxResults=1000,
        orderBy='startTime',
        timeMin='2012-11-01T00:00:00-08:00',
        timeMax='2012-11-30T00:00:00-08:00',
        pageToken=pageToken,
        ).execute()
    return events


def main():
    events = getEvents()
    while True:
        for event in events['items']:
            pprint.pprint(event)
        page_token = events.get('nextPageToken')
        if page_token:
            events = getEvents(page_token)
        else:
            break

if __name__ == '__main__':
    main()


--[ google_calendar.py

client_id='123456789012.apps.googleusercontent.com'
client_secret='aBcDeFgHiGkLMnOpQrStUvWx'
user_agent='xxxxxxxx/vXX'
developerKey='aBcDeFgHiGkLMnOpQrStUvWxYZ1234567890,.;'

import os.path
here = os.path.dirname(os.path.realpath(__file__))
storage_file = os.path.join(here, 'calendar.dat')

import gflags
import httplib2

from apiclient.discovery import build
from oauth2client.file import Storage
from oauth2client.client import OAuth2WebServerFlow
from oauth2client.tools import run

FLAGS = gflags.FLAGS

# Set up a Flow object to be used if we need to authenticate. This
# sample uses OAuth 2.0, and we set up the OAuth2WebServerFlow with
# the information it needs to authenticate. Note that it is called
# the Web Server Flow, but it can also handle the flow for native
# applications
# The client_id and client_secret are copied from the API Access tab on
# the Google APIs Console
FLOW = OAuth2WebServerFlow(
    client_id=client_id,
    client_secret=client_secret,
    scope='https://www.googleapis.com/auth/calendar',
    user_agent=user_agent)

# To disable the local server feature, uncomment the following line:
FLAGS.auth_local_webserver = False

# If the Credentials don't exist or are invalid, run through the native client
# flow. The Storage object will ensure that if successful the good
# Credentials will get written back to a file.
storage = Storage(storage_file)
credentials = storage.get()
if credentials is None or credentials.invalid == True:
  credentials = run(FLOW, storage)

# Create an httplib2.Http object to handle our HTTP requests and authorize it
# with our good Credentials.
http = httplib2.Http()
http = credentials.authorize(http)

# Build a service object for interacting with the API. Visit
# the Google APIs Console
# to get a developerKey for your own application.
service = build(serviceName='calendar', version='v3', http=http,
       developerKey=developerKey)
      

2012-11-09

Android CherryPy Cam

Android Twisted SpyCam:
http://kbcarte.wordpress.com/2011/08/31/android-twisted-spycam

Running CherryPy on Android:
http://www.defuze.org/archives/228-running-cherrypy-on-android-with-sl4a.html

Combining the two to run a CherryPy app on Android, which allow you to take a snapshot remotely by visiting http://x.x.x.x:8080 from a browser in the same LAN segment.

It needs to acquire at least a dim wakelock, otherwise it won't work after android goes to sleep.  Have to kill the app to release the wakelock though.

# -*- coding: utf-8 -*-

# Visit <phone_IP>:8080 to take a snapshot
# and display the snapshot in the web page.
# dkf 121104 creation

# The multiprocessing package isn't
# part of the ASE installation so
# we must disable multiprocessing logging
import logging
logging.logMultiprocessing = 0

import os.path

import android
import cherrypy

droid = android.Android()
here = os.path.abspath(os.path.dirname(__file__))

def snap():
    fn = os.path.join(here, 'latest.jpg')
    droid.cameraCapturePicture(fn, True)
    im = open(fn, 'rb')
    shot = im.read()
    im.close()
    os.remove(fn)
    return shot

class Root(object):
    def __init__(self):
        self.droid = android.Android()

    @cherrypy.expose
    def index(self):
        return "<a href='snapshot'>Click here to take snapshot</a>"

    @cherrypy.expose
    def snapshot(self):
        cherrypy.response.headers['content-type'] = 'image/jpeg'
        return snap()

def run():
    cherrypy.config.update({'server.socket_host': '0.0.0.0'})
    cherrypy.quickstart(Root(), '/')

if __name__ == '__main__':
    droid.wakeLockAcquireDim()
    run()


2012-02-18

Swapping text segments in Vim

I have a text file with a lot of lines like these:

somebody@abc.com,someoneelse@xyz.com (Invoice 10001234) Recipient Refused
john@company.ca (Invoice 10001235) Recipient Refused
manager@firm.com (Invoice 10001235)

which I would like to turn into lines like these:

(Invoice 10001234) somebody@abc.com,someoneelse@xyz.com  Recipient Refused
(Invoice 10001235) john@company.ca  Recipient Refused
(Invoice 10001235) manager@firm.com

It can be done in Vim with the following command:

:%s#\(.*\)\((Invoice [^)]*)\)\(.*\)#\2 \1\3#

Explanation:

:   command mode
%s  substitute in whole file
#   separator

\(.*\)                1st grouping
\((Invoice [^)]*)\)   2nd grouping
\(.*\)                3rd grouping

In 2nd grouping,
[^)]*  match as many characters as possible as long as it is not )

\1  back reference to 1st grouping

\2  back reference to 2nd grouping
\3  back reference to 3rd grouping


Vim is powerful!

2012-01-23

Getting LAN IP address of local computer

Using Python to get the LAN IP address of the local computer:

If we use:

import socket
socket.gethostbyname('localhost')

we will get '127.0.0.1' which may not be what we want due to the presence of the hosts file.

We could use:

import socket
socket.gethostbyname(os.environ['COMPUTERNAME'])

we will get something like '192.168.0.xxx' which is more likely what we want.

The above code fragment works in Windows XP, may need adjustment in getting the host name in other OS.


2012-01-19

Install Apache 2.2 in Fedora 15

I would like to install Apache (2.2) in Fedora 15, and found this post useful.  In short, these are the steps:
  1. sudo yum install httpd
  2. sudo chkconfig httpd on (run on startup)
  3. /etc/init.d/httpd start (start service now)
  4. netstat -tulpn | grep :80 (verify)
The netstat flags are:

-t tcp
-u udp
-l listening
-p program
-n numeric

And the Apache config file is here:

/etc/httpd/conf/httpd.conf