Ejemplo n.º 1
0
func Edit(db *gorp.DbMap, w WikiPage) (WikiPage, bool) {
	if w.Id == 0 {
		db.Insert(&w)
	} else {
		wOld, ok := GetBySlug(db, w.Title)
		if !ok {
			return WikiPage{}, false
		}
		textOld := string(wOld.Body)
		textNew := string(w.Body)

		d := diffmatchpatch.New()
		b := d.DiffMain(textNew, textOld, false)

		dl := d.DiffToDelta(b)

		delta := WikiDelta{
			ItemId:    w.Id,
			PrevDelta: w.PrevDelta,
			Delta:     []byte(dl),
		}

		db.Insert(&delta)

		w.PrevDelta = delta.Id

		db.Update(&w)
	}
	return w, true
}
Ejemplo n.º 2
0
func AddPage(Db *gorp.DbMap, fullurl string) (SitePage, error) {
	fullurl = n(fullurl)
	u, _ := url.Parse(fullurl)
	res := SitePage{}
	if IsExistPage(Db, fullurl) {
		return res, errors.New("exist")
	}

	if !IsExistSite(Db, fullurl) {
		_, err := AddSite(Db, fullurl)
		if err != nil {
			return res, err
		}
	}

	site, err := GetSite(Db, fullurl)
	if err != nil {
		return res, errors.New("site not exist")
	}

	res.SiteId = site.Id
	res.Url = u.RequestURI()

	err = Db.Insert(&res)
	if err != nil {
		return res, err
	}

	return res, nil
}
Ejemplo n.º 3
0
func SetForItem(db *gorp.DbMap, tagId, itemId int64, itemType string) error {
	t := Tags{}
	t.Id = tagId
	t.ItemId = itemId
	t.ItemType = itemType
	return db.Insert(&t)
}
Ejemplo n.º 4
0
func insertOrUpdateContact(dbmap *gorp.DbMap, user, contactid, contactname, group string) error {
	var contacts []Contact
	_, err := dbmap.Select(&contacts, "SELECT * FROM contacts WHERE User=? AND ContactId=?", user, contactid)
	if err != nil {
		return err
	}

	if len(contacts) == 0 {
		contact := Contact{
			User:        user,
			ContactId:   contactid,
			ContactName: contactname,
			Group:       group,
		}
		err = dbmap.Insert(&contact)
		if err != nil {
			return err
		}
	} else if len(contacts) == 1 {
		contact := contacts[0]
		contact.ContactName = contactname
		contact.Group = group
		_, err = dbmap.Update(&contact)
		if err != nil {
			return err
		}
	} else {
		return errors.New("You have more than one contacts")
	}
	return nil
}
Ejemplo n.º 5
0
func PostUser(r render.Render, dbmap *gorp.DbMap, res http.ResponseWriter, u User, e binding.Errors) {
	if e != nil {
		r.JSON(http.StatusBadRequest, map[string]string{"message": e[0].Message})
		return
	}
	//check user exists yet or not?
	var count int64
	count, err := dbmap.SelectInt("SELECT count(*) FROM CUSTOMER WHERE CUS_TEL=?", u.PhoneNumber)
	if err != nil {
		glog.V(1).Infof("[DEBUG:] Search customer by tel:%v fail:%v", u.PhoneNumber, err)
		r.JSON(http.StatusConflict, map[string]string{"message": "DB ERROR"})
		return
	}

	if count > 0 {
		glog.V(1).Infof("Customer with tel:%v exists yet", u.PhoneNumber)
		r.JSON(http.StatusConflict, map[string]string{"message": "User with same Tel exists"})
		return
	}

	//insert new user info to db;
	err = dbmap.Insert(&u)
	if err != nil {
		glog.V(1).Infof("[DEBUG:] Insert customer %v fail:%v", u, err)
		r.JSON(http.StatusConflict, map[string]string{"message": "DB ERROR"})
		return
	}
	r.JSON(200, map[string]string{"message": "SUCCESS"})
}
Ejemplo n.º 6
0
func createTag(db *gorp.DbMap, t Tag) (Tag, error) {
	var err error
	if !tagExist(db, t.Title) {
		err = db.Insert(&t)
	}
	return t, err
}
Ejemplo n.º 7
0
func hostState(msg Message, gameId string, playerId int, gs GameService, ws *websocket.Conn, db *gorp.DbMap, log *log.Logger) error {
	log.Printf("Got state change request from host: %v", msg["state"])

	game, _, err := gs.GetGame(db, gameId, playerId)
	if err != nil {
		log.Printf("%#v", err)
		return err
	}

	// TODO: check to make sure this is a valid state
	game.State = msg["state"].(string)
	var board *TicTacToe_Board
	if game.State == "start" {
		board = &TicTacToe_Board{Game: gameId}
		log.Printf("Setting up starting objects")
		// we are starting a game, so insert a new board
		err = board.setBoard([]int{0, 0, 0, 0, 0, 0, 0, 0, 0})
		if err != nil {
			log.Printf("Unable to set game board: %#v", err)
			return err
		}
		log.Printf("Inserting board: %#v", board)
		err = db.Insert(board)
		if err != nil {
			log.Printf("Couldn't insert board: %#v", err)
			return err
		}
	} else {
		board, err = getBoard(gameId, db)
		if err != nil {
			log.Printf("Unable to get board: %#v", err)
			return err
		}
	}
	log.Printf("Updating game state to %#v", game.State)
	count, err := db.Update(game)
	if err != nil || count == 0 {
		log.Printf("Unable to change game state: %v", err)
		return err
	}
	niceBoard, err := board.getBoard()
	if err != nil {
		log.Printf("Error getting board: %#v", board)
		return err
	}
	log.Printf("Sending state %v to all players", msg["state"])
	gs.Broadcast(gameId, Message{
		"type":  "update",
		"board": niceBoard,
		"state": "start",
	})
	log.Printf("Updating UI")
	ws.WriteJSON(Message{
		"type":  "update",
		"board": niceBoard,
		"state": "start",
	})
	return nil
}
Ejemplo n.º 8
0
func ProductsCreate(product models.Product, db *gorp.DbMap, render render.Render) {
	err := db.Insert(&product)
	if err == nil {
		render.JSON(201, &product)
	} else {
		render.JSON(422, map[string]string{"error": err.Error()})
	}
}
Ejemplo n.º 9
0
func MustCreateAccount(dbmap *gorp.DbMap, email string) *rr.Account {
	account := rr.NewAccount(email)
	err := dbmap.Insert(account)
	if err != nil {
		panic(err.Error())
	}
	return account
}
Ejemplo n.º 10
0
func (r Rate) Create(Db *gorp.DbMap, itemType int64, itemId int64) Rate {
	rn := r.GetRate(Db, itemType, itemId)
	if rn.Id == 0 {
		r.ItemId = itemId
		r.ItemType = itemType
		Db.Insert(&r)
	}
	return r
}
Ejemplo n.º 11
0
func AddToIndex(db *gorp.DbMap, keys []string, itemtype string, itemid int64) error {
	i := SearchIndex{
		Type:   itemtype,
		ItemId: itemid,
		Weight: 0,
		Keys:   strings.Join(keys, " "),
	}
	return db.Insert(&i)
}
Ejemplo n.º 12
0
func AddTask(r render.Render, taskPayload Task, db *gorp.DbMap) {
	err := db.Insert(&taskPayload)
	if err != nil {
		log.Printf("Error inserting: %v", err)
		r.JSON(400, map[string]string{"message": "failed inserting task"})
		return
	}
	r.JSON(201, taskPayload)
}
Ejemplo n.º 13
0
func PlayerInit(playerId int, gameId string, gs GameService, ws *websocket.Conn, db *gorp.DbMap) error {
	log.Printf("Player is connected: %#v", playerId)

	game, _, err := gs.GetGame(db, gameId, playerId)
	if err != nil {
		log.Printf("Couldn't get player and/or game")
		return err
	}

	if game.State == "start" {
		log.Printf("Player %#v rejoining game in play", playerId)
		board, err := getBoard(gameId, db)
		if err != nil {
			log.Printf("Can't get TTT board: %#v", err)
			return err
		}

		log.Printf("Got board, getting nicer one: %#v", board)
		niceBoard, err := board.getBoard()
		if err != nil {
			log.Printf("Unable to get nice board: %#v", err)
			return err
		}
		log.Printf("Got board for player %#v: %#v", playerId, board)

		// There may not be a board yet so just try and send it
		ws.WriteJSON(Message{
			"type":  "update",
			"state": game.State,
			"board": niceBoard,
		})
	} else {
		ws.WriteJSON(Message{
			"type":  "update",
			"state": game.State,
			"board": nil,
		})
	}

	// check to make sure this player has a turn row
	turn := TicTacToe_Turn{}
	err = db.SelectOne(&turn, "select * from tictactoe_turn where game=? and player=?", gameId, playerId)
	if err != nil {
		turn.Game = gameId
		turn.Player = playerId
		turn.Move = -1
		err = db.Insert(&turn)
		if err != nil {
			log.Printf("Unable to insert initial turn row: %#v", err)
			return err
		}
	}

	gs.SendHost(gameId, Message{"type": "join"})
	return nil
}
Ejemplo n.º 14
0
func CreateAddr(db *gorp.DbMap, addr string) Address {
	var a Address
	var err error
	a, err = GetAddr(db, addr)
	if err != nil && err.Error() == ErrorNotFound {
		a.RawText = addr
		db.Insert(&a)
	}
	return a
}
Ejemplo n.º 15
0
func ProductsBulkCreate(products models.Products, db *gorp.DbMap, render render.Render) {
	for _, product := range products.Collection {
		err := db.Insert(&product)
		if err != nil {
			panic(err)
		}
	}

	render.JSON(201, products)
}
Ejemplo n.º 16
0
func CreateStore(db *gorp.DbMap, title, website string) (Store, error) {
	t := time.Now().UnixNano()
	var s = Store{
		Title:   title,
		Website: website,
		Created: t,
		Updated: t,
	}
	err := db.Insert(&s)
	return s, err
}
Ejemplo n.º 17
0
func CreateDelivery(db *gorp.DbMap, title string, price float64) (OrderDelivery,
	error) {
	t := time.Now().UnixNano()
	o := OrderDelivery{
		Title:   title,
		Price:   price,
		Created: t,
		Updated: t,
	}
	err := db.Insert(&o)
	return o, err
}
Ejemplo n.º 18
0
func CreateComment(db *gorp.DbMap, itemid int64, itemtype string, comment []byte,
	userid int64, anon bool) (Comment, error) {
	c := Comment{
		Created:   time.Now().UnixNano(),
		ItemId:    itemid,
		ItemType:  itemtype,
		UserId:    userid,
		Anonymous: anon,
		Val:       comment,
	}
	err := db.Insert(&c)
	return c, err
}
Ejemplo n.º 19
0
func PostersCreate(db *gorp.DbMap, p Poster) (Poster, error) {
	fslug := ""
	if p.ShortTitle != "" {
		fslug = p.ShortTitle
	} else {
		fslug = p.Title
	}
	p.Slug = getSlug(db, fslug)
	t := time.Now()
	p.Created = t.UnixNano()
	err := db.Insert(&p)
	return p, err
}
Ejemplo n.º 20
0
func StartDBWriter(post_channel chan *Post, dbmap *gorp.DbMap) {
	go func() {
		for msg := range post_channel {
			err := dbmap.Insert(msg)
			if err != nil {
				fmt.Println(err)
				log.Fatalln("no insert")
			}
			//build_client.Go("BuildServer.Build", 1, 1, nil)
			//msg.WriteToDB(reflect.ValueOf(msg))
		}
	}()
}
Ejemplo n.º 21
0
func SentenceCreate(ren render.Render, req *http.Request, dbmap *gorp.DbMap, usr User) {
	sentence := newSentence(usr, req.FormValue("text"), req.FormValue("url"))
	_, err := sentence.Validate()

	if err != nil {
		msg := make(map[string]string)
		msg["error"] = err.Error()
		ren.JSON(400, msg)
	} else {
		err = dbmap.Insert(&sentence)
		PanicIf(err)
		ren.JSON(200, sentence)
	}
}
Ejemplo n.º 22
0
Archivo: jail.go Proyecto: virtbsd/jail
func (jail *Jail) Persist(db *gorp.DbMap) error {
	insert := false

	if len(jail.UUID) == 0 {
		insert = true
		count := 0

		db.Select(&count, "select count(UUID) from Jail where Name = ?", jail.Name)
		if count > 0 {
			return fmt.Errorf("Jail with name %s already exists", jail.Name)
		}
	}

	if err := jail.Validate(); err != nil {
		return err
	}

	if insert {
		db.Insert(jail)
	} else {
		db.Update(jail)
	}

	for _, device := range jail.NetworkDevices {
		device.VmUUID = jail.UUID
		if err := device.Persist(db, jail); err != nil {
			return err
		}
	}

	for _, mount := range jail.Mounts {
		if mount.MountPointID == 0 {
			mount.JailUUID = jail.UUID
			db.Insert(mount)
		} else {
			db.Update(mount)
		}
	}

	for _, option := range jail.Options {
		if option.OptionID == 0 {
			option.JailUUID = jail.UUID
			db.Insert(option)
		} else {
			db.Update(option)
		}
	}

	for _, route := range jail.Routes {
		if route.RouteID == 0 {
			route.VmUUID = jail.UUID
			db.Insert(route)
		} else {
			db.Update(route)
		}
	}

	return nil
}
Ejemplo n.º 23
0
func CreateProduct(db *gorp.DbMap, storeid, ownproductid, imgid int64,
	price float64, title string) (StoreProduct, error) {
	t := time.Now().UnixNano()
	b := StoreProduct{
		StoreId:   storeid,
		ProductId: ownproductid,
		Price:     price,
		ImgId:     imgid,
		Title:     title,
		Created:   t,
		Updated:   t,
	}
	err := db.Insert(&b)
	return b, err
}
Ejemplo n.º 24
0
func generateConfirmation(db *gorp.DbMap, userid int64) (UserConfirmation,
	error) {
	b, err := rand.Int(rand.Reader, big.NewInt(int64(8999)))
	if err != nil {
		return UserConfirmation{}, err
	}
	code := 1000 + b.Int64()
	res := UserConfirmation{UserId: userid, Code: code, Created: time.Now().
		UnixNano()}
	err = db.Insert(&res)
	if err != nil {
		return UserConfirmation{}, err
	}
	return res, nil
}
Ejemplo n.º 25
0
func CreatePost(post models.Post, r render.Render, dbmap *gorp.DbMap) {
	log.Printf("%#v", post)

	err := dbmap.Insert(&post)
	if err != nil {
		log.Fatal("Something went wrong", err)
		jsonError := &models.JSONError{
			Error: "err",
		}

		r.JSON(404, jsonError)
	} else {
		r.JSON(200, post)
	}
}
Ejemplo n.º 26
0
func VisitPage(Db *gorp.DbMap, fullurl string, body []byte, code int) error {
	res := SitePage{}
	var err error

	fullurl = n(fullurl)
	u, _ := url.Parse(fullurl)

	if !IsExistSite(Db, fullurl) {
		_, err = AddSite(Db, fullurl)
		if err != nil {
			return err
		}
	}

	if !IsExistPage(Db, fullurl) {
		res.Url = u.RequestURI()
		res.Error = int64(code)
		res.Body = gz.Gz(string(body))
		res.Visited = time.Now().UnixNano()

		site, err := GetSite(Db, fullurl)
		if err != nil {
			return err
		}
		res.SiteId = site.Id

		err = Db.Insert(&res)
		if err != nil {
			return err
		}

		return nil

	} else {
		res, err = GetPage(Db, fullurl)
		if err != nil {
			return err
		}
	}

	res.Error = int64(code)
	res.Body = gz.Gz(string(body))
	res.Visited = time.Now().UnixNano()

	_, err = Db.Update(&res)

	return err
}
Ejemplo n.º 27
0
func (gs *GameServiceImpl) ConnectToGame(db *gorp.DbMap, gameId string, playerObj interface{}) (*Game, *Player, error) {
	obj, err := db.Get(Game{}, gameId)
	if err != nil {
		return nil, nil, err
	}
	if obj == nil {
		return nil, nil, errors.New("Player not saved to session")
	}
	game := obj.(*Game)

	var player *Player
	if playerObj == nil { // no, it's a new player
		player = &Player{
			Game: game.Id,
		}

		// save to db so we can find them if they disconnect
		err = db.Insert(player)
		if err != nil {
			return nil, nil, err
		}
	} else { // player is rejoining
		playerObj, err := db.Get(Player{}, playerObj)
		if err != nil {
			return nil, nil, err
		}
		player = playerObj.(*Player)
		// TODO: this would screw with any games they are currently already in?
		if player.Game != game.Id {
			player.Game = game.Id
			count, err := db.Update(player)
			if count == 0 {
				return nil, nil, errors.New("Player update effected 0 rows")
			}
			if err != nil {
				return nil, nil, err
			}
			log.Printf("Joining player id is: %#v", player.Id)
		} else {
			log.Printf("Returning player id is: %#v", player.Id)
		}
	}

	return game, player, nil
}
Ejemplo n.º 28
0
func Create(db *gorp.DbMap, c ChangeLog) (ChangeLog, error) {
	c.Slug = chpu.Chpu(c.Title)
	for {
		id, _ := db.SelectInt("select Id from ChangeLog where Slug = ?", c.Slug)
		if id != 0 {
			c.Slug = strinc.Inc(c.Slug)
		} else {
			break
		}
	}
	r := rate.Rate{}

	t := time.Now().UTC()
	c.Created = t.UnixNano()
	err := db.Insert(&c)
	r.Create(db, 6, c.Id)
	return c, err
}
Ejemplo n.º 29
0
func PostGoods(r render.Render, dbmap *gorp.DbMap, res http.ResponseWriter, g GoodInfo, e binding.Errors) {
	if e != nil {
		r.JSON(http.StatusBadRequest, map[string]string{"message": e[0].Message})
		return
	}

	//check user exists yet or not?
	var count int64
	//count,err := dbmap.SelectInt("SELECT count(*) FROM ORDERS WHERE O_ID=?",o.Id)
	row, err := dbmap.Db.Query("SELECT count(*) FROM GOODS WHERE G_ID=?", g.Id)
	if err != nil {
		glog.V(1).Infof("[DEBUG:] Search goods by id:%v fail:%v", g.Id, err)
		r.JSON(http.StatusConflict, map[string]string{"message": "DB ERROR"})
		return
	}
	defer row.Close()

	row.Next()
	err = row.Scan(&count)
	if err != nil {
		glog.V(2).Infof("Scan fail:", err.Error())
	}
	//glog.V(2).Infof("Count = %v", count)

	if count > 0 {
		glog.V(1).Infof("Goods with tel:%v exists yet", g.Id)
		r.JSON(http.StatusConflict, map[string]string{"message": "Order with same Id exists"})
		return
	}

	g.CreateTime = NullTime{Time: time.Now(), Valid: true}
	g.UpdateTime = NullTime{Time: time.Now(), Valid: true}

	//insert new user info to db;
	err = dbmap.Insert(&g)
	if err != nil {
		glog.V(1).Infof("[DEBUG:] Insert Goods %v fail:%v", g, err)
		r.JSON(http.StatusConflict, map[string]string{"message": "DB ERROR"})
		return
	}

	r.JSON(200, map[string]string{"message": "SUCCESS"})
}
Ejemplo n.º 30
0
func (r Rate) Vote(Db *gorp.DbMap, v string, u int64) (Rate, error) {
	var el int64
	if r.Id == 0 {
		return Rate{}, errors.New("Rate not found")
	}
	r = r.GetRate(Db, r.ItemType, r.ItemId)
	id, err := Db.SelectInt("select RateId from Vote where RateId = ? and"+
		" UserId = ?", r.Id, u)
	if err != nil {
		return Rate{}, err
	}
	if id != 0 {
		return Rate{}, errors.New("You have already voted")
	}
	switch v {
	case "a":
		el = -1
		r.Against++
		Db.Exec("update Rate set Against = Against+1 where Id = ?", r)
		break
	case "b":
		el = 1
		r.Behind++
		Db.Exec("update Rate set Behind = Behind+1 where Id = ?", r)
		break
	default:
		return Rate{}, errors.New("Vote election undefined")
	}

	r.Rate = WilsonSum(r.Behind-r.Against, r.Against+r.Behind)

	vote := Vote{
		RateId: r.Id,

		Value:  el,
		UserId: u,
	}

	Db.Update(&r)
	Db.Insert(&vote)
	return r, nil
}