Exemple #1
0
func ServiceHandlers_ChatGetMessages(request *restful.Request, response *restful.Response) {

	// Input
	//UserId := request.PathParameter("UserId")
	//LastMessageId := request.PathParameter("LastMessageId")

	// Search
	context := appengine.NewContext(request.Request)
	querySize1 := 100

	query1 := datastore.NewQuery("Chat").Order("When").Limit(querySize1)
	queryResult1 := make([]Chat, 0, querySize1)
	query1.GetAll(context, &queryResult1)

	querySize2 := 5000
	query2 := datastore.NewQuery("User").Limit(querySize2)
	queryResult2 := make([]User, 0, querySize2)
	query2.GetAll(context, &queryResult2)

	m := make(map[string]string)
	for i := 0; i < len(queryResult2); i++ {
		m[queryResult2[i].Id] = queryResult2[i].Name
	}

	for j := 0; j < len(queryResult1); j++ {
		queryResult1[j].OwnerId = m[queryResult1[j].OwnerId]
		queryResult1[j].WhenAsString = queryResult1[j].When.Format("2006/01/02 03:04:05")
	}

	// Output
	bytes, _ := json.Marshal(queryResult1)
	response.Write(bytes)
}
Exemple #2
0
func cleanImage(w http.ResponseWriter, r *http.Request) {
	// Con esta manejador borramos las imagenes que no están asociadas a
	// ningún punto y han quedado huerfanas

	c := appengine.NewContext(r)

	var blobs []blobstore.BlobInfo

	q := datastore.NewQuery("__BlobInfo__")
	keys, _ := q.GetAll(c, &blobs)
	for _, key := range keys {

		var imgk = appengine.BlobKey(key.StringID())

		// Busco algun punto con esa key como imagen
		var points []points.Point
		qp := datastore.NewQuery("points").Filter("ImageKey = ", imgk)
		qp.GetAll(c, &points)
		if len(points) == 0 {
			// borro la imagen
			c.Infof("borro imagen %s", imgk)
			err := blobstore.Delete(c, imgk)
			if err != nil {
				app.ServeError(c, w, err)
				return
			}
		}
	}
}
Exemple #3
0
func ServiceHandlers_LoadBorrow(request *restful.Request, response *restful.Response) {

	// Input
	//UserId := request.PathParameter("UserId")

	context := appengine.NewContext(request.Request)
	querySize := 5000

	// Search 1
	query1 := datastore.NewQuery("Borrow").Limit(querySize)
	queryResult1 := make([]Borrow, 0, querySize)
	query1.GetAll(context, &queryResult1)

	// Search 2
	query2 := datastore.NewQuery("BorrowWant").Limit(querySize)
	queryResult2 := make([]BorrowWant, 0, querySize)
	query2.GetAll(context, &queryResult2)

	// Update
	m := make(map[string]int)
	for i := 0; i < len(queryResult2); i++ {
		m[queryResult2[i].ItemId] = m[queryResult2[i].ItemId] + 1
	}

	for j := 0; j < len(queryResult1); j++ {
		queryResult1[j].WantCount = m[queryResult1[j].Id]
	}

	bytes, _ := json.Marshal(queryResult1)

	response.Write(bytes)
}
Exemple #4
0
func DeleteTweetsByHashtag(c appengine.Context, hashtag string) error {
	c.Debugf("DeleteTweetsByHashtag")
	q := datastore.NewQuery("Tweet").Filter("Hashtag =", hashtag).Order("Created_At").Limit(300)
	var tweets []Tweet
	keys, err := q.GetAll(c, &tweets)
	if err != nil {
		c.Errorf("DeleteTweetsByHashtag failed to get: %v", err)
		return err
	}
	c.Debugf("DeleteTweetsByHashtag keys for delete: %v", keys)
	for _, tweet := range tweets {
		c.Infof("DeleteTweetsByHashtag tweet for delete: %v", tweet.Text)
	}
	if err = datastore.DeleteMulti(c, keys); err != nil {
		c.Errorf("DeleteTweetsByHashtag failed to delete tweet: %v", err)
		return err
	}

	//tweetを削除した結果、tweetが無かったら、Hashtagを削除する
	length, err := datastore.NewQuery("Tweet").Filter("Hashtag =", hashtag).Count(c)
	if err != nil {
		c.Errorf("DeleteTweetsByHashtag failed to get count: %v", err)
		return err
	}
	c.Debugf("DeleteTweetsByHashtag tweets length: %d", length)
	if length == 0 {
		c.Infof("DeleteTweetsByHashtag delete Hashtag: %s", hashtag)
		if err := DeleteHashtag(c, hashtag); err != nil {
			c.Errorf("DeleteTweetsByHashtag failed to delete hashtag: %v", err)
			return err
		}
	}
	return nil
}
Exemple #5
0
func See(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	q := datastore.NewQuery("Pay").Order("-Date").Limit(100)
	k := make([]Pay, 0, 100)
	_, err1 := q.GetAll(c, &k)
	//fmt.Fprintf(w,len(k))
	if err1 != nil {
		http.Error(w, err1.Error(), http.StatusInternalServerError)
		return
	}
	if err := SeePTemplate.Execute(w, k); err != nil {
		http.Error(w, err1.Error(), http.StatusInternalServerError)
	}
	q2 := datastore.NewQuery("Trans").Limit(100)
	l := make([]Trans, 0, 100)
	_, err2 := q2.GetAll(c, &l)
	//fmt.Fprintf(w,len(l))
	if err2 != nil {
		http.Error(w, err2.Error(), http.StatusInternalServerError)
		return
	}
	if err := SeeTTemplate.Execute(w, l); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
}
Exemple #6
0
func handleIndex(w http.ResponseWriter, r *http.Request) {
    c := appengine.NewContext(r)

    // Get user info
    userInfo := getUserInfo(c)

    // Get post id and page id
    pageId, _ := strconv.Atoi(getUrlQuery(r.URL, "pid"))
    pageSize  := config.PageSize

    // Get offset and page numbers
    offset, pageNums := getOffset("Article", pageId, pageSize, c)

    // New PageSetting
    pageSetting := new(PageSetting)

    // Setting PageSetting
    pageSetting.Title       = config.Title
    pageSetting.Description = config.Description
    pageSetting.Layout      = "column2"
    pageSetting.ShowSidebar = true

    // showNext and showPrev button
    if pageId <= 0 || pageId > pageNums {
        pageId = 1
    }
    if pageId < pageNums {
        pageSetting.ShowPrev = true
    }
    if pageId != 1 {
        pageSetting.ShowNext = true
    }
    pageSetting.PrevPageID = pageId + 1
    pageSetting.NextPageID = pageId - 1

    // Get article data
    dbQuery          := datastore.NewQuery("Article").Order("-Date").Offset(offset).Limit(pageSize)
    articleData, err := getArticleData(dbQuery, true, c)
    if err != nil {
        serveError(c, w, err)
        return
    }

    // Get widget data
    dbQuery          = datastore.NewQuery("Widget").Order("Sequence")
    widgetData, err := getWidgetData(dbQuery, true, c)
    if err != nil {
        serveError(c, w, err)
        return
    }

    // New PageData
    pageData := &PageData{ User: userInfo, Article: articleData, Widget: widgetData }

    // New Page
    page := NewPage(pageSetting, pageData)

    // Render page
    page.Render("index", w)
}
Exemple #7
0
func addTagToFact(c appengine.Context, factKey *datastore.Key, tag string) {
	q := datastore.NewQuery("Tag").Filter("Name =", tag)
	cnt, _ := q.Count(c)
	var existingTag Tag
	var existingTagKey *datastore.Key
	if cnt > 0 {
		// retrieve
		for t := q.Run(c); ; {
			existingTagKey, _ = t.Next(&existingTag)
			break // only need one
		}
	} else {
		// create a new one
		var t = Tag{Name: tag}
		existingTagKey, _ = datastore.Put(c, datastore.NewIncompleteKey(c, "Tag", nil), &t)
	}
	qft := datastore.NewQuery("FactTag").
		Filter("Fact = ", factKey).
		Filter("Tag = ", existingTagKey)
	cnt2, _ := qft.Count(c)
	if cnt2 == 0 {
		// create a new one
		var ft = FactTag{Fact: factKey, Tag: existingTagKey}
		_, _ = datastore.Put(c, datastore.NewIncompleteKey(c, "FactTag", nil), &ft)
	}
}
Exemple #8
0
// Get returns an User by id, name or SocialAccount.Name
func (dsum *DataStoreUserManager) Get(id string) (u *User, err error) {
	u = &User{}
	intid, err := strconv.ParseInt(id, 10, 64)
	if err == nil && intid != 0 {
		u, err = dsum.getById(intid)
		if err != datastore.ErrNoSuchEntity {
			return
		}
	}
	q := datastore.NewQuery("User").Filter("Name =", id)
	t := q.Run(dsum.c)
	_, err = t.Next(u)
	if err != datastore.Done {
		return
	}
	q = datastore.NewQuery("User").Filter("Email =", id)
	t = q.Run(dsum.c)
	_, err = t.Next(u)
	if err != datastore.Done {
		return
	}
	q = datastore.NewQuery("User").Filter("Accounts.Name =", id)
	t = q.Run(dsum.c)
	_, err = t.Next(u)
	if err != datastore.Done {
		return
	}
	return nil, datastore.ErrNoSuchEntity
}
Exemple #9
0
func DeleteOldFeed(c mpg.Context, w http.ResponseWriter, r *http.Request) {
	g := goon.FromContext(c)
	oldDate := time.Now().Add(-time.Hour * 24 * 90)
	feed := Feed{Url: r.FormValue("f")}
	if err := g.Get(&feed); err != nil {
		c.Criticalf("err: %v", err)
		return
	}
	if feed.LastViewed.After(oldDate) {
		return
	}
	q := datastore.NewQuery(g.Kind(&Story{})).Ancestor(g.Key(&feed)).KeysOnly()
	keys, err := q.GetAll(c, nil)
	if err != nil {
		c.Criticalf("err: %v", err)
		return
	}
	q = datastore.NewQuery(g.Kind(&StoryContent{})).Ancestor(g.Key(&feed)).KeysOnly()
	sckeys, err := q.GetAll(c, nil)
	if err != nil {
		c.Criticalf("err: %v", err)
		return
	}
	keys = append(keys, sckeys...)
	c.Infof("delete: %v - %v", feed.Url, len(keys))
	err = g.DeleteMulti(keys)
	if err != nil {
		c.Criticalf("err: %v", err)
	}
}
Exemple #10
0
// Show the front page
func RootHandler(c appengine.Context, w http.ResponseWriter, r *http.Request) {
	p := setup(c, r)

	var items []Item
	q := datastore.NewQuery("Item").Order("-Score")
	keys, err := q.GetAll(c, &items)
	check(err, "Could not load items.")

	var votes []Vote
	q = datastore.NewQuery("Vote").Filter("OwnerKey=", p.User.userKey).Filter("ParentType=", "Item")
	q.GetAll(c, &votes) // Eat the error, we don't care if we can't load votes

	var vote Vote

	for i, key := range keys {
		items[i].itemKey = key
		items[i].loadOwner(c)
		if len(votes) > 0 {
			for _, vote = range votes {
				if items[i].itemKey.IntID() == vote.ParentKey.IntID() {
					items[i].SessionUserVote = vote.Value
				}
			}
		}
	}

	p.Data["Items"] = items

	renderTemplate(w, "index.html", p)
}
Exemple #11
0
func computeRank(c appengine.Context, userId int64, examId int64) ([]Rank, error) {
	score := make([]Rank, 0, 0)
	q := datastore.NewQuery("ExamResult")
	for t := q.Run(c); ; {
		var e ExamResult
		_, err := t.Next(&e)
		if err == datastore.Done {
			break
		}
		if err != nil {
			return score, err
		}
		if (userId == -1 || e.UserId == userId) && (examId == -1 || e.ExamId == examId) {
			err, s := getExamResultScore(c, e)
			if err != nil {
				return score, err
			}
			var userName, examName string
			var userProf []UserProfile
			var exam []Exam
			q := datastore.NewQuery("UserProfile").Filter("UserId =", e.UserId)
			if _, err := q.GetAll(c, &userProf); err == nil && len(userProf) > 0 {
				userName = userProf[0].FirstName + " " + userProf[0].LastName
			}
			q2 := datastore.NewQuery("Exam").Filter("Id =", e.ExamId)
			if _, err := q2.GetAll(c, &exam); err == nil && len(exam) > 0 {
				examName = exam[0].Name
			}
			score = append(score, Rank{e.ExamId, examName, e.UserId, userName, s})
		}
	}
	return score, nil
}
Exemple #12
0
func Clean(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	q := datastore.NewQuery("User").Limit(100)
	x := make([]User, 0, 100)
	k, err := q.GetAll(c, &x)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	datastore.DeleteMulti(c, k)
	q2 := datastore.NewQuery("Pay").Limit(100)
	x2 := make([]Pay, 0, 100)
	k2, err2 := q2.GetAll(c, &x2)
	if err2 != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	datastore.DeleteMulti(c, k2)
	q3 := datastore.NewQuery("Trans").Limit(100)
	x3 := make([]Trans, 0, 100)
	k3, err3 := q3.GetAll(c, &x3)
	if err3 != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	datastore.DeleteMulti(c, k3)

	http.Redirect(w, r, "/admin", http.StatusFound)
}
Exemple #13
0
func (session *Session) DatastoreInfo() (err error) {
	c, err := session.AppEngineContext()
	if err != nil {
		log.Fatalf("Failed to create context: %v", err)
		return
	}
	log.Printf("App ID %q", appengine.AppID(c))

	q := datastore.NewQuery(DatastoreKindName).Order("kind_name")
	kinds := []*DatastoreKind{}
	if _, err := q.GetAll(c, &kinds); err != nil {
		log.Fatalf("Failed to fetch kind info: %v", err)
	}

	for _, k := range kinds {
		fmt.Printf("\nkind %q\t%d entries\t%d bytes\n", k.KindName, k.Count, k.Bytes)
		if false {
			props := datastore.PropertyList{}
			if _, err := datastore.NewQuery(k.KindName).Limit(1).Run(c).Next(&props); err != nil {
				log.Printf("Unable to fetch sample entity kind %q: %v", k.KindName, err)
				continue
			}
			for _, prop := range props {
				fmt.Printf("\t%s: %v\n", prop.Name, prop.Value)
			}
		}
	}
	return
}
Exemple #14
0
func AdminUser(c mpg.Context, w http.ResponseWriter, r *http.Request) {
	gn := goon.FromContext(c)
	q := datastore.NewQuery(gn.Key(&User{}).Kind()).Limit(1)
	q = q.Filter("e =", r.FormValue("u"))
	it := gn.Run(q)
	var u User
	ud := UserData{Id: "data"}
	var h []Log
	k, err := it.Next(&u)
	if err == nil {
		q = datastore.NewQuery(gn.Key(&Log{}).Kind()).Ancestor(k)
		_, err = gn.GetAll(q, &h)
		ud.Parent = gn.Key(&u)
		gn.Get(&ud)
	}
	if err := templates.ExecuteTemplate(w, "admin-user.html", struct {
		User  User
		Data  UserData
		Log   []Log
		Error error
	}{
		u,
		ud,
		h,
		err,
	}); err != nil {
		serveError(w, err)
	}
}
Exemple #15
0
func (p *Puzzle) UpdatableProgressInfo(c appengine.Context, h *hunt.Hunt, t *team.Team) UpdatableProgressInfo {
	u := UpdatableProgressInfo{
		AvailablePoints: p.PointValue,
		Solved:          false,
		GrantedPoints:   0,
		SolveTimes:      nil,
		Answerable:      t != nil && !t.Key.Equal(p.Team),
	}
	if t != nil {
		var solves []Solve
		_, err := datastore.NewQuery(solveKind).Ancestor(h.Key).Filter("Puzzle =", p.Key).Filter("Team =", t.Key).Limit(1).GetAll(c, &solves)
		if err != nil {
			c.Errorf("Error: %v", err)
		}
		if len(solves) > 0 {
			u.Solved = true
			u.GrantedPoints = solves[0].Points
			u.Answerable = false
		}
	}
	var solves []Solve
	_, err := datastore.NewQuery(solveKind).Ancestor(h.Key).Filter("Puzzle =", p.Key).Order("Time").GetAll(c, &solves)
	if err != nil {
		c.Errorf("Error: %v", err)
	}
	for _, s := range solves {
		u.SolveTimes = append(u.SolveTimes, s.Time.In(h.GetTimezone(c)).Format("15:04:05"))
	}
	return u
}
func admin(w http.ResponseWriter, r *http.Request) {
	// handle requests to "/admin/"
	c := appengine.NewContext(r)
	billQuery := datastore.NewQuery("Bill").Order("-Session").Order("-Number")
	bills := make([]bill.Bill, 0)
	if _, err := billQuery.GetAll(c, &bills); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	senatorQuery := datastore.NewQuery("Senator").Order("-Name")
	senators := make([]senator.Senator, 0)
	if _, err := senatorQuery.GetAll(c, &senators); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	login, _ := user.LoginURL(c, "/")
	logout, _ := user.LogoutURL(c, "/")
	pageInfo := PageInfo{Title: "Administrator Dashboard",
		User:      user.Current(c),
		Admin:     user.IsAdmin(c),
		LoginURL:  login,
		LogoutURL: logout,
		Bills:     bills,
		Senators:  senators}
	if err := adminTemplate.Execute(w, pageInfo); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
}
Exemple #17
0
func getQuery(r *http.Request, postID int64, numToRender int, queryType string) ([]*datatypes.Post, error) {
	c := appengine.NewContext(r)
	q := datastore.NewQuery(queryType)
	if postID > -1 {
		// According to https://developers.google.com/appengine/docs/go/datastore/queries#Go_Filters,
		// Query.Filter("__key__="...) matches keys in order of
		// 1. Ancestor path
		// 2. Entity kind
		// 3 Identifier (key name or numeric ID)
		// So by making a new key with the same type and ancestor path (no ancestors) and with the same postID, the two can be matched and returned from the query.
		// There has got to be a better way to do this, and this might be a waste of a key, but since uses the same ID, maybe it doesn't matter.
		q = datastore.NewQuery(queryType).Filter("__key__=", datastore.NewKey(c, queryType, "", postID, nil)).Order("-GoDate")
	} else if numToRender != -1 {
		q = datastore.NewQuery(queryType).Order("-GoDate").Limit(numToRender)
	}

	var allPosts []*datatypes.Post
	keys, err := q.GetAll(c, &allPosts)
	if err != nil {
		return nil, err
	}

	for i := range allPosts {
		allPosts[i].ID = keys[i].IntID()
	}
	sort.Sort(sort.Reverse(datatypes.Posts(allPosts)))

	return allPosts, nil
}
Exemple #18
0
/*
This call deletes and creates unit-testing data.
*/
func (h *System) CreateTestData(r *http.Request, args *SystemArgs, reply *GeneralReply) error {
	c := appengine.NewContext(r)
	var err error

	// delete any previous testing data
	{
		var keys_to_delete []*datastore.Key

		REGION_UIDS_TO_DELETE := []string{"@test-san-francisco", "@test-los-angeles"}
		RESTAURANT_UIDS_TO_DELETE := []string{"@test-mcdonalds", "@test-In-N-Out", "@test-Wendys"}
		TAGS_UIDS_TO_DELETE := []string{"@test-american", "@test-french"}

		for _, uid := range REGION_UIDS_TO_DELETE {
			q := datastore.NewQuery("Tags").Filter("Uid =", uid).KeysOnly()
			keys_to_delete, err = q.GetAll(c, nil)
			checkErr(err, "DB error1")
			err = datastore.DeleteMulti(c, keys_to_delete)
			checkErr(err, "DB error2")
		}
		for _, uid := range RESTAURANT_UIDS_TO_DELETE {
			q := datastore.NewQuery("Region").Filter("Uid =", uid).KeysOnly()
			keys_to_delete, err = q.GetAll(c, nil)
			checkErr(err, "DB error3")
			err = datastore.DeleteMulti(c, keys_to_delete)
			checkErr(err, "DB error4")
		}

		for _, uid := range TAGS_UIDS_TO_DELETE {
			q := datastore.NewQuery("Restaurant").Filter("Uid =", uid).KeysOnly()
			_, err = q.GetAll(c, &keys_to_delete)
			checkErr(err, "DB error5")
			err = datastore.DeleteMulti(c, keys_to_delete)
			checkErr(err, "DB error6")
		}
		log.Printf("... cleanup done")
	}

	// re-create the data (unless this was a cleanup operation only)
	if !args.CleanupOnly {
		region1 := models.Region{Uid: "@test-san-francisco", Title: "TEST San Francisco"}
		_, err = datastore.Put(c, datastore.NewKey(c, "Region", region1.Uid, 0, nil), &region1)
		checkErr(err, "fail trying to insert")
		region2 := models.Region{Uid: "@test-los-angeles", Title: "TEST Los Angeles"}
		_, err = datastore.Put(c, datastore.NewKey(c, "Region", region2.Uid, 0, nil), &region2)
		checkErr(err, "fail trying to insert")

		restaurant1 := models.Restaurant{Uid: "@test-mcdonalds", Title: "TEST McDonalds", Tags: []string{"French Cuisine", "American"}, Regions: []string{region1.Uid}}
		_, err = datastore.Put(c, datastore.NewKey(c, "Restaurant", restaurant1.Uid, 0, nil), &restaurant1)
		checkErr(err, "fail trying to insert")
		restaurant2 := models.Restaurant{Uid: "@test-In-N-Out", Tags: []string{"American"}, Regions: []string{region1.Uid, region2.Uid}}
		_, err = datastore.Put(c, datastore.NewKey(c, "Restaurant", restaurant2.Uid, 0, nil), &restaurant2)
		checkErr(err, "fail trying to insert")
		restaurant3 := models.Restaurant{Uid: "@test-Wendys", Tags: []string{"American"}, Regions: []string{region2.Uid}}
		_, err = datastore.Put(c, datastore.NewKey(c, "Restaurant", restaurant3.Uid, 0, nil), &restaurant3)
		checkErr(err, "fail trying to insert")

		log.Printf("... creation done")
	}
	return nil
}
Exemple #19
0
func DiscoverHandler(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	vineApi := VineRequest{c}
	db := DB{c}
	var recentUsers []*VineUser
	var recentVerified []StoredUserMeta

	recent := datastore.NewQuery("Queue").Order("-Discovered").Limit(5).KeysOnly()
	k, _ := recent.GetAll(c, nil)
	for i, _ := range k {
		user, err := vineApi.GetUser(strconv.FormatInt(k[i].IntID(), 10))
		if err == nil {
			recentUsers = append(recentUsers, user)
		}
	}
	verified := datastore.NewQuery("UserMeta").Filter("Verified =", true).Limit(5).KeysOnly()
	k, _ = verified.GetAll(c, nil)
	for i, _ := range k {
		user, err := db.GetUserMeta(k[i].IntID())
		if err == nil {
			recentVerified = append(recentVerified, user.(StoredUserMeta))
		}
	}
	data := map[string]interface{}{"recentUsers": recentUsers, "recentVerified": recentVerified}
	dir := path.Join(os.Getenv("PWD"), "templates")
	discover := path.Join(dir, "discover.html")
	layout := path.Join(dir, "pageLayout.html")
	page := mustache.RenderFileInLayout(discover, layout, data)
	fmt.Fprint(w, page)
}
Exemple #20
0
func watashi(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	ks, err := datastore.NewQuery("feed").KeysOnly().GetAll(c, nil)
	if err != nil {
		handleError(w, err)
		return
	}
	for _, k := range ks {
		err = subscribe(c, k, false)
		if err != nil {
			handleError(w, err)
			return
		}
	}
	ks, err = datastore.NewQuery("item").Filter("Read =", false).KeysOnly().GetAll(c, nil)
	if err != nil {
		handleError(w, err)
		return
	}
	for _, k := range ks {
		propagate.Call(c, k)
		fmt.Fprintln(w, k)
	}
	fmt.Fprintln(w, "OK!")
}
Exemple #21
0
func Refresh(w http.ResponseWriter, r *http.Request) {
	if extendMethod(r) == "GET" {
		var account Account
		q := datastore.NewQuery("Account")
		for t := q.Run(c); ; {
			_, err := t.Next(&account)
			if err == datastore.Done {
				break
			}
			if account.Verified() {
				if account.Version() == 2 {
					account.prepareOAuth2Connection(r)
				}
				switch account.Name {
				case "github":
					account.GetGithubUpdates(r)
				case "linkedin":
					account.GetLinkedInUpdates(r)
				case "twitter":
					account.GetTwitterUpdates(r)
				case "xing":
					account.GetXingUpdates(r)
				}
			}
		}
		q = datastore.NewQuery("Status").Order("-Created").Offset(100).KeysOnly()
		keys, err := q.GetAll(c, nil)
		if err == nil && len(keys) > 0 {
			datastore.DeleteMulti(c, keys)
		}
	}
	pageTemplate, _ := template.ParseFiles("templates/manage/refresh.txt")
	w.Header().Set("Content-Type", "text/plain; charset=utf-8")
	pageTemplate.Execute(w, map[string]interface{}{"notice": session.Flashes()})
}
Exemple #22
0
func showGrid(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	parts := strings.Split(r.URL.String(), "/")
	if len(parts) < 3 {
		http.Error(w, "bad request", 404)
		return
	}
	gridkey := parts[2]
	k, g, err := getGrid(c, gridkey)

	if err != nil {
		http.Error(w, "Couldn't load Grid", http.StatusInternalServerError)
		c.Errorf("setting up: %v", err)
		c.Errorf("key: %v", parts)
		return
	}

	rowmap := make(map[string]Row)
	rq := datastore.NewQuery("row").Filter("Grid=", k).Order("DisplayOrder")
	rows := make([]Row, 0, 100)
	rkeys, err := rq.GetAll(c, &rows)
	if err != nil {
		// handle the error
		c.Errorf("rows fetch: %v", err)
	}
	for i, rk := range rkeys {
		rowmap[rk.String()] = rows[i]
	}

	colmap := make(map[string]Col)
	cq := datastore.NewQuery("col").Filter("Grid=", k).Order("DisplayOrder")
	cols := make([]Col, 0, 100)
	ckeys, err := cq.GetAll(c, &cols)
	if err != nil {
		// handle the error
		c.Errorf("cols fetch: %v", err)
	}
	for i, ck := range ckeys {
		colmap[ck.String()] = cols[i]
	}

	cellq := datastore.NewQuery("cell").Filter("Grid=", k).Limit(100 * 100)
	cells := make([]Cell, 0, 100*100)
	vcells := make([]vcell, 0, 100*100)

	if _, err := cellq.GetAll(c, &cells); err != nil {
		c.Errorf("cells fetch: %v", err)
	}

	for _, cell := range cells {
		var fr = rowmap[cell.Row.String()]
		var fc = colmap[cell.Col.String()]
		vcells = append(vcells, vcell{cell, fr, fc, fr.DisplayOrder, fc.DisplayOrder})
	}

	err = gridTemplate.Execute(w, gridPage{g, gridkey, rows, cols, vcells})
	if err != nil {
		c.Errorf("gridTemplate: %v", err)
	}
}
Exemple #23
0
func getArticleTags(c appengine.Context, articleID string) (map[int]string, os.Error) {
	q := datastore.NewQuery("Tag").Order("+Name").Filter("ArticleID =", articleID)
	count, err := q.Count(c)
	if err != nil {
		return nil, err
	}
	tags := make([]Tag, 0, count)
	_, err = q.GetAll(c, &tags)
	if err != nil {
		return nil, err
	}

	count, err = q.Count(c)
	if err != nil {
		return nil, err
	}
	q = datastore.NewQuery("TagNames")
	tagNames := make([]TagNames, 0, count)
	_, err = q.GetAll(c, &tagNames)
	if err != nil {
		return nil, err
	}

	out := make(map[int]string)
	for i := 0; i < len(tags); i++ {
		for j := 0; j < len(tagNames); j++ {
			if tags[i].TagID == tagNames[j].TagID {
				out[tagNames[i].TagID] = tagNames[j].TagName
			}
		}
	}

	return out, err
}
Exemple #24
0
// Get the current max of userLevel and questionLevel
func GetMaxLevels(r *http.Request) (int, int) {
	c := appengine.NewContext(r)
	// Get the current max level. TODO: Det här görs för ofta.
	qn := datastore.NewQuery("Users").
		Order("-Level").
		Limit(1)

	dbUsers := make([]users.Users, 1, 1)

	_, err := qn.GetAll(c, &dbUsers)

	if err != nil {
		c.Infof("error getting users")
	}

	c.Infof("length %s", strconv.Itoa(len(dbUsers)))

	userMaxLevel := dbUsers[0].Level

	qn = datastore.NewQuery("Questions").
		Order("-Level").
		Limit(1)

	dbQuestions := make([]question.Question, 1, 1)

	_, err = qn.GetAll(c, &dbQuestions)

	if err != nil {
		c.Infof("error getting questions")
	}
	c.Infof(dbUsers[0].Name)
	questionMaxLevel := dbQuestions[0].Level

	return userMaxLevel, questionMaxLevel
}
Exemple #25
0
func GetFeed(c mpg.Context, w http.ResponseWriter, r *http.Request) {
	gn := goon.FromContext(c)
	f := Feed{Url: r.FormValue("f")}
	var stars []string
	wg := sync.WaitGroup{}
	fk := gn.Key(&f)
	q := datastore.NewQuery(gn.Kind(&Story{})).Ancestor(fk).KeysOnly()
	q = q.Order("-" + IDX_COL)
	if cur := r.FormValue("c"); cur != "" {
		if dc, err := datastore.DecodeCursor(cur); err == nil {
			q = q.Start(dc)
		}
	} else {
		// grab the stars list on the first run
		wg.Add(1)
		go c.Step("stars", func(c mpg.Context) {
			gn := goon.FromContext(c)
			usk := starKey(c, f.Url, "")
			q := datastore.NewQuery(gn.Kind(&UserStar{})).Ancestor(gn.Key(usk).Parent()).KeysOnly()
			keys, _ := gn.GetAll(q, nil)
			stars = make([]string, len(keys))
			for i, key := range keys {
				stars[i] = starID(key)
			}
			wg.Done()
		})
	}
	iter := gn.Run(q)
	var stories []*Story
	for i := 0; i < 20; i++ {
		if k, err := iter.Next(nil); err == nil {
			stories = append(stories, &Story{
				Id:     k.StringID(),
				Parent: k.Parent(),
			})
		} else if err == datastore.Done {
			break
		} else {
			serveError(w, err)
			return
		}
	}
	cursor := ""
	if ic, err := iter.Cursor(); err == nil {
		cursor = ic.String()
	}
	gn.GetMulti(&stories)
	wg.Wait()
	b, _ := json.Marshal(struct {
		Cursor  string
		Stories []*Story
		Stars   []string `json:",omitempty"`
	}{
		Cursor:  cursor,
		Stories: stories,
		Stars:   stars,
	})
	w.Write(b)
}
Exemple #26
0
func ClearAllUsersDB(c appengine.Context) {
	q := datastore.NewQuery("User")

	var us []db.User
	// To retrieve the results,
	// you must execute the Query using its GetAll or Run methods.
	ks, err := q.GetAll(c, &us)
	if err != nil {
		fmt.Fprint(os.Stderr, "DB Error Getting All Users:"+err.Error()+"!\n\n")
		log.Fatal(err)
		return
	}

	err = datastore.DeleteMulti(c, ks)
	if err != nil {
		fmt.Fprint(os.Stderr, "DB Error Deleting All Users:"+err.Error()+"!\n\n")
		log.Fatal(err)
		return
	}

	q = datastore.NewQuery("Message")

	var ms []db.Message
	// To retrieve the results,
	// you must execute the Query using its GetAll or Run methods.
	ks, err = q.GetAll(c, &ms)
	if err != nil {
		fmt.Fprint(os.Stderr, "DB Error Getting All Messages:"+err.Error()+"!\n\n")
		log.Fatal(err)
		return
	}

	err = datastore.DeleteMulti(c, ks)
	if err != nil {
		fmt.Fprint(os.Stderr, "DB Error Deleting All Messages:"+err.Error()+"!\n\n")
		log.Fatal(err)
		return
	}

	q = datastore.NewQuery("Memo")

	var mes []db.Memo
	// To retrieve the results,
	// you must execute the Query using its GetAll or Run methods.
	ks, err = q.GetAll(c, &mes)
	if err != nil {
		fmt.Fprint(os.Stderr, "DB Error Getting All Messages:"+err.Error()+"!\n\n")
		log.Fatal(err)
		return
	}

	err = datastore.DeleteMulti(c, ks)
	if err != nil {
		fmt.Fprint(os.Stderr, "DB Error Deleting All Messages:"+err.Error()+"!\n\n")
		log.Fatal(err)
		return
	}
}
Exemple #27
0
// API that updates the level of a permission. Only owners can elevate a user's
// permission. Requires "userKey" of the user whose permission to update, the
// "doorKey" of the involved door, and the desired "level" of the permission.
func updatePermission(
	r *http.Request, c appengine.Context, u *user.User) (*[]Permission, error) {
	uKey, err := ds.DecodeKey(r.FormValue("userKey"))
	if err != nil {
		return nil, ErrNoUserKey
	}
	var dKey *ds.Key
	dKey, err = ds.DecodeKey(r.FormValue("doorKey"))
	if err != nil {
		return nil, ErrNoDoorKey
	}
	var level int
	level, err = strconv.Atoi(r.FormValue("level"))
	if err != nil {
		return nil, Err{"'level' missing or invalid.", http.StatusBadRequest}
	}
	if level != LevelOpener {
		return nil, Err{"Only updating a permission to opener is allowed.",
			http.StatusForbidden}
	}

	// Verify caller is owner of the door.
	p := Permission{}
	cnt := 0
	if cnt, err = ds.NewQuery("Permission").
		Filter("userKey=", ds.NewKey(c, "User", u.ID, 0, nil)).
		Filter("doorKey=", dKey).
		Filter("level=", LevelOwner).
		Count(c); err != nil {
		return nil, err
	}
	if cnt == 0 {
		return nil, Err{
			"Either the door doesn't exist, or you are not an owner on it.",
			http.StatusForbidden}
	}

	p = Permission{}
	k, err := ds.NewQuery("Permission").
		Filter("userKey=", uKey).
		Filter("doorKey=", dKey).
		Run(c).
		Next(&p)
	if err != nil {
		if err == ds.Done {
			err = Err{"User not has asked for permission on this door",
				http.StatusForbidden}
		}
		return nil, err
	}

	p.Level = level
	if _, err = ds.Put(c, k, &p); err != nil {
		return nil, err
	}

	return &[]Permission{p}, nil
}
Exemple #28
0
// Returns simulations favorited by and comments from the user id passed in the url
func InteractionsHandler(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	userKeyName := vars["userID"]
	ctx := appengine.NewContext(r)
	var simulations []models.SimulationData
	var comments []models.CommentData

	// Check to see if the page user is the same as the logged in user
	userIsOwner := utils.IsOwner(userKeyName, ctx)

	// Only get favorited and commented information if it's the proper user
	// Don't display interaction data to any user except for the user who owns it
	if userIsOwner {
		// Get 50 of the most recent ratings made by the logged in user
		var ratingKeys []*datastore.Key
		var ratingObjs []models.Rating
		q := datastore.NewQuery("Rating").KeysOnly().Filter("AuthorKeyName =", userKeyName).Order("-CreationDate").Limit(50)
		ratingKeys, err := q.GetAll(ctx, ratingObjs)

		// Get the parent keys of the ratings made (these are the keys of the simulations the ratings were for)
		var simulationRateKeys []*datastore.Key
		for _, key := range ratingKeys {
			simulationRateKeys = append(simulationRateKeys, key.Parent())
		}

		// Get all of the simulation objects from the simulation keys
		simulationRateObjs := make([]models.Simulation, len(simulationRateKeys))
		err = datastore.GetMulti(ctx, simulationRateKeys, simulationRateObjs)
		if err != nil {
			controllers.ErrorHandler(w, r, err.Error(), http.StatusInternalServerError)
			return
		}

		// Build the proper simulation data objects from the simulation models
		simulations, err = utils.BuildSimulationDataSlice(ctx, simulationRateObjs, simulationRateKeys)
		if err != nil {
			controllers.ErrorHandler(w, r, "Could not load user simulations: "+err.Error(), http.StatusInternalServerError)
			return
		}

		// Get 50 of the most recent comments made by the logged in user
		q = datastore.NewQuery("Comment").Filter("AuthorKeyName =", userKeyName).Order("-CreationDate").Limit(50)
		comments, err = utils.GetCommentDataSlice(r, q)
		if err != nil {
			controllers.ErrorHandler(w, r, "Error fetching comments: "+err.Error(), http.StatusInternalServerError)
			return
		}
	}

	data := map[string]interface{}{
		"simulations":  simulations,
		"comments":     comments,
		"userIsOwner":  false,
		"userOwnsPage": userIsOwner,
	}

	controllers.BaseHandler(w, r, "user/interactions", data)
}
Exemple #29
0
// GetArticles returns all articles for a feed, refreshing it if necessary.
func (f FeedInfo) articlesSince(c appengine.Context, t time.Time) (articles Articles, err error) {
	key := datastore.NewKey(c, feedKind, f.Url, 0, nil)
	if t.IsZero() {
		_, err = datastore.NewQuery(articleKind).Ancestor(key).GetAll(c, &articles)
	} else {
		_, err = datastore.NewQuery(articleKind).Ancestor(key).Filter("WhenAdded >=", t).GetAll(c, &articles)
	}
	return
}
Exemple #30
0
func articleView(w http.ResponseWriter, r *http.Request, id string) {
	c := appengine.NewContext(r)

	// Get user info
	userInfo := getUserInfo(c)

	// Create get article data query
	dbQuery := datastore.NewQuery("Article").Filter("ID =", id)

	// Check article is exists
	if count, _ := dbQuery.Count(c); count < 1 {
		serve404(w)
		return
	}

	// Get article data
	articleData, err := getArticleData(dbQuery, true, c)
	if err != nil {
		serveError(c, w, err)
		return
	}

	// Get widget data
	dbQuery = datastore.NewQuery("Widget").Order("Sequence")
	widgetData, err := getWidgetData(dbQuery, true, c)
	if err != nil {
		serveError(c, w, err)
		return
	}

	// New PageSetting
	pageSetting := new(PageSetting)

	// Setting PageSetting
	for _, v := range articleData {
		// title
		pageSetting.Title = v.Title + " - " + config.Title

		// description
		if len(v.Content) < 100 {
			pageSetting.Description = html.EscapeString(v.Content)
		} else {
			pageSetting.Description = html.EscapeString(v.Content[:100])
		}
	}
	pageSetting.Layout = "column2"
	pageSetting.ShowSidebar = true

	// New PageData
	pageData := &PageData{User: userInfo, Article: articleData, Widget: widgetData}

	// New Page
	page := NewPage(pageSetting, pageData)

	// Render page
	page.Render("article/view", w)
}