예제 #1
0
// Read handles GET
func (ctl *FileController) Read(c *models.Context) {
	fileHash := c.RouteVars["fileHash"]
	if fileHash == "" {
		c.RespondWithErrorMessage(
			fmt.Sprintf("The supplied file hash cannot be zero characters: %s", c.RouteVars["fileHash"]),
			http.StatusBadRequest,
		)
		return
	}

	fileBytes, headers, _, err := models.GetFile(fileHash)
	if err != nil {
		c.RespondWithErrorMessage(
			fmt.Sprintf("Could not retrieve file: %v", err.Error()),
			http.StatusInternalServerError,
		)
		return
	}

	oneYear := time.Hour * 24 * 365
	nextYear := time.Now().Add(oneYear)
	c.ResponseWriter.Header().Set("Cache-Control", fmt.Sprintf("max-age=%d", oneYear/time.Second))
	c.ResponseWriter.Header().Set("Expires", nextYear.Format(time.RFC1123))

	for h, v := range headers {
		c.ResponseWriter.Header().Set(h, v)
	}

	c.WriteResponse(fileBytes, http.StatusOK)
	return
}
예제 #2
0
// Read handles GET
func (ctl *GeoCodeController) Read(c *models.Context) {
	c.ResponseWriter.Header().Set("Content-Type", "application/json")

	// Debugging info
	dur := time.Now().Sub(c.StartTime)

	place := strings.Trim(c.Request.URL.Query().Get("q"), " ")

	if strings.Trim(c.Request.URL.Query().Get("q"), " ") == "" {
		ctl.Error(c, "query needed", http.StatusBadRequest)
		return
	}
	if c.Auth.ProfileID <= 0 {
		ctl.Error(c, "no auth", http.StatusForbidden)
		return
	}

	u, _ := url.Parse("http://open.mapquestapi.com/nominatim/v1/search.php")
	q := u.Query()
	q.Set("format", "json")
	// We are not interested in the array returned, just the best match which is the first response
	q.Set("limit", "1")
	q.Set("q", place)
	u.RawQuery = q.Encode()

	resp, err := http.Get(u.String())
	if err != nil {
		ctl.Error(c, err.Error(), http.StatusInternalServerError)
		return
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		ctl.Error(c, err.Error(), http.StatusInternalServerError)
		return
	}

	// Again, not interested in the outer array [], so we substring that out
	t := string(body)
	t = t[1 : len(t)-1]

	// But if we now have nothing (no matches were found, we need to return an empty object)
	if strings.Trim(t, ` `) == `` {
		t = `{}`
	}
	body = []byte(t)

	// Return our JavaScript object
	contentLength := len(body)
	c.ResponseWriter.Header().Set("Content-Length", strconv.Itoa(contentLength))
	go models.SendUsage(c, http.StatusOK, contentLength, dur, []string{})

	c.WriteResponse([]byte(body), http.StatusOK)
}
예제 #3
0
// Error is a generic error handler for the Geo controller
func (ctl *GeoCodeController) Error(c *models.Context, message string, status int) {
	errorJSON := `{"error":["` + message + `"]}`

	contentLength := len(errorJSON)
	c.ResponseWriter.Header().Set("Content-Length", strconv.Itoa(contentLength))

	dur := time.Now().Sub(c.StartTime)
	go models.SendUsage(c, status, contentLength, dur, []string{"message"})

	c.WriteResponse([]byte(errorJSON), status)
	return
}
예제 #4
0
// ReadMany handles GET
func (ctl *AttendeesCSVController) ReadMany(c *models.Context) {
	eventID, err := strconv.ParseInt(c.RouteVars["event_id"], 10, 64)
	if err != nil {
		c.RespondWithErrorMessage(
			fmt.Sprintf("The supplied event_id ('%s') is not a number.", c.RouteVars["event_id"]),
			http.StatusBadRequest,
		)
		return
	}

	// Start Authorisation
	perms := models.GetPermission(
		models.MakeAuthorisationContext(
			c, 0, h.ItemTypes[h.ItemTypeEvent], eventID),
	)
	if !perms.CanRead {
		c.RespondWithErrorMessage(h.NoAuthMessage, http.StatusForbidden)
		return
	}
	if !(perms.IsOwner || perms.IsModerator || perms.IsSiteOwner) {
		c.RespondWithErrorMessage(h.NoAuthMessage, http.StatusForbidden)
		return
	}
	// End Authorisation

	attendees, status, err := models.GetAttendeesCSV(c.Site.ID, eventID, c.Auth.ProfileID)
	if err != nil {
		c.RespondWithErrorDetail(err, status)
		return
	}

	c.ResponseWriter.Header().Set(`Cache-Control`, `no-cache, max-age=0`)
	c.ResponseWriter.Header().Set(`Vary`, `Authorization`)
	c.ResponseWriter.Header().Set(`Content-Type`, `text/csv`)
	c.ResponseWriter.Header().Set(`Content-Disposition`, fmt.Sprintf(`attachment; filename=event%d.csv`, eventID))
	c.WriteResponse([]byte(attendees), http.StatusOK)
}
예제 #5
0
// Read handles GET
func (ctl *MetricsController) Read(c *models.Context) {

	// Hard coded to only work for founders.
	if c.Auth.UserID != 1 && c.Auth.UserID != 2 {
		c.RespondWithErrorMessage(
			fmt.Sprintf("Only founders can see metrics"),
			http.StatusForbidden,
		)
		return
	}

	metrics, status, err := models.GetMetrics()
	if err != nil {
		c.RespondWithErrorMessage(
			fmt.Sprintf("Error fetching metrics: %s", err.Error()),
			status,
		)
		return
	}
	html := `<!DOCTYPE html>
<meta charset="utf-8">
<script type="text/javascript" src="https://www.google.com/jsapi"></script>`

	// Total Profiles
	idPrefix := `tp_`
	html += `
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var ` + idPrefix + `data = google.visualization.arrayToDataTable([
  ['Date', 'Total Profiles', 'Customised Profiles', 'Total Sites', 'Engaged Sites'],`

	for _, metric := range metrics {
		html += fmt.Sprintf(
			`['%s',%d, %d, %d, %d],`,
			metric.Timestamp.Local().Format("2006-01-02"),
			metric.TotalProfiles,
			metric.EditedProfiles,
			metric.TotalForums,
			metric.EngagedForums,
		)
	}

	html += `]);

var ` + idPrefix + `options = {
  title: 'Profiles vs Sites (accumulative)',
  hAxis: {title: 'Date',  titleTextStyle: {color: '#333'}},
  vAxis: {0: {logScale:false},
          1: {logScale:false}},
  series:{
  	0:{targetAxisIndex:0},
  	1:{targetAxisIndex:0},
  	2:{targetAxisIndex:1},
  	3:{targetAxisIndex:1}
  }
};

var chart = new google.visualization.AreaChart(document.getElementById('` + idPrefix + `chart'));
chart.draw(` + idPrefix + `data, ` + idPrefix + `options);
}
</script>
<div id="` + idPrefix + `chart" style="width: 900px; height: 500px;"></div>
<p style="width:900px">In the above chart a small divergence would indicate
linear growth of profiles per site = cubic growth of total population.</p>
<p style="width:900px">A massive divergence indicates a cubic growth of profiles
per site = an exponential growth of total population.</p>
`

	// Active + New Profiles
	idPrefix = `ap_`
	html += `
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var ` + idPrefix + `data = google.visualization.arrayToDataTable([
  ['Date', 'New', 'Active (1 day)'],`

	for _, metric := range metrics {
		html += fmt.Sprintf(
			`['%s',%d,%d],`,
			metric.Timestamp.Local().Format("2006-01-02"),
			metric.NewProfiles,
			metric.Signins,
		)
	}

	html += `]);

var ` + idPrefix + `options = {
  title: 'New Profiles + Active Profiles',
  hAxis: {title: 'Date',  titleTextStyle: {color: '#333'}},
  vAxis: {minValue: 0}
};

var chart = new google.visualization.AreaChart(document.getElementById('` + idPrefix + `chart'));
chart.draw(` + idPrefix + `data, ` + idPrefix + `options);
}
</script>
<div id="` + idPrefix + `chart" style="width: 900px; height: 500px;"></div>`

	// Guests vs Actives
	idPrefix = `gu_`
	html += `
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var ` + idPrefix + `data = google.visualization.arrayToDataTable([
  ['Date', 'Unique Users', 'Active Profiles (1 day)'],`

	for _, metric := range metrics {
		html += fmt.Sprintf(
			`['%s',%d,%d],`,
			metric.Timestamp.Local().Format("2006-01-02"),
			metric.Uniques,
			metric.Signins,
		)
	}

	html += `]);

var ` + idPrefix + `options = {
  title: 'Unique Users + Active Profiles',
  hAxis: {title: 'Date',  titleTextStyle: {color: '#333'}},
  vAxis: {minValue: 0}
};

var chart = new google.visualization.AreaChart(document.getElementById('` + idPrefix + `chart'));
chart.draw(` + idPrefix + `data, ` + idPrefix + `options);
}
</script>
<div id="` + idPrefix + `chart" style="width: 900px; height: 500px;"></div>`

	// Guests vs Actives
	idPrefix = `ga_`
	html += `
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var ` + idPrefix + `data = google.visualization.arrayToDataTable([
  ['Date', 'Pageviews', 'Unique Visits'],`

	for _, metric := range metrics {
		html += fmt.Sprintf(
			`['%s',%d,%d],`,
			metric.Timestamp.Local().Format("2006-01-02"),
			metric.Pageviews,
			metric.Visits,
		)
	}

	html += `]);

var ` + idPrefix + `options = {
  title: 'Pageviews + Visits',
  hAxis: {title: 'Date',  titleTextStyle: {color: '#333'}},
  vAxis: {minValue: 0}
};

var chart = new google.visualization.AreaChart(document.getElementById('` + idPrefix + `chart'));
chart.draw(` + idPrefix + `data, ` + idPrefix + `options);
}
</script>
<div id="` + idPrefix + `chart" style="width: 900px; height: 500px;"></div>`

	// Content Creation
	idPrefix = `cc_`
	html += `
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var ` + idPrefix + `data = google.visualization.arrayToDataTable([
  ['Date', 'Comments', 'Conversations'],`

	for _, metric := range metrics {
		html += fmt.Sprintf(
			`['%s',%d,%d],`,
			metric.Timestamp.Local().Format("2006-01-02"),
			metric.Comments,
			metric.Conversations,
		)
	}

	html += `]);

var ` + idPrefix + `options = {
  title: 'Content Creation',
  hAxis: {title: 'Date',  titleTextStyle: {color: '#333'}},
  vAxis: {minValue: 0}
};

var chart = new google.visualization.AreaChart(document.getElementById('` + idPrefix + `chart'));
chart.draw(` + idPrefix + `data, ` + idPrefix + `options);
}
</script>
<div id="` + idPrefix + `chart" style="width: 900px; height: 500px;"></div>`

	// Change in Content Creation
	idPrefix = `ccc_`
	html += `
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var ` + idPrefix + `data = google.visualization.arrayToDataTable([
  ['Date', 'Comments-Delta', 'Conversations-Delta'],`

	prev := metrics[0]
	for _, metric := range metrics[1:] {
		html += fmt.Sprintf(
			`['%s',%d,%d],`,
			metric.Timestamp.Local().Format("2006-01-02"),
			(metric.Comments - prev.Comments),
			(metric.Conversations - prev.Conversations),
		)
	}

	html += `]);

var ` + idPrefix + `options = {
  title: 'Content Creation',
  hAxis: {title: 'Date',  titleTextStyle: {color: '#333'}},
  vAxis: {minValue: 0}
};

var chart = new google.visualization.AreaChart(document.getElementById('` + idPrefix + `chart'));
chart.draw(` + idPrefix + `data, ` + idPrefix + `options);
}
</script>
<div id="` + idPrefix + `chart" style="width: 900px; height: 500px;"></div>`

	// Raw Data
	html += `<table>
<tr>
	<th>Timestamp</th>
	<th>Total forums</th>
	<th>Engaged forums</th>
	<th>Conversations</th>
	<th>Comments</th>
	<th>Total profiles</th>
	<th>Edited profiles</th>
	<th>New profiles</th>
	<th>Siginins</th>
	<th>Uniques</th>
	<th>Visits</th>
	<th>Pageviews</th>
</tr>
`

	for _, metric := range metrics {
		html += fmt.Sprintf(
			`<tr><td>%s</td><td>%d</td><td>%d</td><td>%d</td><td>%d</td><td>%d</td><td>%d</td><td>%d</td><td>%d</td><td>%d</td><td>%d</td><td>%d</td></tr>
`,
			metric.Timestamp.Local().Format("2006-01-02"),
			metric.TotalForums,
			metric.EngagedForums,
			metric.Conversations,
			metric.Comments,
			metric.TotalProfiles,
			metric.EditedProfiles,
			metric.NewProfiles,
			metric.Signins,
			metric.Uniques,
			metric.Visits,
			metric.Pageviews,
		)
	}
	html += `</table>`

	c.ResponseWriter.Header().Set("Content-Encoding", "text/html")
	c.WriteResponse([]byte(html), http.StatusOK)
	return
}