本文整理汇总了Golang中github.com/skypies/complaints/complaintdb.NewDB函数的典型用法代码示例。如果您正苦于以下问题:Golang NewDB函数的具体用法?Golang NewDB怎么用?Golang NewDB使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewDB函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: purgeuserHandler
func purgeuserHandler(w http.ResponseWriter, r *http.Request) {
ctx := req2ctx(r)
cdb := complaintdb.NewDB(ctx)
email := r.FormValue("email")
str := fmt.Sprintf("(purgeuser for %s)\n", email)
q := cdb.QueryAllByEmailAddress(email).KeysOnly()
keys, err := q.GetAll(cdb.Ctx(), nil)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
str += fmt.Sprintf("purge: %d complaints found\n", len(keys))
if r.FormValue("forrealz") == "1" {
maxRm := 400
for len(keys) > maxRm {
if err := datastore.DeleteMulti(cdb.Ctx(), keys[0:maxRm-1]); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
keys = keys[maxRm:]
}
str += "all deleted :O\n"
}
w.Header().Set("Content-Type", "text/plain")
w.Write([]byte(fmt.Sprintf("OK, purge\n%s", str)))
}
示例2: isBanned
func isBanned(r *http.Request) bool {
ctx := req2ctx(r)
cdb := complaintdb.NewDB(ctx)
u := user.Current(cdb.Ctx())
userWhitelist := map[string]int{
"[email protected]": 1,
"[email protected]": 1,
"[email protected]": 1,
"[email protected]": 1,
}
reqBytes, _ := httputil.DumpRequest(r, true)
cdb.Infof("remoteAddr: '%v'", r.RemoteAddr)
cdb.Infof("user: '%v' (%s)", u, u.Email)
cdb.Infof("inbound IP determined as: '%v'", getIP(r))
cdb.Infof("HTTP req:-\n%s", string(reqBytes))
if strings.HasPrefix(r.UserAgent(), "python") {
cdb.Infof("User-Agent rejected")
return true
}
if _, exists := userWhitelist[u.Email]; !exists {
cdb.Infof("user not found in whitelist")
return true
}
return false
}
示例3: deleteComplaintsHandler
func deleteComplaintsHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) {
cdb := complaintdb.NewDB(ctx)
sesh, _ := GetUserSession(ctx)
r.ParseForm()
// This is so brittle; need to move away from display text
if r.FormValue("act") == "CANCEL" {
http.Redirect(w, r, "/", http.StatusFound)
return
} else if r.FormValue("act") == "UPDATE/EDIT LIST" {
http.Redirect(w, r, "/edit", http.StatusFound)
return
}
keyStrings := []string{}
for k, _ := range r.Form {
if len(k) < 50 {
continue
}
keyStrings = append(keyStrings, k)
}
cdb.Infof("Deleting %d complaints for %s", len(keyStrings), sesh.Email)
if err := cdb.DeleteComplaints(keyStrings, sesh.Email); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
http.Redirect(w, r, "/", http.StatusFound)
}
示例4: complaintUpdateFormHandler
func complaintUpdateFormHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) {
cdb := complaintdb.NewDB(ctx)
sesh, _ := GetUserSession(ctx)
key := r.FormValue("k")
if complaint, err := cdb.GetComplaintByKey(key, sesh.Email); err != nil {
cdb.Errorf("updateform, getComplaint: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
} else {
cdb.Infof("Loaded complaint: %+v", complaint)
var params = map[string]interface{}{
"ActivityList": kActivities, // lives in add-complaint
"DefaultFlightNumber": complaint.AircraftOverhead.FlightNumber,
"DefaultTimestamp": complaint.Timestamp,
"DefaultActivity": complaint.Activity,
"DefaultLoudness": complaint.Loudness,
"DefaultSpeedbrakes": complaint.HeardSpeedbreaks,
"DefaultDescription": complaint.Description,
"C": complaint,
}
if err := templates.ExecuteTemplate(w, "complaint-updateform", params); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
}
示例5: upgradeHandler
// Grab all users, and enqueue them for batch processing
func upgradeHandler(w http.ResponseWriter, r *http.Request) {
ctx := req2ctx(r)
cdb := complaintdb.NewDB(ctx)
var cps = []types.ComplainerProfile{}
cps, err := cdb.GetAllProfiles()
if err != nil {
cdb.Errorf("upgradeHandler: getallprofiles: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
for _, cp := range cps {
t := taskqueue.NewPOSTTask("/backend/cdb-batch-user", map[string][]string{
"email": {cp.EmailAddress},
})
if _, err := taskqueue.Add(cdb.Ctx(), t, "batch"); err != nil {
cdb.Errorf("upgradeHandler: enqueue: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
cdb.Infof("enqueued %d batch", len(cps))
w.Write([]byte(fmt.Sprintf("OK, enqueued %d", len(cps))))
}
示例6: profileButtonAddHandler
func profileButtonAddHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) {
cdb := complaintdb.NewDB(ctx)
sesh, _ := GetUserSession(ctx)
cp, _ := cdb.GetProfileByEmailAddress(sesh.Email)
if r.FormValue("NewButtonId") != "" {
id := sanitizeButtonId(r.FormValue("NewButtonId"))
if len(id) != 16 {
http.Error(w, fmt.Sprintf("Button ID must have sixteen characters; only got %d", len(id)),
http.StatusInternalServerError)
return
}
// Check we don't have the button registered already. This isn't super safe.
if existingProfile, _ := cdb.GetProfileByButtonId(id); existingProfile != nil {
http.Error(w, fmt.Sprintf("Button '%s' is already claimed", id), http.StatusBadRequest)
return
}
cp.ButtonId = append(cp.ButtonId, id)
if err := cdb.PutProfile(*cp); err != nil {
cdb.Errorf("profileUpdate: cdb.Put: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
var params = map[string]interface{}{"Buttons": cp.ButtonId}
if err := templates.ExecuteTemplate(w, "buttons", params); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
示例7: addComplaintHandler
// HandleWithSession should handle all situations where we don't have an email address
func addComplaintHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) {
cdb := complaintdb.NewDB(ctx)
cdb.Debugf("ac_001", "num cookies: %d", len(r.Cookies()))
for _, c := range r.Cookies() {
cdb.Debugf("ac_001", "cookie: %s", c)
}
cdb.Debugf("ac_001a", "Cf-Connecting-Ip: %s", r.Header.Get("Cf-Connecting-Ip"))
reqBytes, _ := httputil.DumpRequest(r, true)
cdb.Debugf("ac_002", "req: %s", reqBytes)
sesh, _ := GetUserSession(ctx)
cdb.Debugf("ac_003", "have email")
complaint := form2Complaint(r)
//complaint.Timestamp = complaint.Timestamp.AddDate(0,0,-3)
cdb.Debugf("ac_004", "calling cdb.ComplainByEmailAddress")
if err := cdb.ComplainByEmailAddress(sesh.Email, &complaint); err != nil {
cdb.Errorf("cdb.Complain failed: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
cdb.Debugf("ac_900", "all done, about to redirect")
http.Redirect(w, r, "/", http.StatusFound)
}
示例8: profileFormHandler
func profileFormHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) {
// https, yay
if r.URL.Host == "stop.jetnoise.net" {
// We're behind cloudflare, so we always see http. This is how we can tell if the user is
// using https ...
if r.Header.Get("Cf-Visitor") != `{"scheme":"https"}` {
safeUrl := r.URL
safeUrl.Scheme = "https"
http.Redirect(w, r, safeUrl.String(), http.StatusFound)
return
}
}
sesh, _ := GetUserSession(ctx)
cdb := complaintdb.NewDB(ctx)
cp, _ := cdb.GetProfileByEmailAddress(sesh.Email)
if cp.EmailAddress == "" {
// First ever visit - empty profile !
cp.EmailAddress = sesh.Email
cp.CcSfo = true
}
var params = map[string]interface{}{
"Profile": cp,
"MapsAPIKey": kGoogleMapsAPIKey, // For autocomplete & latlong goodness
}
params["Message"] = r.FormValue("msg")
if err := templates.ExecuteTemplate(w, "profile-edit", params); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
示例9: SendEmailToAllUsers
func SendEmailToAllUsers(r *http.Request, subject string) int {
ctx := req2ctx(r)
cdb := complaintdb.NewDB(ctx)
if cps, err := cdb.GetAllProfiles(); err != nil {
cdb.Errorf("SendEmailToAllUsers/GetAllProfiles: %v", err)
return 0
} else {
buf := new(bytes.Buffer)
params := map[string]interface{}{}
if err := templates.ExecuteTemplate(buf, "email-update", params); err != nil {
return 0
}
n := 0
for _, cp := range cps {
msg := &mail.Message{
Sender: kSenderEmail,
ReplyTo: kSenderEmail,
To: []string{cp.EmailAddress},
Subject: subject,
HTMLBody: buf.String(),
}
if err := mail.Send(cdb.Ctx(), msg); err != nil {
cdb.Errorf("Could not send useremail to <%s>: %v", cp.EmailAddress, err)
}
n++
}
return n
}
}
示例10: profileUpdateHandler
func profileUpdateHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) {
cdb := complaintdb.NewDB(ctx)
r.ParseForm()
lat, err := strconv.ParseFloat(r.FormValue("Lat"), 64)
if err != nil {
cdb.Errorf("profileUpdate:, parse lat '%s': %v", r.FormValue("Lat"), err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
long, err2 := strconv.ParseFloat(r.FormValue("Long"), 64)
if err2 != nil {
cdb.Errorf("profileUpdate:, parse long '%s': %v", r.FormValue("Long"), err)
http.Error(w, err2.Error(), http.StatusInternalServerError)
return
}
sesh, _ := GetUserSession(ctx)
// Maybe make a call to fetch the elevation ??
// https://developers.google.com/maps/documentation/elevation/intro
cp := types.ComplainerProfile{
EmailAddress: sesh.Email,
CallerCode: r.FormValue("CallerCode"),
FullName: strings.TrimSpace(r.FormValue("FullName")),
Address: strings.TrimSpace(r.FormValue("AutoCompletingMagic")),
StructuredAddress: types.PostalAddress{
Number: r.FormValue("AddrNumber"),
Street: r.FormValue("AddrStreet"),
City: r.FormValue("AddrCity"),
State: r.FormValue("AddrState"),
Zip: r.FormValue("AddrZip"),
Country: r.FormValue("AddrCountry"),
},
CcSfo: true, //FormValueCheckbox(r, "CcSfo"),
DataSharing: FormValueTriValuedCheckbox(r, "DataSharing"),
ThirdPartyComms: FormValueTriValuedCheckbox(r, "ThirdPartyComms"),
Lat: lat,
Long: long,
ButtonId: []string{},
}
// Preserve some values from the old profile
if origProfile, err := cdb.GetProfileByEmailAddress(sesh.Email); err == nil {
cp.ButtonId = origProfile.ButtonId
}
if err := cdb.PutProfile(cp); err != nil {
cdb.Errorf("profileUpdate: cdb.Put: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
http.Redirect(w, r, "/", http.StatusFound)
}
示例11: profileButtonsHandler
func profileButtonsHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) {
sesh, _ := GetUserSession(ctx)
cdb := complaintdb.NewDB(ctx)
cp, _ := cdb.GetProfileByEmailAddress(sesh.Email)
var params = map[string]interface{}{"Buttons": cp.ButtonId}
if err := templates.ExecuteTemplate(w, "buttons", params); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
示例12: userReportHandler
func userReportHandler(w http.ResponseWriter, r *http.Request) {
ctx := req2ctx(r)
cdb := complaintdb.NewDB(ctx)
profiles, err := cdb.GetAllProfiles()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if true {
nOK, nNotOK, nDefault := 0, 0, 0
for _, p := range profiles {
switch {
case p.DataSharing < 0:
nNotOK++
case p.DataSharing > 0:
nOK++
case p.DataSharing == 0:
nDefault++
}
}
w.Header().Set("Content-Type", "text/plain")
fmt.Fprintf(w, "nOK=%d, nDefault=%d, nNotOk=%d\n", nOK, nDefault, nNotOK)
return
}
filename := date.NowInPdt().Format("users-as-of-20060102.csv")
w.Header().Set("Content-Type", "application/csv")
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", filename))
cols := []string{"EMAIL", "NAME", "CALLERCODE", "STREET", "CITY", "ZIP", "ALLINONELINE"}
csvWriter := csv.NewWriter(w)
csvWriter.Write(cols)
for _, p := range profiles {
street := p.StructuredAddress.Street
if p.StructuredAddress.Number != "" {
street = p.StructuredAddress.Number + " " + street
}
row := []string{
p.EmailAddress,
p.FullName,
p.CallerCode,
street,
p.StructuredAddress.City,
p.StructuredAddress.Zip,
p.Address,
}
csvWriter.Write(row)
}
csvWriter.Flush()
}
示例13: downloadHandler
func downloadHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) {
sesh, _ := GetUserSession(ctx)
filename := date.NowInPdt().Format("complaints-20060102.csv")
w.Header().Set("Content-Type", "application/csv")
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", filename))
cols := []string{
"Date", "Time(PDT)", "Notes", "Speedbrakes", "Loudness", "Activity",
"Flightnumber", "Origin", "Destination", "Speed(Knots)", "Altitude(Feet)",
"Lat", "Long", "Registration", "Callsign",
"VerticalSpeed(FeetPerMin)", "Dist2(km)", "Dist3(km)",
"City",
}
csvWriter := csv.NewWriter(w)
csvWriter.Write(cols)
cdb := complaintdb.NewDB(ctx)
iter := cdb.NewIter(cdb.QueryAllByEmailAddress(sesh.Email))
for {
c, err := iter.NextWithErr()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if c == nil {
break
}
a := c.AircraftOverhead
speedbrakes := ""
if c.HeardSpeedbreaks {
speedbrakes = "y"
}
r := []string{
c.Timestamp.Format("2006/01/02"),
c.Timestamp.Format("15:04:05"),
c.Description, speedbrakes, fmt.Sprintf("%d", c.Loudness), c.Activity,
a.FlightNumber, a.Origin, a.Destination,
fmt.Sprintf("%.0f", a.Speed), fmt.Sprintf("%.0f", a.Altitude),
fmt.Sprintf("%.5f", a.Lat), fmt.Sprintf("%.5f", a.Long),
a.Registration, a.Callsign, fmt.Sprintf("%.0f", a.VerticalSpeed),
fmt.Sprintf("%.1f", c.Dist2KM), fmt.Sprintf("%.1f", c.Dist3KM),
c.Profile.GetStructuredAddress().City,
}
if err := csvWriter.Write(r); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
csvWriter.Flush()
}
示例14: addHistoricalComplaintHandler
func addHistoricalComplaintHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) {
cdb := complaintdb.NewDB(ctx)
sesh, _ := GetUserSession(ctx)
complaint := form2Complaint(r)
if err := cdb.AddHistoricalComplaintByEmailAddress(sesh.Email, &complaint); err != nil {
cdb.Errorf("cdb.HistoricalComplain failed: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Write([]byte(fmt.Sprintf("Added OK\n")))
}
示例15: countHackHandler
// countHackHandler will append a new complaint total to the daily counts object.
// These are sorted elsewhere, so it's OK to 'append' out of sequence.
// Note no deduping is done; if you want that, add it here.
func countHackHandler(w http.ResponseWriter, r *http.Request) {
ctx := req2ctx(r)
cdb := complaintdb.NewDB(ctx)
cdb.AddDailyCount(complaintdb.DailyCount{
Datestring: "2016.06.22",
NumComplaints: 6555,
NumComplainers: 630,
})
w.Header().Set("Content-Type", "text/plain")
w.Write([]byte("OK!\n"))
}