Example #1
0
func Housing(w http.ResponseWriter, r *http.Request, app app.App) {

	w.Header().Set("Content-Type", "text/html")
	fmt.Fprintf(w, `<html><head>
    <style>
        body {
            background-color: cyan
        }
        .okay {
            background-color: grey
        }
        .bad {
            background-color: red
        }
        .good {
            background-color: green
        }
    </style>
    </head><body>`)
	/*

	   showParsed, _ := strconv.Atoi(r.URL.Query().Get("showParsed"));
	   if (showParsed != 0 && showParsed != 1) { showParsed = 0; }

	   //countU, err := db.Find(bson.M{"parsed": showParsed}).Count()
	   countT, err := db.Find(bson.M{}).Count()
	   if (err != nil) {
	       log.Fatal(err)
	   }

	   fmt.Fprintf(w, "In db: %d total,<br />", countT)
	*/
	count, _ := strconv.Atoi(r.URL.Query().Get("count"))
	if count == 0 {
		count = 50
	}
	skip, _ := strconv.Atoi(r.URL.Query().Get("skip"))
	if skip < 0 || skip > 100 {
		skip = 0
	}

	qq := app.Env().Db.Find(bson.M{"version": app.Env().Version}).Sort("tm") /*.Select(bson.M{"resource": 1, "link" : 1}).Sort*/

	iter := qq.Iter()
	i := 0
	rec := schema.Record{}
	log.Printf("Skipping %d entries", count*skip)
	if skip > 0 {
		for iter.Next(&rec) {
			i++
			if i >= count*skip {
				break
			}
		}
	}

	ix := 0
	for iter.Next(&rec) {
		ix++
		id := b64.StdEncoding.EncodeToString([]byte(string(rec.Resource)))
		links := ""
		//i, _ := strconv.ParseInt(rec.Tm, 10, 64)
		//tm := time.Unix(i, 0)
		class := "okay"
		//datetime := tm;// + ";"

		if rec.Parsed == 0 {
			links = fmt.Sprintf(`<a href="/review?id=%s" target="_blank">Review description</a>`, id)
		}
		if rec.Parsed == 1 || rec.Parsed == 2 {
			if rec.Parsed != 2 {
				links = fmt.Sprintf(`<a href="/report?id=%s" target="_blank">report to Slack</a></p>`, id)
			}
			meta := schema.MetaRecord{}
			json.Unmarshal([]byte(rec.Meta), &meta)

			if meta.Good == false {
				class = "bad"
			} else {
				class = "good"
			}

			if rec.Parsed == 2 {
				//tm = tm + rec.ReviewTime
			}

		}
		fmt.Fprintf(w, `<p>
                        <div class="%s">
                            <p>#%d Resource ID: <a href="%v">%v</a> (%s)</p>
                            <p>Meta (can be either from parser or from review): <i>%v</i></p>
                            <p>Item status : %d;
                            %s
                        </div>
                        </p><br />`, class, 0 /*(i + ix)*/, rec.Link, 0 /* datetimes*/, rec.Resource, html.EscapeString(rec.Meta), rec.Parsed, links)

		if ix >= count {
			break
		}
	}

	nSkip := skip - 1
	if nSkip < 0 {
		nSkip = 0
	}
	fmt.Fprintf(w, `<br /><div><a href='/?skip=%d&count=%d'>prev</a>;
                    <a href='/?skip=%d&count=%d'>next</a></div>`, nSkip, count, skip+1, count)
	fmt.Fprintf(w, "</body></html>")
}
Example #2
0
func Review(w http.ResponseWriter, r *http.Request, a app.App) {

	bar, _ := strconv.Atoi(r.URL.Query().Get("save"))
	foo, _ := b64.StdEncoding.DecodeString(r.URL.Query().Get("id"))

	id := string(foo)

	qq := a.Env().Db.Find(bson.M{"resource": id})
	cnt, _ := qq.Count()
	rec := schema.Record{}
	qq.Iter().Next(&rec)
	if cnt != 1 || !((rec.Parsed == 0 && bar == 0) || (rec.Parsed == 0 && bar == 1)) {
		fmt.Fprintf(w, "Wrong flat id or parsed state provided: %d, %d", cnt, rec.Parsed)
		return
	}

	fmt.Fprintf(w, `<html><head>
            <script>
                window.onunload = refreshParent;
                function refreshParent() {
                    window.opener.location.reload();
                }
                function continueExecution() {
                    window.close();
                   
                }
                function closeSelf(f) {
                    f.submit();
                    setTimeout(continueExecution, 1000);
                }                
            </script>
            </head><body>`)
	if bar == 1 {
		oldmeta := schema.WWWRecord{}
		err := json.Unmarshal([]byte(rec.Meta), &oldmeta)
		if err != nil {
			log.Panic(err)
		}

		meta := schema.MetaRecord{}

		meta.SavedHTMLName = oldmeta.SavedHTMLName
		meta.ScreenshotName = oldmeta.ScreenshotName
		meta.SlackTS = oldmeta.SlackTS
		meta.SlackCN = oldmeta.SlackCN
		meta.ReviewTime = time.Now().Format("Jan 2, 2006 at 3:04pm (MST)")

		if len(meta.SlackCN) < 3 {
			log.Panic("no meta")
		}

		meta.TimeToOffice = r.URL.Query().Get("tto")
		meta.Rent = r.URL.Query().Get("rent")
		meta.Address = r.URL.Query().Get("address")
		meta.Good = (r.URL.Query().Get("valid") == "true")

		b, _ := json.Marshal(meta)

		rec.Meta = string(b)
		rec.Parsed = 1
		fmt.Printf("Debug: stored time '%s'\n", rec.Tm)

		//		app.Env().Db.Update(bson.M{"resource": id}, rec)

		fmt.Fprintf(w, "<script>window.close();</script></body></html>")
	} else {
		w.Header().Set("Content-Type", "text/html")
		meta := schema.WWWRecord{}
		json.Unmarshal([]byte(rec.Meta), &meta)

		fmt.Fprintf(w, `(object screenshot and editor for <a href="%v">%v</a> go here)<br />
            Found at time: `+rec.Tm+`<br />
            Meta raw: <i>`+html.EscapeString(rec.Meta)+`</i><br />
            <FORM METHOD="GET" ACTION="/review" onsubmit="closeSelf(this);">
                <input type="hidden" name="save" value="1" />
                <input type="hidden" name="id" value="`+r.URL.Query().Get("id")+`" />
                TimeToOffice minutes: <input type="text" name="tto" /><br />
                Rent (kr): <input type="text" name="rent" /><br />
                Address: <input type="text" name="address" /><br />
                Valid content (no daily rent, weekly rent, Gothia cup/Summer specials): <input type="checkbox" name="valid" value="true" />
                <br /><hr /><input type="submit" value="SEND" />
            </FORM><hr /><br /><br /><img src="file/`+meta.ScreenshotName+`"/>
            `, rec.Link, rec.Link)

		fmt.Fprintf(w, "</body></html>")
	}
}
Example #3
0
func Report(w http.ResponseWriter, r *http.Request, app app.App) {
	fmt.Fprintf(w, `<html><head>
            <script>
                window.onunload = refreshParent;
                function refreshParent() {
                    window.opener.location.reload();
                }
            </script>
            </head><body>`)

	foo, _ := b64.StdEncoding.DecodeString(r.URL.Query().Get("id"))
	id := string(foo)

	rec := schema.Record{}
	meta := schema.MetaRecord{}

	qq := app.Env().Db.Find(bson.M{"resource": id})
	cnt, _ := qq.Count()
	if cnt != 1 {
		fmt.Fprintf(w, "Error reporting flat: flat not found")
		return
	}

	qq.Iter().Next(&rec)

	if rec.Parsed != 1 {
		fmt.Fprintf(w, "Bad state")
		return
	}

	json.Unmarshal([]byte(rec.Meta), &meta)

	meta.Address = html.EscapeString(meta.Address)
	meta.TimeToOffice = html.EscapeString(meta.TimeToOffice)
	meta.Rent = html.EscapeString(meta.Rent)

	fmt.Fprintf(w, "Object found, link: %s<br />encoded meta: %s<br />found at %s, status: %d<hr />", rec.Link, rec.Meta, rec.Tm, rec.Parsed)

	color := "good"
	if meta.Good == false {
		color = "danger"
	}

	fmt.Printf("Time: '%s'\n", rec.Tm)
	i, err := strconv.ParseInt(rec.Tm, 10, 64)
	if err != nil {
		panic(err)
	}
	tm := time.Unix(i, 0).Format("Jan 2, 2006 at 3:04pm (MST)")
	fmt.Printf("Time: -> '%s'\n", tm)
	var jsonStr = `[
                {
                    "pretext": "Flat info",                  
                    "fallback": "hyra-bot stuff",

                    "color": "` + color + `",

                    "author_name": "blocket",
                    "author_link": "` + rec.Link + `",
                    "author_icon": "http://m.img.brothersoft.com/android/455/1352509189_icon.png",

                    "title": "` + meta.Address + `",
                    "title_link": "` + rec.Link + `",

                    "text": "Record found at ` + tm + `, parsed at ` + meta.ReviewTime + `",

                    "fields": [
                        {
                            "title": "Rent",
                            "value": "` + meta.Rent + `",
                            "short": true
                        },
                        {
                            "title": "TimeToOffice",
                            "value": "` + meta.TimeToOffice + `",
                            "short": true
                        }
                    ],

                    "image_url": "http://my-website.com/path/to/image.jpg",
                    "thumb_url": "http://example.com/path/to/thumb.png"
                }
            ]`

	if len(app.Env().AppConfig.SlackAPIKey) < 1 {
		log.Panic("No key")
	}

	s := string("https://slack.com/api/chat.postMessage") // chat.update.. but I don't support that due to perms
	data := url.Values{}

	data.Set("token", app.Env().AppConfig.SlackAPIKey)
	data.Set("text", "Another rent ad")
	data.Set("channel", app.Env().AppConfig.Chan_pt)
	data.Set("attachments", jsonStr)

	st := data.Encode()
	log.Printf("req> %s", st)
	req, err := http.NewRequest("POST", s, bytes.NewBufferString(st))
	req.Header.Set("Content-Type", "application/json")

	client := &http.Client{}
	resp, err := client.Get(fmt.Sprintf("%s?%s", s, bytes.NewBufferString(data.Encode())))
	if err != nil {
		panic(err)
	}

	var sla schema.SlackResponse
	var buf bytes.Buffer
	buf.ReadFrom(resp.Body)
	err = json.Unmarshal([]byte(buf.Bytes()), &sla)

	if err != nil {
		log.Panic(resp.Body)
	}
	if sla.Ok == false {
		log.Panic("not ok: ", string(buf.Bytes()))
	}

	log.Printf(jsonStr)
	defer resp.Body.Close()

	fmt.Println("response Status:", resp.Status)
	if resp.Status != "500 Server Error" {
		rec.Parsed = 2
		app.Env().Db.Update(bson.M{"resource": id, "parsed": 1}, rec)
		fmt.Fprintf(w, `<br />You can close this now
            <script>
                window.onunload = refreshParent;
                function refreshParent() {
                    window.opener.location.reload();
                };
                window.close()</script>
                `)
	} else {
		fmt.Fprintf(w, `error happened
                <script>
                window.onunload = refreshParent;
                function refreshParent() {
                    window.opener.location.reload();
                };
                window.close()</script>`)
	}
	fmt.Println("response Headers:", resp.Header)
	fmt.Println("response Body:", string(buf.Bytes()))

	fmt.Fprintf(w, "</body></html>")
}