Example #1
0
// Handles "raw" query by spitting out raw Events list.
func serveCalendar(c web.C, w http.ResponseWriter, r *http.Request) error {
	fbID := c.URLParams["fbID"]
	u, err := GetUser(UserSpec{FacebookID: fbID})
	if err != nil {
		return err
	}
	var query calendarQuery
	if err := schema.NewDecoder().Decode(&query, r.URL.Query()); err != nil {
		return err
	}
	// Check that the user's secret key is valid.
	if query.Key != u.SecretKey() {
		return fmt.Errorf("User %d has invalid key for URL %q", u.ID, r.URL)
	}
	// Check to see if the user has a valid access token.
	if !u.AccessToken.Valid || u.ExpiresOn == nil || u.ExpiresOn.Before(time.Now()) {
		return fmt.Errorf("The access token for %d is not valid", u.ID)
	}
	fbSession := fb.Session(u.AccessToken.String)
	res, err := fbSession.Get("/me/events?"+
		"fields=owner,end_time,description,id,name,rsvp_status,"+
		"place,start_time,timezone", nil)
	if err != nil {
		return fmt.Errorf("Could not get events: %s", err)
	}
	pr, err := res.Paging(fbSession)
	if err != nil {
		return fmt.Errorf("Could not use as paging result: %s", err)
	}
	var allEvents []Event
	dateMarker := time.Now().Add(-48 * time.Hour)
outer:
	for {
		for _, r := range pr.Data() {
			var e Event
			if err := r.Decode(&e); err != nil {
				return fmt.Errorf("Could not decode events: %s", err)
			}
			dt, err := parseFacebookDateTime(e.StartTime)
			if err != nil {
				return fmt.Errorf("Error during calendar generation: %s", err)
			}
			e.startTimeParsed = dt
			if e.startTimeParsed.T.Before(dateMarker) {
				break outer
			}
			if e.RSVPStatus == "attending" {
				allEvents = append(allEvents, e)
			}
		}
		if !pr.HasNext() {
			break
		}
		pr.Next()
	}
	if query.Raw {
		// The URL has the query "raw".
		w.Write([]byte(fmt.Sprintf("%+v", allEvents)))
		return nil
	}
	cal, err := generateICal(fbID, u.Name, allEvents)
	if err != nil {
		return fmt.Errorf("Error generating calendar for %s: %s", fbID, err)
	}
	w.Write(cal)
	return nil
}