Пример #1
0
// Only called when doing update or delete.
// At inserting, user.OkayToDoAction is sufficient.
// This needs additional action: you can only update or delete a given comment only if it's yours (under a certain level).
func CanModifyComment(db *mgo.Database, inp map[string][]string, correction_level int, user_id bson.ObjectId, user_level int) error {
	rule := map[string]interface{}{
		"content_id": "must",
		"comment_id": "must",
		"type":       "must",
	}
	dat, err := extract.New(rule).Extract(inp)
	if err != nil {
		return err
	}
	// Even if he has the required level, and he is below correction_level, he can't modify other people's comment, only his owns.
	// So we query here the comment and check who is the owner of it.
	if user_level < correction_level {
		content_id_str := basic.StripId(dat["content_id"].(string))
		comment_id_str := basic.StripId(dat["comment_id"].(string))
		auth, err := findCommentAuthor(db, content_id_str, comment_id_str)
		if err != nil {
			return err
		}
		if auth.Hex() != user_id.Hex() {
			return fmt.Errorf("You are not the rightous owner of the comment.")
		}
	}
	return nil
}
Пример #2
0
func (c Blog) GetRead(id bson.ObjectId) revel.Result {
	if id.Hex() != "" {
		article := models.GetArticleByObjectId(c.MongoSession, id)
		return c.Render(article)
	}
	return c.NotFound("Invalid article Id.")
}
Пример #3
0
// Get document from id
func (s *session) GetId(col string, id bson.ObjectId, doc interface{}) error {
	c := s.db.C(col)
	err := c.FindId(id).One(doc)
	if err != nil {
		log.Printf("**ERROR: Could not lookup document with id %v from collection %v: %v", id.Hex(), col, err)
	}
	return err
}
Пример #4
0
// 添加共享d笔记
func (this *NoteService) AddSharedNote(note info.Note, myUserId bson.ObjectId) info.Note {
	// 判断我是否有权限添加
	if shareService.HasUpdateNotebookPerm(note.UserId.Hex(), myUserId.Hex(), note.NotebookId.Hex()) {
		note.CreatedUserId = myUserId // 是我给共享我的人创建的
		return this.AddNote(note)
	}
	return info.Note{}
}
Пример #5
0
// 查找ObjectId数组中是否有指定值.
func ObjectIdInSlice(id bson.ObjectId, list []bson.ObjectId) bool {
	for _, b := range list {
		if b.Hex() == id.Hex() {
			return true
		}
	}
	return false
}
Пример #6
0
func backupServer(serverId string, backupTime time.Time) (err error) {
	wip := <-wipGen.C
	defer close(wip)

	server := servers.Get(serverId)
	if server == nil {
		err = errors.New(fmt.Sprintf("no server for %s", serverId))
		return
	}

	var (
		url  string
		size int64
	)
	err = retry(1000, 5*time.Second, func(retries int) error {
		var err error
		url, size, err = server.BackupWorld(backupTime)
		if err != nil {
			plog.Error(err, map[string]interface{}{
				"event":    "world_backup",
				"serverId": serverId,
				"retries":  retries,
			})
		}
		return err
	})
	if err != nil {
		return
	}

	var snapshotId bson.ObjectId
	err = retry(1000, 5*time.Second, func(retries int) error {
		var err error
		snapshotId, err = StoreBackupInMongo(serverId, url, size, backupTime)
		if err != nil {
			plog.Error(err, map[string]interface{}{
				"event":    "world_db_store",
				"serverId": serverId,
				"retries":  retries,
			})

		}
		return err
	})

	pushPinkyEvent(map[string]interface{}{
		"ts":          time.Now(),
		"server_id":   serverId,
		"event":       "server_event",
		"type":        "backed_up",
		"snapshot_id": snapshotId.Hex(),
		"url":         url,
		"size":        size,
	})

	return
}
Пример #7
0
func (api *EventsApi) deleteImage(id bson.ObjectId) error {

	err := api.images.DeleteFile(api.images.GetBasePath() + string(os.PathSeparator) + id.Hex() + ".jpg")
	if err != nil {
		return err
	}

	api.imageCache.Remove(api.imageCache.FindKeys(id.Hex()))
	return nil
}
Пример #8
0
//-------------------------------------------------------
// methods
//-------------------------------------------------------
// obtain all the data and proceed to authorisation
func (d *Daemon) Authenticate(id bson.ObjectId) error {
	c := db.C("daemons")
	err := c.FindId(id).One(&d.Entry)
	if err == nil {
		d.Id = id.Hex()
		d.OrgId = d.Entry.OrgId.Hex()
		return d.Authorise()
	}
	return err
}
func mapFromFeed(feed *domain.Feed) feedDao {
	var id bson.ObjectId
	if len(feed.ID) > 0 {
		id = bson.ObjectIdHex(feed.ID)
	} else {
		id = bson.NewObjectId()
		feed.ID = id.Hex()
	}
	return feedDao{id, feed.Uri, feed.LastSync}
}
Пример #10
0
//-------------------------------------------------------
// methods
//-------------------------------------------------------
// obtain all the data and proceed to authorisation
func (u *User) Authenticate(id bson.ObjectId) error {
	c := db.C("users")
	err := c.FindId(id).One(&u.Entry)
	if err == nil {
		u.Id = id.Hex()
		u.OrgId = u.Entry.OrgId.Hex()
		return u.Authorise()
	}
	return err
}
Пример #11
0
// 检测ObjectId数组中是否存在某一个id。
func ObjectIdIsIn(ids []bson.ObjectId, id bson.ObjectId) bool {
	result := false
	for i := 0; i < len(ids); i++ {
		if ids[i].Hex() == id.Hex() {
			result = true
			break
		}
	}

	return result
}
Пример #12
0
func (c User) GetUpdate(id bson.ObjectId) revel.Result {
	if c.ActiveUser != nil {
		action := "/User/" + id.Hex()
		user := c.ActiveUser
		if user.CanBeUpdatedBy(c.MongoSession, c.ActiveUser) {
			return c.Render(action, user)
		}
		return c.Forbidden("You are not allowed to edit this resource.")
	}
	return c.Redirect(User.GetLogin)
}
Пример #13
0
// Implements bson.Setter for mongo.Ref compatibility.
// Yes this bson dependency is dirty, but necessary
// for transition form mongo.Ref to model.Ref.
func (self *Ref) SetBSON(raw bson.Raw) error {
	var objectId *bson.ObjectId
	if raw.Unmarshal(&objectId) == nil {
		if objectId != nil {
			*self = Ref(objectId.Hex())
		} else {
			*self = ""
		}
		return nil
	}
	return raw.Unmarshal(self)
}
Пример #14
0
func (table *mongoTable) CheckForId(id bson.ObjectId) error {

	count, err := table.CountById(id)
	if err != nil {
		return err
	}

	if count == 1 {
		return nil
	} else {
		return errors.New(table.collection.Name + " " + id.Hex() + " not found.")
	}
}
Пример #15
0
// Sets a cookie to w named "user" with a value of the encoded user_id.
// Admins, guests, registered users, everyone logs in with this.
func Login(w http.ResponseWriter, user_id bson.ObjectId, block_key []byte) error {
	id_b, err := encryptStr(block_key, user_id.Hex())
	if err != nil {
		return err
	}
	encoded_id := string(id_b)
	c := &http.Cookie{
		Name:   "user",
		Value:  encoded_id,
		MaxAge: 3600000,
		Path:   "/",
	}
	http.SetCookie(w, c)
	return nil
}
Пример #16
0
func TestGetDeveloperById(t *testing.T) {
	mock, err := MockDB()
	if err != nil {
		t.Fatal("Unable to Mock DB:", err)
	}

	var id bson.ObjectId

	id = mock.ID

	dev, err := GetDeveloperById(id.Hex())
	if err != nil {
		t.Fatal("Unable to GetDeveloperById:", err)
	}

	if dev.Email != mock.Email {
		t.Error("email not saved correctly.")
	}
}
Пример #17
0
func TestPasswordEditHandler(t *testing.T) {
	mock, err := db.MockDB()
	if err != nil {
		t.Fatal("Could not Mock DB:", err)
	}

	var id bson.ObjectId
	fmt.Printf("%T", mock.ID)
	id = mock.ID

	var token string
	if token = mock.Token; token == "" {
		t.Fatal("Invalid token")
	}

	req, err := http.NewRequest("PUT", "http://broome.io/developers/reset/"+token, nil)
	if err != nil {
		t.Fatal("Could not Create Request", err)
	}
	req.PostForm = url.Values{
		"id":  {id.Hex()},
		"new": {"password"},
	}
	res := httptest.NewRecorder()
	broomeServer(res, req)

	if res.Code != http.StatusOK {
		t.Fatalf("Non-expected status code: %v\tbody: %v", res.Code, res.Body)
	}

	body := map[string]interface{}{}
	if err := json.Unmarshal([]byte(res.Body.String()), &body); err != nil {
		t.Fatal("Response is not valid JSON", err)
	}

	if body["status"] != "success" {
		t.Fatal("response status should be 'updated' not ", body["status"])
	}
}
Пример #18
0
// Returns true if one is entitled to modify the given content.
func CanModifyContent(db *mgo.Database, inp map[string][]string, correction_level int, user_id bson.ObjectId, user_level int) error {
	rule := map[string]interface{}{
		"id": "must",
	}
	dat, err := extract.New(rule).Extract(inp)
	if err != nil {
		return err
	}
	if user_level < correction_level {
		content := find(db, dat["id"].(string))
		if content == nil {
			return fmt.Errorf("Can't find content.")
		}
		auth, err := contentAuthor(content)
		if err != nil {
			return err
		}
		if auth.Hex() != user_id.Hex() {
			return fmt.Errorf("You can not modify this type of content if it is not yours.")
		}
	}
	return nil
}
Пример #19
0
func (s *WebAPISuite) pingSession(sessionId bson.ObjectId, machineId string) *Response {
	return s.handlePost(PingSessionHandler, map[string]string{
		"session_id": sessionId.Hex(),
		"machine_id": machineId,
	})
}
Пример #20
0
func (self *Collection) logIdNotFoundError(id bson.ObjectId) {
	config.Logger.Printf("MongoDB document with id %s not found in collection %s", id.Hex(), self.Collection().Name)
	debug.LogCallStack()
}
Пример #21
0
func hexId(a bson.ObjectId) string {
	return a.Hex()
}
Пример #22
0
func (an *analyser) analyseFile(documentID bson.ObjectId /*tess *tesseract.Tess,*/, tmpDirName string, fileInfo os.FileInfo) bool {
	pageNumberSubmatch := regexpOutputFileName.FindStringSubmatch(fileInfo.Name())
	pageNumberString := pageNumberSubmatch[1]
	pageNumberUint64, _ := strconv.ParseUint(pageNumberString, 10, 32)
	pageNumber := uint(pageNumberUint64)
	an.Logf("found page %d", pageNumber)

	outputTmpFile, err := os.Open(path.Join(tmpDirName, fileInfo.Name()))
	if err != nil {
		log.Printf("error opening output file(%s): %s\n", fileInfo.Name(), err)
		return false
	}
	defer outputTmpFile.Close()

	outputGridFileHighresName := fmt.Sprintf("highres/%s-%s.png", documentID.Hex(), pageNumberString)
	outputGridFileHighres, err := gridFS.Create(outputGridFileHighresName)
	if err != nil {
		log.Printf("error creating GridFS file(%s): %s\n", outputGridFileHighresName, err)
		return false
	}
	defer outputGridFileHighres.Close()

	// create buffer to be filled with image data
	imageBuf := bytes.NewBuffer(make([]byte, 0, fileInfo.Size()))

	// copy image data to gridFile while tee-reading to imageBuf
	_, err = io.Copy(outputGridFileHighres, io.TeeReader(outputTmpFile, imageBuf))
	if err != nil {
		log.Printf("error copying data from tempFile to gridFile: %s\n", err)
		return false
	}
	outputGridFileHighres.Close()
	an.Logf("read output png, saved highres. page %d", pageNumber)

	// // get bytes from imageBuf and create leptonica pix
	// imageBytes := imageBuf.Bytes()
	// pix, err := leptonica.NewPixReadMem(&imageBytes)
	// if err != nil {
	// 	log.Printf("error creating new pix from imageBuf: %s\n", err)
	// 	return false
	// }
	// defer pix.Close()

	// resize for thumbnail
	if pageNumber == 1 {
		imageBufReader := bytes.NewReader(imageBuf.Bytes())
		outputGridFileThumbnailName := fmt.Sprintf("document-thumbnails/%s.png", documentID.Hex())
		outputGridFileThumbnail, err := gridFS.Create(outputGridFileThumbnailName)
		if err != nil {
			log.Printf("error creating GridFS file(%s): %s\n", outputGridFileThumbnailName, err)
			return false
		}
		defer outputGridFileThumbnail.Close()
		err, _ = readResizeWrite(imageBufReader, outputGridFileThumbnail, thumbnailWidth)
		if err != nil {
			log.Printf("error performing readResizeWrite for gridFile(%s): %s\n", outputGridFileThumbnailName, err)
			return false
		}
		outputGridFileThumbnail.Close()
		an.Logf("resized page for thumbnail %d", pageNumber)
	}

	// resize for docviewer
	imageBufReader := bytes.NewReader(imageBuf.Bytes())
	outputGridFileDocviewerName := fmt.Sprintf("docviewer-pages/%s-%s.png", documentID.Hex(), pageNumberString)
	outputGridFileDocviewer, err := gridFS.Create(outputGridFileDocviewerName)
	if err != nil {
		log.Printf("error creating GridFS file(%s): %s\n", outputGridFileDocviewerName, err)
		return false
	}
	defer outputGridFileDocviewer.Close()
	err, sizes := readResizeWrite(imageBufReader, outputGridFileDocviewer, docviewerWidth)
	if err != nil {
		log.Printf("error performing readResizeWrite for gridFile(%s): %s\n", outputGridFileDocviewerName, err)
		return false
	}
	outputGridFileDocviewer.Close()
	an.Logf("resized page for docviewer %d", pageNumber)

	// // hand leptonica pix to tess
	// tess.SetImagePix(pix)

	// create page object
	page := &pageData{
		ID:         bson.NewObjectId(),
		DocumentID: documentID,
		PageNumber: pageNumber,
		// Text:          tess.Text(),
		Lines:         make([]*[]*charData, 0),
		HighresWidth:  sizes.Dx(),
		HighresHeight: sizes.Dy(),
	}

	// // get boxed text
	// boxText, err := tess.BoxText(0)
	// if err != nil {
	// 	log.Printf("error retrieving boxText: %s\n", err)
	// 	return false
	// }
	// // cleanup tess and pix for this page
	// tess.Clear()
	// pix.Close()
	// an.Logf("retrieved boxText for page %d", pageNumber)

	// // loop over box text and create lines
	// var line []*charData
	// for _, tessChar := range boxText.Characters {
	// 	char := &charData{
	// 		X1: (float32(tessChar.StartX) / float32(page.HighresWidth) * float32(100)),
	// 		Y1: (float32(tessChar.StartY) / float32(page.HighresHeight) * float32(100)),
	// 		X2: (float32(tessChar.EndX) / float32(page.HighresWidth) * float32(100)),
	// 		Y2: (float32(tessChar.EndY) / float32(page.HighresHeight) * float32(100)),
	// 		C:  string(tessChar.Character),
	// 	}
	// 	//TODO: \n won't ever happen with BoxText()
	// 	// ++ need to mix this information with .Text() information to have whitespace
	// 	if line == nil || char.C == "\n" {
	// 		line = make([]*charData, 0)
	// 		page.Lines = append(page.Lines, &line)
	// 	}

	// 	line = append(line, char)
	// }

	err = colPages.Insert(page)
	if err != nil {
		log.Printf("error inserting page into collection: %s\n", err)
		return false
	}
	an.Logf("inserted page %s", page.ID.Hex())
	return true
}
Пример #23
0
func (a *AbstractModel) IsEmptyObjectId(id bson.ObjectId) bool {
	return id.Hex() == "000000000000000000000000"
}
Пример #24
0
func (self *Collection) DocumentLabel(docId bson.ObjectId, labelSelectors ...string) (string, error) {
	if !docId.Valid() {
		return "", fmt.Errorf("Invalid bson.ObjectId")
	}
	if len(labelSelectors) == 0 {
		labelSelectors = self.DocLabelSelectors
	}

	if len(labelSelectors) == 0 {
		// No label selectors, use hex ID as label
		count, err := self.collection.FindId(docId).Count()
		if err != nil {
			return "", err
		}
		if count == 0 {
			return "", fmt.Errorf("No document with ID '%s' in collection '%s'", docId.Hex(), self.Name)
		}
		return docId.Hex(), nil
	}

	labels := make([]string, len(labelSelectors))
	for i, selector := range labelSelectors {
		if len(selector) == 0 {
			return "", fmt.Errorf("Label selector must not be an empty string")
		}

		selector = strings.ToLower(selector)

		var doc bson.M
		err := self.collection.FindId(docId).Select(bson.M{selector: 1}).One(&doc)
		if err != nil {
			return "", err
		}

		var label interface{}
		if strings.IndexRune(selector, '.') != -1 {
			for _, subSel := range strings.Split(selector, ".") {
				label, _ = doc[subSel]
				if label == nil {
					break
				}
				doc, _ = label.(bson.M)
				if doc == nil {
					break
				}
			}
		} else {
			label, _ = doc[selector]
		}

		if label != nil {
			// Support the basic BSON types from unmarshalling
			switch s := label.(type) {
			case string:
				labels[i] = s

			case int:
				labels[i] = strconv.Itoa(s)

			case float64:
				labels[i] = strconv.FormatFloat(s, 'f', -1, 64)

			case bool:
				labels[i] = strconv.FormatBool(s)

			case bson.ObjectId:
				labels[i] = s.Hex()

			default:
				return "", fmt.Errorf("Can't get label of %s for '%s' because it is of type %T", docId.Hex(), selector, label)
			}
		}
	}

	label := strings.Join(labels, self.DocLabelSeparator)
	label = strings.TrimSpace(utils.RemoveMultipleWhiteSpace(label))

	return label, nil
}
Пример #25
0
// URL: /comment/{contentId}
// 评论,不同内容共用一个评论方法
func commentHandler(handler Handler) {
	if handler.Request.Method != "POST" {
		return
	}

	user, _ := currentUser(handler.Request)

	vars := mux.Vars(handler.Request)
	contentId := vars["contentId"]

	var temp map[string]interface{}
	c := DB.C(CONTENTS)
	c.Find(bson.M{"_id": bson.ObjectIdHex(contentId)}).One(&temp)

	temp2 := temp["content"].(map[string]interface{})
	var contentCreator bson.ObjectId
	contentCreator = temp2["createdby"].(bson.ObjectId)
	type_ := temp2["type"].(int)

	var url string
	switch type_ {
	case TypeArticle:
		url = "/a/" + contentId
	case TypeTopic:
		url = "/t/" + contentId
	case TypePackage:
		url = "/p/" + contentId
	}

	c.Update(bson.M{"_id": bson.ObjectIdHex(contentId)}, bson.M{"$inc": bson.M{"content.commentcount": 1}})

	content := handler.Request.FormValue("content")

	html := handler.Request.FormValue("html")
	html = strings.Replace(html, "<pre>", `<pre class="prettyprint linenums">`, -1)

	Id_ := bson.NewObjectId()
	now := time.Now()

	c = DB.C(COMMENTS)
	c.Insert(&Comment{
		Id_:       Id_,
		Type:      type_,
		ContentId: bson.ObjectIdHex(contentId),
		Markdown:  content,
		Html:      template.HTML(html),
		CreatedBy: user.Id_,
		CreatedAt: now,
	})

	if type_ == TypeTopic {
		// 修改最后回复用户Id和时间
		c = DB.C(CONTENTS)
		c.Update(bson.M{"_id": bson.ObjectIdHex(contentId)}, bson.M{"$set": bson.M{"latestreplierid": user.Id_.Hex(), "latestrepliedat": now}})

		// 修改中的回复数量
		c = DB.C(STATUS)
		c.Update(nil, bson.M{"$inc": bson.M{"replycount": 1}})
		/*mark ggaaooppeenngg*/
		//修改用户的最近回复
		c = DB.C(USERS)
		//查找评论中at的用户,并且更新recentAts
		users := findAts(content)
		for _, v := range users {
			var user User
			err := c.Find(bson.M{"username": v}).One(&user)
			if err != nil {
				fmt.Println(err)
			} else {
				user.RecentAts = append(user.RecentAts, contentId)
				if err = c.Update(bson.M{"username": user.Username}, bson.M{"$set": bson.M{"recentats": user.RecentAts}}); err != nil {
					fmt.Println(err)
				}
			}
		}

		//修改用户的最近回复
		//该最近回复提醒通过url被点击的时候会被disactive
		//更新最近的评论
		//自己的评论就不提示了
		if contentCreator.Hex() != user.Id_.Hex() {
			var recentreplies []string
			var Creater User
			err := c.Find(bson.M{"_id": contentCreator}).One(&Creater)
			if err != nil {
				fmt.Println(err)
			}
			recentreplies = Creater.RecentReplies
			//添加最近评论所在的主题id
			recentreplies = append(recentreplies, contentId)
			if err = c.Update(bson.M{"_id": contentCreator}, bson.M{"$set": bson.M{"recentreplies": recentreplies}}); err != nil {
				fmt.Println(err)
			}
		}
	}

	http.Redirect(handler.ResponseWriter, handler.Request, url, http.StatusFound)
}
Пример #26
0
// 主题链接
func (t *Topic) Link(createdBy bson.ObjectId) string {
	return "http://golangtc.com/t/" + createdBy.Hex()

}
Пример #27
0
func ObjectIdHex(id bson.ObjectId) string {
	return id.Hex()
}