2016-11-21 12:24:50 +00:00
|
|
|
package api
|
2016-11-19 21:35:23 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
|
|
|
"log"
|
|
|
|
"github.com/mssola/user_agent"
|
2016-11-21 12:24:50 +00:00
|
|
|
"github.com/dannyvankooten/ana/models"
|
|
|
|
"github.com/dannyvankooten/ana/core"
|
2016-11-19 21:35:23 +00:00
|
|
|
)
|
|
|
|
|
2016-11-21 12:24:50 +00:00
|
|
|
func CollectHandler(w http.ResponseWriter, r *http.Request) {
|
2016-11-19 21:35:23 +00:00
|
|
|
ua := user_agent.New(r.UserAgent())
|
2016-11-21 12:24:50 +00:00
|
|
|
|
|
|
|
// abort if this is a bot.
|
2016-11-19 21:35:23 +00:00
|
|
|
if ua.Bot() {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// prepare statement for inserting data
|
2016-11-21 12:24:50 +00:00
|
|
|
stmt, err := core.DB.Prepare(`INSERT INTO visits(
|
2016-11-19 21:35:23 +00:00
|
|
|
ip_address,
|
2016-11-21 15:01:14 +00:00
|
|
|
path,
|
2016-11-19 21:35:23 +00:00
|
|
|
referrer_url,
|
|
|
|
browser_language,
|
|
|
|
browser_name,
|
|
|
|
browser_version,
|
|
|
|
device_os,
|
|
|
|
screen_resolution
|
|
|
|
) VALUES( ?, ?, ?, ?, ?, ?, ?, ? )`)
|
|
|
|
if err != nil {
|
|
|
|
log.Fatal(err.Error())
|
|
|
|
}
|
|
|
|
defer stmt.Close()
|
|
|
|
|
|
|
|
// TODO: Mask IP Address
|
|
|
|
// TODO: Query DB to determine whether visitor is returning
|
2016-11-25 15:39:51 +00:00
|
|
|
ipAddress := r.RemoteAddr
|
|
|
|
headerForwardedFor := r.Header.Get("X-Forwarded-For")
|
|
|
|
if( headerForwardedFor != "" ) {
|
|
|
|
ipAddress = headerForwardedFor
|
|
|
|
}
|
2016-11-19 21:35:23 +00:00
|
|
|
|
|
|
|
q := r.URL.Query()
|
2016-11-21 12:24:50 +00:00
|
|
|
visit := models.Visit{
|
2016-11-19 21:35:23 +00:00
|
|
|
Path: q.Get("p"),
|
2016-11-25 15:39:51 +00:00
|
|
|
IpAddress: ipAddress,
|
2016-11-19 21:35:23 +00:00
|
|
|
ReferrerUrl: q.Get("r"),
|
|
|
|
BrowserLanguage: q.Get("l"),
|
|
|
|
ScreenResolution: q.Get("sr"),
|
|
|
|
}
|
|
|
|
|
|
|
|
// add browser details
|
|
|
|
visit.BrowserName, visit.BrowserVersion = ua.Browser()
|
|
|
|
|
|
|
|
// add device details
|
|
|
|
visit.DeviceOS = ua.OS()
|
|
|
|
|
|
|
|
_, err = stmt.Exec(
|
|
|
|
visit.IpAddress,
|
|
|
|
visit.Path,
|
|
|
|
visit.ReferrerUrl,
|
|
|
|
visit.BrowserLanguage,
|
|
|
|
visit.BrowserName,
|
|
|
|
visit.BrowserVersion,
|
|
|
|
visit.DeviceOS,
|
|
|
|
visit.ScreenResolution,
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
log.Fatal(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
// don't you cache this
|
|
|
|
w.Header().Set("Content-Type", "image/gif")
|
|
|
|
w.Header().Set("Expires", "Mon, 01 Jan 1990 00:00:00 GMT")
|
|
|
|
w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
|
|
|
|
w.Header().Set("Pragma", "no-cache")
|
|
|
|
w.Header().Set("Status", "200")
|
|
|
|
}
|