Пример #1
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>")
	}
}
Пример #2
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>")
}