diff --git a/database.go b/database.go index a00a10c..47d1863 100644 --- a/database.go +++ b/database.go @@ -247,24 +247,25 @@ func (d *DB) GetTags(numTags int) ([]string, error) { return tags, nil } -type visits struct { - Month string "_id" - Count int "value" +type Visits struct { + Date int64 "_id" + Count int "value" } -func (d *DB) GetMonthVisits() ([]visits, error) { +func (d *DB) GetDayVisits(start time.Time) ([]Visits, error) { var mr mgo.MapReduce - mr.Map = "function() { " + - "var month = this.date.getMonth() + 1;" + - "var year = this.date.getFullYear();" + - "emit(month + \".\" + year, 1);" + - "}" - mr.Reduce = "function(date, vals) { " + - "var count = 0;" + - "vals.forEach(function() { count += 1; });" + - "return count;" + - "}" - var result []visits - _, err := d.stats.Find(bson.M{}).MapReduce(&mr, &result) + mr.Map = `function() { + var day = Date.UTC(this.date.getFullYear(), + this.date.getMonth(), + this.date.getDate()); + emit(day, 1); + }` + mr.Reduce = `function(date, vals) { + var count = 0; + vals.forEach(function(v) { count += v; }); + return count; + }` + var result []Visits + _, err := d.stats.Find(bson.M{"date": bson.M{"$gte": start}}).MapReduce(&mr, &result) return result, err } diff --git a/stats.go b/stats.go index 3dcd3ea..b9e8d23 100644 --- a/stats.go +++ b/stats.go @@ -4,6 +4,7 @@ import ( "github.com/gorilla/mux" "labix.org/v2/mgo/bson" "net/http" + "strconv" "strings" "time" ) @@ -46,13 +47,44 @@ func statsWorker() { func statsHandler(w http.ResponseWriter, r *http.Request, sess *Session) { var data statsData data.S = GetStatus(w, r) - data.Visits, _ = db.GetMonthVisits() + data.Daily = getDailyVisits() + loadTemplate(w, "stats", data) } type statsData struct { - S Status - Visits []visits + S Status + Daily []visitData +} + +type visitData struct { + Label string + Count int +} + +func getDailyVisits() []visitData { + const numDays = 30 + visits := make([]visitData, numDays) + + start := time.Now().Add(-numDays * 24 * time.Hour).Truncate(24 * time.Hour) + visit, _ := db.GetDayVisits(start) + prevDay := start.Day() + i := 0 + for _, v := range visit { + day := time.Unix(v.Date/1000, 0).Day() + for prevDay+1 < day { + prevDay++ + visits[i].Label = strconv.Itoa(prevDay) + visits[i].Count = 0 + i++ + } + visits[i].Label = strconv.Itoa(day) + visits[i].Count = v.Count + prevDay = day + i++ + } + + return visits } func appendFiles(r *http.Request, stats map[string]interface{}) { diff --git a/templates/stats.html b/templates/stats.html index 152c33c..dd81785 100644 --- a/templates/stats.html +++ b/templates/stats.html @@ -3,28 +3,26 @@
-
-

Visits:

- -
+

Daily visits:

+