Exemple #1
0
// Apart from rule, there are two mandatory field which must come from the UI: "content_id" and "comment_id"
func UpdateComment(db *mgo.Database, ev ifaces.Event, rule map[string]interface{}, inp map[string][]string, user_id bson.ObjectId) error {
	dat, err := extract.New(rule).Extract(inp)
	if err != nil {
		return err
	}
	basic.DateAndAuthor(rule, dat, user_id, true)
	ids, err := basic.ExtractIds(inp, []string{"content_id", "comment_id"})
	if err != nil {
		return err
	}
	comment_id := bson.ObjectIdHex(ids[1])
	q := bson.M{
		"_id": bson.ObjectIdHex(ids[0]),
		"comments.comment_id": comment_id,
	}
	upd := bson.M{
		"$set": bson.M{
			"comments.$": dat,
		},
	}
	err = db.C("contents").Update(q, upd)
	if err != nil {
		return err
	}
	return db.C("comments").Remove(m{"_id": comment_id})
}
Exemple #2
0
func GetPeerOutCallsAndDurationForDay(day string, peer string, mongoDb *mgo.Database) bson.M {
	collection := mongoDb.C("dailypeer_outgoing")
	results := bson.M{}
	startDate, err := time.Parse(time.RFC3339, day)
	if err != nil {
		panic(err)
	}
	startDayDate := time.Date(startDate.Year(), startDate.Month(), startDate.Day(), 0, 0, 0, 0, time.UTC)
	endDayDate := time.Date(startDate.Year(), startDate.Month(), startDate.Day(), 23, 59, 59, 0, time.UTC)

	var myMatch bson.M

	if len(peer) > 0 {
		myMatch = bson.M{
			"$match": bson.M{
				"metadata.dt":          bson.M{"$gte": startDayDate, "$lte": endDayDate},
				"metadata.dst":         bson.RegEx{peer, "i"},
				"metadata.disposition": 16,
			},
		}
	} else {
		myMatch = bson.M{
			"$match": bson.M{
				"metadata.dt":          bson.M{"$gte": startDayDate, "$lte": endDayDate},
				"metadata.disposition": 16,
			},
		}
	}

	//
	myProject := bson.M{
		"$project": bson.M{
			"_id":      0,
			"calls":    "$calls",
			"duration": "$duration",
		},
	}

	myGroup := bson.M{
		"$group": bson.M{
			"_id":                 0,
			"outCallsNumber":      bson.M{"$sum": "$calls"},
			"outCallsDuration":    bson.M{"$sum": "$duration"},
			"outCallsAvgDuration": bson.M{"$avg": "$duration"},
		},
	}

	//
	operations := []bson.M{myMatch, myProject, myGroup}
	pipe := collection.Pipe(operations)
	err = pipe.One(&results)
	if err != nil {
		results["outCallsNumber"] = 0
		results["outCallsDuration"] = 0
		results["outCallsAvgDuration"] = 0
		return results
	}

	return results
}
func GetBattleAnswerRecs(db *mgo.Database, query interface{}) []BattleAnswerRec {
	var recs []BattleAnswerRec

	db.C("battle_answers").Find(query).All(&recs)

	return recs
}
Exemple #4
0
// this method responds to client updates
// the json data is part of the post request body, we parse
//   it and...
//   1. set the id to the serial
//   2. convert the softwareoutput to html using template.html
//   3. upsert the data into the database
func updateMachine(w http.ResponseWriter, r *http.Request, db *mgo.Database, argPos int) {
	if r.Method != "POST" {
		http.Error(w, "only accepts POST requests", 405)
	}

	body, err := ioutil.ReadAll(r.Body)
	defer r.Body.Close()
	var m machine
	err = json.Unmarshal(body, &m)
	if err != nil {
		fmt.Println(err)
		return
	}

	m.Now = time.Now()
	m.Softwareoutput = template.HTML(strings.Replace(string(m.Softwareoutput), "\n", "<br>", -1))

	fmt.Printf("%v: Connection from %v - ip: %v\n", m.Now, m.Hostname, m.Ip)

	_, err = db.C("machines").UpsertId(m.Id, m)
	if err != nil {
		fmt.Println(err)
	}

	return
}
func GetGameRecs(db *mgo.Database, query interface{}) []GameRec {
	var recs []GameRec

	db.C("games").Find(query).All(&recs)

	return recs
}
Exemple #6
0
// png = path and query
// In the CMS you can access it from uni.P + "?" + uni.Req.URL.RawQuery.
func DoPaging(db *mgo.Database, collection string, query map[string]interface{}, page_num_key string, get map[string][]string, pnq string, limit int) PagingInfo {
	var current_page int
	num_str, has := get[page_num_key]
	if !has {
		current_page = 1
	} else {
		val, err := strconv.ParseInt(num_str[0], 10, 32)
		if err == nil {
			current_page = int(val)
		} else {
			current_page = 1
		}
	}
	all_results, _ := db.C(collection).Find(query).Count() // TODO: think about the error here.
	nav, _ := paging.P(current_page, all_results/limit+1, 3, pnq)
	skip := (current_page - 1) * limit
	return PagingInfo{
		Result:       nav,
		Skip:         skip,
		Current_page: current_page,
		Limit:        limit,
		All_results:  all_results,
		Paramkey:     page_num_key,
		Url:          pnq,
	}
}
Exemple #7
0
/***********************************
delete a machine given machine_id
************************************/
func deleteMachine(w http.ResponseWriter, r *http.Request, db *mgo.Database, argPos int) {
	machine_id := r.URL.Path[argPos:]
	if len(machine_id) == 0 {
		http.Redirect(w, r, "/", 302)
	}
	fmt.Println("Deleting machine: ", machine_id)
	col_m := db.C("machines")

	var m *machine
	err := col_m.Find(bson.M{"_id": machine_id}).One(&m)

	if err != nil {
		fmt.Print(err)
		return
	}

	_, err = db.C("old_machines").Upsert(bson.M{"hostname": m.Hostname}, m)

	if err != nil {
		fmt.Print(err)
	}

	err = col_m.Remove(bson.M{"_id": machine_id})

	if err != nil {
		fmt.Print(err)
	}

	http.Redirect(w, r, "/", 302)
	return
}
Exemple #8
0
// Checks if unvotes are approved at all. Returns error if not.
// Checks if vote option is legal.
// Checks if user indeed voted to that option. Return error if not.
// Decreases the counter field of the given vote option, and pulls the user_id from the field of the given vote option.
func Unvote(db *mgo.Database, user, action map[string]interface{}, inp map[string][]string) error {
	can_unvote, has_cu := action["can_unvote"]
	if !has_cu || can_unvote.(bool) == false {
		return fmt.Errorf("Can't unvote.")
	}
	dat, collection, _, input_vote, err := sharedProc(action, inp)
	if err != nil {
		return err
	}
	doc_id := patterns.ToIdWithCare(dat["document_id"].(string))
	user_id := user["_id"].(bson.ObjectId)
	q := m{"_id": doc_id, input_vote: user_id}
	count, err := db.C(collection).Find(q).Count()
	if err != nil {
		return err
	}
	if count != 1 {
		return fmt.Errorf("Can't unvote a doc which you haven't vote on yet.")
	}
	q = m{"_id": doc_id}
	upd := m{
		"$inc": m{
			input_vote + "_count": -1,
		},
		"$pull": m{
			input_vote: user_id,
		},
	}
	return db.C(collection).Update(q, upd)
}
Exemple #9
0
// 主题所属节点
func (t *Topic) Node(db *mgo.Database) *Node {
	c := db.C("nodes")
	node := Node{}
	c.Find(bson.M{"_id": t.NodeId}).One(&node)

	return &node
}
Exemple #10
0
func (u *Utils) AdCode(position string, db *mgo.Database) template.HTML {
	c := db.C(ADS)
	var ad AD
	c.Find(bson.M{"position": position}).Limit(1).One(&ad)

	return template.HTML(ad.Code)
}
Exemple #11
0
// Called from Front hook.
// Find slug value by given key.
func FindContent(db *mgo.Database, keys []string, val string) (map[string]interface{}, bool) {
	query := bson.M{}
	if len(keys) == 0 {
		return nil, false
	} else if len(keys) == 1 {
		if keys[0] == "_id" && len(val) == 24 { // TODO: check for validity of id.
			query[keys[0]] = bson.ObjectIdHex(val)
		} else {
			query[keys[0]] = val
		}
	} else {
		or := []map[string]interface{}{}
		for _, v := range keys {
			if v == "_id" && len(v) == 24 { // TODO: check fir validity of id.
				or = append(or, map[string]interface{}{v: bson.ObjectIdHex(val)})
			} else {
				or = append(or, map[string]interface{}{v: val})
			}
		}
		query["$or"] = or
	}
	var v interface{}
	db.C(Cname).Find(query).One(&v)
	if v == nil {
		return nil, false
	}
	return basic.Convert(v).(map[string]interface{}), true
}
Exemple #12
0
func (ms *MongodbService) Init(session *mgo.Session, db *mgo.Database, coll string) {
	ms.session = session
	ms.db = db
	ms.c = db.C(coll)
	ms.coll = coll
	ms.mutex = new(sync.Mutex)
}
Exemple #13
0
//reference:[[dataSource, dataSet, fieldName, id], [dataSource, dataSet, fieldName, id]]
//beReference:[[dataSource, dataSet, fieldName, id], [dataSource, dataSet, fieldName, id]]
func (o UsedCheck) GetBeReferenceLi(db *mgo.Database, fieldGroup FieldGroup, relationItem RelationItem, data *map[string]interface{}) []interface{} {
	sourceLi := []interface{}{}
	relationId, err := strconv.Atoi(fmt.Sprint((*data)[fieldGroup.Id]))
	if err != nil {
		panic(err)
	}
	if relationItem.RelationDataSetId == "A" {
		sourceLi = append(sourceLi, []interface{}{relationItem.RelationModelId, "A", "id", relationId})
		return sourceLi
	}

	refData := map[string]interface{}{}
	query := map[string]interface{}{
		relationItem.RelationDataSetId + ".id": relationId,
	}
	//{"B.id": 2}
	err = db.C(relationItem.RelationModelId).Find(query).One(&refData)
	if err != nil {
		panic(err)
	}
	masterData := refData["A"].(map[string]interface{})
	masterDataId, err := strconv.Atoi(fmt.Sprint(masterData["id"]))
	if err != nil {
		panic(err)
	}
	sourceLi = append(sourceLi, []interface{}{relationItem.RelationModelId, "A", "id", masterDataId})

	sourceLi = append(sourceLi, []interface{}{relationItem.RelationModelId, relationItem.RelationDataSetId, "id", relationId})
	return sourceLi
}
Exemple #14
0
// Fork current private template into an other private one.
// Copies the whole directory from /templates/private/{host}/{current_template} to /templates/private/{host}/{inp:new_private_name}
func ForkPrivate(db *mgo.Database, opt map[string]interface{}, inp map[string][]string, root, host string) error {
	if scut.TemplateType(opt) != "private" {
		return fmt.Errorf("Your current template is not a private one.") // Kinda unsensical error message but ok...
	}
	rule := map[string]interface{}{
		"new_template_name": "must",
	}
	dat, e_err := extract.New(rule).Extract(inp)
	if e_err != nil {
		return e_err
	}
	new_template_name := dat["new_template_name"].(string)
	to := filepath.Join(root, "templates", "private", host, new_template_name)
	e, e_err := Exists(to)
	if e_err != nil {
		return fmt.Errorf("Can't determine if private template exists.")
	}
	if e {
		return fmt.Errorf("Private template named %v already exists.", new_template_name)
	}
	from := filepath.Join(root, "templates", "private", host, scut.TemplateName(opt))
	copy_err := copyrecur.CopyDir(from, to)
	if copy_err != nil {
		return fmt.Errorf("There was an error while copying.")
	}
	id := basic.CreateOptCopy(db)
	q := m{"_id": id}
	upd := m{
		"$set": m{
			"Template": new_template_name,
		},
	}
	return db.C("options").Update(q, upd)
}
Exemple #15
0
// Retrieve an instance of the resource given the id. Assumes the resource name matches the collection name
func GetResource(p martini.Params, r render.Render, db *mgo.Database) {
	resource := p["resource"]
	id := p["id"]

	// TODO use reflection
	var result *interface{}
	if !bson.IsObjectIdHex(id) {
		r.JSON(400, map[string]string{"error": "Invalid id"})
		return
	}

	err := db.C(resource).Find(bson.M{"_id": bson.ObjectIdHex(id)}).One(&result)
	if err != nil {
		var status int
		if err == mgo.ErrNotFound {
			status = 404
		} else {
			status = 500
		}

		r.JSON(status, map[string]string{"error": err.Error()})
		return
	}
	r.JSON(200, result)
}
Exemple #16
0
// 分类下的所有站点
func (sc *SiteCategory) Sites(db *mgo.Database) *[]Site {
	var sites []Site
	c := db.C("contents")
	c.Find(bson.M{"categoryid": sc.Id_, "content.type": TypeSite}).All(&sites)

	return &sites
}
Exemple #17
0
func getIndex(w http.ResponseWriter, req *http.Request, vars martini.Params, db *mgo.Database) {
	req.ParseForm()
	// make query & ensure index for meta
	keys := []string{}
	q := bson.M{}
	for k, v := range req.Form {
		key := "metadata." + k
		value := strings.Join(v, "")
		if len(value) > 0 {
			keys = append(keys, key)
			q[key] = value
		}
	}

	// async ensure index
	go func() {
		if len(keys) > 0 {
			db.C(vars["coll"] + ".files").EnsureIndexKey(keys...)
		}
	}()

	result := []Doc{}
	db.C(vars["coll"] + ".files").Find(q).All(&result)
	names := make([]string, len(result))
	for i, _ := range names {
		names[i] = result[i].Join()
	}
	w.WriteHeader(http.StatusOK)
	bytes, _ := json.Marshal(names)
	w.Write(bytes)
}
Exemple #18
0
// 主题所属类型
func (a *Article) Category(db *mgo.Database) *ArticleCategory {
	c := db.C("articlecategories")
	category := ArticleCategory{}
	c.Find(bson.M{"_id": a.CategoryId}).One(&category)

	return &category
}
Exemple #19
0
func RegisterEventAttendeeHandler(a Attendee, mdb *mgo.Database, res http.ResponseWriter, req *http.Request) {

	fmt.Println("Register event attendee")

	mdb.C("attendees").Upsert(bson.M{"eid": a.Eid, "fbuid": a.Fbuid}, &a)

}
Exemple #20
0
// 评论人
func (c *Comment) Creater(db *mgo.Database) *User {
	c_ := db.C("users")
	user := User{}
	c_.Find(bson.M{"_id": c.CreatedBy}).One(&user)

	return &user
}
Exemple #21
0
// TODO: define which fields are shown using the header-file
func machineList(w http.ResponseWriter, r *http.Request, db *mgo.Database, argPos int) {
	sortKey := r.FormValue("sortkey")
	if sortKey == "" {
		sortKey = "hostname"
	}

	m := new(machines)
	m.Headers = MachineListHeaders()

	c := db.C("machines")

	var arr *machine
	i := 1
	err := c.Find(nil).Sort(sortKey).
		For(&arr, func() error {
			arr.Cnt = i
			i++
			m.Machines = append(m.Machines, *arr)
			return nil
		})
	if err != nil {
		fmt.Println(err)
		http.NotFound(w, r)
		return
	}
	set.ExecuteTemplate(w, "machinelist", m)
}
Exemple #22
0
// 主题
func (c *Comment) Topic(db *mgo.Database) *Topic {
	// 内容
	var topic Topic
	c_ := db.C("contents")
	c_.Find(bson.M{"_id": c.ContentId, "content.type": TypeTopic}).One(&topic)
	return &topic
}
Exemple #23
0
/************************************
 * Return Codes:
 * SUCCESS		if friendship was in database,
 * NOTFOUND 	if one or both of the users
 *						is not in the DB
 * NOTFRIENDS	if they aren't friends
 ************************************/
func (u *User) QueryFriend(db mgo.Database, friendEmail string) (returnCode int) {

	friend := User{}
	friend.Email = friendEmail

	// Check that they're both in the database
	if u.Query(db) != error.SUCCESS || friend.Query(db) != error.SUCCESS {
		return error.NOTFOUND
	}

	// See if they're already friends, both ways since commutative
	result := Friendship{}
	result2 := Friendship{}
	db.C("friends").Find(bson.M{"user1": u.Email, "user2": friendEmail}).One(&result)
	db.C("friends").Find(bson.M{"user2": u.Email, "user1": friendEmail}).One(&result2)

	// if they are, say so
	if (result.User1 == u.Email && result.User2 == friendEmail) ||
		(result.User1 == friendEmail && result.User1 == u.Email) {
		return error.SUCCESS
	}

	// otherwise not found
	return error.NOTFRIENDS
}
Exemple #24
0
func (p *Package) Category(db *mgo.Database) *PackageCategory {
	category := PackageCategory{}
	c := db.C("packagecategories")
	c.Find(bson.M{"_id": p.CategoryId}).One(&category)

	return &category
}
Exemple #25
0
func GetYearPeerInCallsAndDurationForYear(year int, peer string, mongoDb *mgo.Database) bson.M {
	collection := mongoDb.C("monthlypeer_incomming")

	results := bson.M{}

	startDayDate := time.Date(year, 1, 1, 1, 0, 0, 0, time.UTC)
	endDayDate := time.Date(year, 12, 31, 23, 59, 59, 0, time.UTC)

	var myMatch bson.M

	if len(peer) > 0 {
		myMatch = bson.M{
			"$match": bson.M{
				"metadata.dt":          bson.M{"$gte": startDayDate, "$lte": endDayDate},
				"metadata.dst":         bson.RegEx{peer, "i"},
				"metadata.disposition": 16,
			},
		}
	} else {
		myMatch = bson.M{
			"$match": bson.M{
				"metadata.dt":          bson.M{"$gte": startDayDate, "$lte": endDayDate},
				"metadata.disposition": 16,
			},
		}
	}

	//
	myProject := bson.M{
		"$project": bson.M{
			"_id":              0,
			"calls":            "$calls",
			"duration":         "$duration",
			"answer_wait_time": "$answer_wait_time",
		},
	}

	myGroup := bson.M{
		"$group": bson.M{
			"_id":                      0,
			"inCallsAnswered":          bson.M{"$sum": "$calls"},
			"inCallsDuration":          bson.M{"$sum": "$duration"},
			"inCallsAvgDuration":       bson.M{"$avg": "$duration"},
			"inCallsAvgWaitAnswerTime": bson.M{"$avg": "$answer_wait_time"},
		},
	}

	//
	operations := []bson.M{myMatch, myProject, myGroup}
	pipe := collection.Pipe(operations)
	err := pipe.One(&results)
	if err != nil {
		results["inCallsAnswered"] = 0
		results["inCallsDuration"] = 0
		results["inCallsAvgDuration"] = 0
		results["inCallsAvgWaitAnswerTime"] = 0
		return results
	}
	return results
}
Exemple #26
0
// Queries a draft and rebuilds it. Queries its parent too, and merges it with the input fields saved in "data".
// The returned draft will be like a simple draft in the database, but in the data field it will contain fields of the parent plus the fresher saved input data.
// draft_typ example: blog_draft
// Only
func BuildDraft(db *mgo.Database, draft_typ, draft_id_str string) (map[string]interface{}, error) {
	draft_id := patterns.ToIdWithCare(draft_id_str)
	q := m{"_id": draft_id}
	var v interface{}
	err := db.C(Cname + Draft_collection_postfix).Find(q).One(&v)
	if err != nil {
		return nil, err
	}
	draft := basic.Convert(v).(map[string]interface{})
	typ_i, has_typ := draft["type"]
	if !has_typ {
		return nil, fmt.Errorf("Draft has no type.")
	}
	typ, is_str := typ_i.(string)
	if !is_str {
		return nil, fmt.Errorf("Draft type is not a string.")
	}
	if typ != draft_typ {
		return nil, fmt.Errorf("Draft type is not the expected one: %v instead if %v.", typ, draft_typ)
	}
	parent, err := GetParent(db, "contents", draft)
	if err != nil {
		return nil, err
	}
	draft["data"] = mergeWithParent(draft["data"].(map[string]interface{}), parent)
	return draft, nil
}
Exemple #27
0
func GetPeers(mongoDb *mgo.Database) []bson.M {
	incomming := mongoDb.C("peers")
	results := []bson.M{}

	//
	myProject := bson.M{
		"$project": bson.M{
			"id":      "$peer",
			"comment": "$comment",
			"value":   "$value",
		},
	}

	mySort := bson.M{
		"$sort": bson.M{
			"id": 1,
		},
	}
	//
	operations := []bson.M{myProject, mySort}
	pipe := incomming.Pipe(operations)
	err := pipe.All(&results)
	if err != nil {
		panic(err)
	}

	return results
}
Exemple #28
0
// Implementation of versioning is in basic.InudVersion.
func ChangeHead(db *mgo.Database, ev ifaces.Event, inp map[string][]string, non_versioned_fields []string) error {
	rule := map[string]interface{}{
		"version_id": "must",
		"id":         "must",
	}
	dat, err := extract.New(rule).Extract(inp)
	if err != nil {
		return err
	}
	version_id_str := basic.StripId(dat["version_id"].(string))
	version_id := bson.ObjectIdHex(version_id_str)
	var v interface{}
	err = db.C(Cname + "_version").Find(bson.M{"_id": version_id}).One(&v)
	if err != nil {
		return err
	}
	revert_to := v.(bson.M)
	id := patterns.ToIdWithCare(dat["id"].(string))
	for _, v := range non_versioned_fields {
		delete(revert_to, v)
	}
	revert_to["points_to"] = revert_to["_id"]
	delete(revert_to, "id")
	return db.C(Cname).Update(bson.M{"_id": id}, bson.M{"$set": revert_to})
}
Exemple #29
0
// *****************************************
// BLACKLISTING APPLICATIONS
// *****************************************
func addBlacklist(w http.ResponseWriter, r *http.Request, db *mgo.Database, argPos int) {
	// name example: key="apps._name", val="Dropbox"
	// path example: key="apps.path", val="/Applications/Xinet Software/Uploader Manager.app"
	path := r.FormValue("path")
	name := r.FormValue("name")
	app := &black{
		Path: path,
		Name: name}

	if app.Name == "" {
		tmp := strings.Split(path, "/")
		app.Name = strings.Split(tmp[len(tmp)-1], ".")[0]
	}

	if strings.Split(path, "/")[1] == "Users" {
		fmt.Println("blacklisting by name: ", path, "\n\tname: ", name)
		// if application is located in a users folder
		// we must match on name instead of complete path
		app.Key = "apps._name"
		app.Val = app.Name
	} else {
		fmt.Println("blacklisting by path: ", path)
		app.Key = "apps.path"
		app.Val = path
	}
	// doesn't nessesarily need to match on both key AND val..
	db.C("blacklist").Upsert(bson.M{"key": app.Key, "val": app.Val}, app)

	http.Redirect(w, r, "/blacklist/", 302)
}
Exemple #30
0
/********************************************************
// queries a list of machines that has exacly the machine
// - filters using filter_apps
*********************************************************/
func searchExact(w http.ResponseWriter, r *http.Request, db *mgo.Database, argPos int) {
	key := r.FormValue("key")
	val := r.FormValue("val")

	context := make([]appResult, 0, 10)
	var res *appResult

	c := db.C("machines")
	var usePath bool
	if key == "apps.path" {
		usePath = true
	}

	err := c.Find(bson.M{key: val}).
		Select(bson.M{
			"hostname": 1,
			"apps":     1,
			"_id":      1}).
		Sort("hostname").
		For(&res, func() error {
			res.Apps = filter_apps(val, res.Apps, usePath)
			context = append(context, *res)
			return nil
		})

	if err != nil {
		fmt.Println(err)
		http.NotFound(w, r)
		return
	}
	set.ExecuteTemplate(w, "searchresults", context)
}