import os
from flask import Flask, render_template, request, redirect
from flask.ext.bootstrap import Bootstrap
from urllib2 import urlopen, Request
import json
from icalendar import Calendar, Event
import pytz
from datetime import datetime
import hashlib

app = Flask(__name__)
Bootstrap(app)

app.config['BOOTSTRAP_USE_MINIFIED'] = True
app.config['BOOTSTRAP_USE_CDN'] = True
app.config['BOOTSTRAP_FONTAWESOME'] = True

beeminder_client_id = os.environ["BEEMINDER_CLIENT_ID"]
site_redirect_address = os.environ["SITE_ADDRESS"] + "/oauth"

@app.route('/')
def index():
	return render_template('index.html', beeminder_client_id = beeminder_client_id, site_redirect_address = site_redirect_address)

@app.route("/oauth")
def oauth():
	access_token = request.args.get("access_token", None)
	if access_token == None:
		return redirect("/")
	data = urlopen("https://www.beeminder.com/api/v1/users/me.json?access_token=%s"%(access_token)).read()
	data = json.loads(data)
	return redirect("/calendar/%s?access_token=%s&timezone=%s"%(data["username"], access_token, data["timezone"]))

@app.route('/calendar/<username>')
def calendar(username):
	access_token = request.args.get("access_token")
	tz = pytz.timezone(request.args.get("timezone"))

	data = urlopen("https://www.beeminder.com/api/v1/users/%s/goals.json?access_token=%s"%(username, access_token)).read()
	data = json.loads(data)

	cal = Calendar()
	cal.add('prodid', '-//Beeminder calendar//tevp.net//')
	cal.add('version', '2.0')
	cal.add('X-WR-CALNAME', 'Beeminder Calendar for %s'%username)

	for goal in data:
		enddate = datetime.fromtimestamp(goal["losedate"]).replace(tzinfo = tz)
		startdate = enddate.replace(hour=0, minute=0, second=0)
		title = goal["title"]
		event = Event()
		event.add('summary', "Beeminder fail day for %s" % title)
		event.add('dtstart', startdate)
		event.add('dtend', enddate)
		event['uid'] = hashlib.md5(title).hexdigest()
		cal.add_component(event)

	return cal.to_ical()

if '__main__' == __name__:
	app.run(debug=True, port=8080)

@@ -233,16 +233,27 @@
 datetime
+, timedelta
 %0Aimport 
@@ -1020,20 +1020,8 @@
 n=%25s
-&timezone=%25s
 %22%25(d
@@ -1053,26 +1053,8 @@
 oken
-, data%5B%22timezone%22%5D
 ))%0A%0A
@@ -1164,58 +1164,8 @@
 en%22)
-%0A%09tz = pytz.timezone(request.args.get(%22timezone%22))
 %0A%0A%09d
@@ -1494,19 +1494,21 @@
 data:%0A%09%09
-end
+start
 date = d
@@ -1551,85 +1551,57 @@
 %22%5D).
-replace(tzinfo = tz)%0A%09%09startdate = enddate.replace(hour=0, minute=0, second=0
+date()%0A%09%09enddate = startdate + timedelta(days = 1
 )%0A%09%09

Make events "whole day" entries