Ejemplo n.º 1
0
func (r Rate) GetRateById(Db *gorp.DbMap, id int64) Rate {
	Db.SelectOne(&r, "select * from Rate where Id = ?", id)
	if r.Id != 0 {
		r.Votes = r.GetVotes(Db)
	}
	return r
}
Ejemplo n.º 2
0
func UserGet(ren render.Render, params martini.Params, dbmap *gorp.DbMap, s sessions.Session) {
	var usr User
	log.Println(params)
	err := dbmap.SelectOne(&usr, "SELECT * from users WHERE id = $1", s.Get("userId"))
	PanicIf(err)
	ren.JSON(200, usr)
}
Ejemplo n.º 3
0
func FindArticleWithReadReceipts(dbmap *gorp.DbMap, id int64) (*Article, error) {
	var a Article
	err := dbmap.SelectOne(&a, "select * from articles where id = $1", id)
	a.AddReadReceipts(dbmap)

	return &a, err
}
Ejemplo n.º 4
0
func GetBySlug(db *gorp.DbMap, slug string) (WikiPage, bool) {
	w := WikiPage{}
	err := db.SelectOne(&w, "select * from WikiPage where Title = ?", slug)
	if err != nil {
		return w, false
	}
	return w, true
}
Ejemplo n.º 5
0
func (r Rate) GetRate(Db *gorp.DbMap, itemType int64, itemId int64) Rate {
	if r.Id != 0 {
		return r
	}
	Db.SelectOne(&r, "select * from Rate where ItemId = ? and ItemType = ?",
		itemId, itemType)
	r.Votes = r.GetVotes(Db)
	return r
}
Ejemplo n.º 6
0
func CheckPhone(db *gorp.DbMap, phone string) (User, error) {
	var user = User{}
	db.SelectOne(&user, "select * from User where Phone = ? limit 1",
		phone)
	if user.Id != 0 {
		return user, errors.New("User found")
	}
	return user, nil
}
Ejemplo n.º 7
0
func GetAddr(db *gorp.DbMap, addr string) (Address, error) {
	var a Address
	var err error
	db.SelectOne(&a, "select * from Address where RawText = ?", addr)
	if a.Id == 0 || a.RawText == "" {
		err = errors.New(ErrorNotFound)
	}
	return a, err
}
Ejemplo n.º 8
0
func GetAddrById(db *gorp.DbMap, id int64) (Address, error) {
	var a Address
	var err error
	db.SelectOne(&a, "select * from Address where Id = ?", id)
	if a.Id == 0 || a.RawText == "" {
		err = errors.New(ErrorNotFound)
	}
	return a, err
}
Ejemplo n.º 9
0
func GetGoodsById(gid string, dbmap *gorp.DbMap) (GoodInfo, error) {
	var ginfo GoodInfo
	err := dbmap.SelectOne(&ginfo, "SELECT * FROM GOODS WHERE G_ID=?", gid)
	if err != nil {
		glog.V(1).Infof("[DEBUG:] Search goods by id:%v fail:%v", gid, err)
		return ginfo, err
	}
	return ginfo, nil
}
Ejemplo n.º 10
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
}
func Authenticate(user *User, dbmap *gorp.DbMap) bool {
	var db_user User
	err := dbmap.SelectOne(&db_user, "SELECT * FROM CUSTOMER WHERE CUS_TEL=?", user.PhoneNumber)
	//count,err := dbmap.SelectInt("SELECT count(*) FROM CUSTOMER WHERE CUS_TEL=?",user.PhoneNumber)
	if err != nil {
		return false
	}
	glog.V(4).Infof("User Info:%v", db_user)
	return user.Password == db_user.Password
}
Ejemplo n.º 12
0
func (ph *Station) GetNearestStation(dbMap *gorp.DbMap, latitudeF, longitudeF float64) error {
	latitude := strconv.FormatFloat(latitudeF, 'f', 6, 64)
	longitude := strconv.FormatFloat(longitudeF, 'f', 6, 64)
	err := dbMap.SelectOne(ph, "SELECT * FROM station_info WHERE ( 3959 * acos( cos( radians('"+latitude+"') ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians('"+longitude+"') ) + sin( radians('"+latitude+"') ) * sin( radians( latitude ) ) ) )  < '300' ORDER BY ( 3959 * acos( cos( radians('"+latitude+"') ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians('"+longitude+"') ) + sin( radians('"+latitude+"') ) * sin( radians( latitude ) ) ) ) ASC LIMIT 0, 1")
	// err = dbMap.SelectOne(ph, "SELECT * FROM station_info WHERE station_code = ?", 2)
	if err != nil {
		return err
	}
	return nil
}
Ejemplo n.º 13
0
func MustGet(db *gorp.DbMap, name string) (Tag, bool) {
	t := Tag{}
	exist := false
	if tagExist(db, name) {
		db.SelectOne(&t, "select * from Tag where Title = ?", name)
		exist = true
	} else {
		t, _ = createTag(db, Tag{Title: name})
	}
	return t, exist
}
Ejemplo n.º 14
0
func getStationDetails(dbMap *gorp.DbMap, code string) PathReturnFormat {
	var station model.Station
	err := dbMap.SelectOne(&station, "SELECT * FROM station_info WHERE station_code = ?", code)
	if err != nil {
		fmt.Println("error retreiving station info")
	}
	var pathReturnFormat PathReturnFormat
	pathReturnFormat.Lat = station.Latitude
	pathReturnFormat.Long = station.Longitude
	pathReturnFormat.Name = station.StationName
	return pathReturnFormat
}
Ejemplo n.º 15
0
func Login(r *http.Request, render render.Render, db *gorp.DbMap, s sessions.Session) {
	user := User{}
	email, password := r.FormValue("email"), r.FormValue("password")
	err := db.SelectOne(&user, "Select * from users where email=? ", email)
	//tmp_pass, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	//err := db.QueryRow("select id, password from users where email=$1", email).Scan(&userId, &dbPasswd)
	if err != nil || bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)) != nil {
		render.HTML(400, "404", "")
	}
	s.Set("userId", user.Id)
	render.HTML(200, "dashboard", "")
}
Ejemplo n.º 16
0
func RequireLogin(ren render.Render, req *http.Request, s sessions.Session, dbmap *gorp.DbMap, c martini.Context) {

	var usr User
	err := dbmap.SelectOne(&usr, "SELECT * from users WHERE id = $1", s.Get("userId"))

	if err != nil {
		ren.JSON(http.StatusForbidden, nil)
		return
	}

	c.Map(usr)
}
Ejemplo n.º 17
0
func GetUser(r render.Render, dbmap *gorp.DbMap, params martini.Params, res http.ResponseWriter) {
	tel := params["tel"]
	//get userinfo
	var u User
	err := dbmap.SelectOne(&u, "SELECT * FROM CUSTOMER WHERE CUS_TEL=?", tel)
	//err := db.QueryRow("SELECT CUS_NAME,CUS_ADDR,CUS_EMAIL,CUS_TEL,CUS_PW FROM CUSTOMER WHERE CUS_TEL=?",tel).Scan(&u.Name,&u.Address,&u.Email,&u.PhoneNumber,&u.Password)
	if err != nil {
		glog.V(1).Infof("[DEBUG:] Search customer by tel:%v fail:%v", tel, err)
		r.JSON(http.StatusConflict, map[string]string{"message": "DB ERROR"})
		return
	}
	r.JSON(200, u)
}
Ejemplo n.º 18
0
func PostLogin(req *http.Request, dbmap *gorp.DbMap, s sessions.Session) (int, string) {
	var userId string

	email, password := req.FormValue("email"), req.FormValue("password")
	err := dbmap.SelectOne(&userId, "select id from users where email=$1 and password=$2", email, Md5(password))

	if err != nil {
		return 401, "Unauthorized"
	}

	s.Set("userId", userId)

	return 200, "User id is " + userId
}
Ejemplo n.º 19
0
func GetPost(args martini.Params, r render.Render, dbmap *gorp.DbMap) {
	var post models.Post

	err := dbmap.SelectOne(&post, "SELECT * FROM posts WHERE id = ?", args["id"])

	if err != nil {
		jsonError := &models.JSONError{
			Error: "Post not found",
		}

		r.JSON(404, jsonError)
	} else {
		r.JSON(200, post)
	}
}
Ejemplo n.º 20
0
func GetSite(Db *gorp.DbMap, fullurl string) (Site, error) {
	fullurl = n(fullurl)
	w := Site{}
	u, _ := url.Parse(fullurl)
	err := Db.SelectOne(&w, "select * from Site where Domain="+
		" ?", u.Host)
	if err != nil {
		fmt.Println(err)
		return w, err
	}
	if w.Id == 0 {
		fmt.Println("Site not exist")
		return w, errors.New("not exist")
	}
	return w, nil
}
Ejemplo n.º 21
0
func GetPage(Db *gorp.DbMap, fullurl string) (SitePage, error) {
	fullurl = n(fullurl)
	w := SitePage{}
	u, _ := url.Parse(fullurl)

	err := Db.SelectOne(&w, "select * from SitePage where SiteId"+
		" in (select Id from Site where Domain = ?) and Url = ?",
		u.Host, u.RequestURI())
	if err != nil || w.Url == "" {
		fmt.Println(err)
		return w, errors.New("not exist")
	}
	w.Url = fullurl

	return w, nil
}
Ejemplo n.º 22
0
func (u *User) Confirm(db *gorp.DbMap, code int64, userid int64) error {
	var uc = UserConfirmation{}
	err := db.SelectOne(&uc, "select * from UserConfirmation where UserId = ? and Code = ?"+
		" and Tried = 0 and Created > ?", userid, code, time.Now().Truncate(5*
		time.Minute).UnixNano())
	if err != nil {
		return err
	}
	if uc.Id == 0 {
		return errors.New("Confirmation not found")
	}
	u.Registered = true
	_, err = db.Update(u)
	if err != nil {
		return err
	}
	return nil
}
Ejemplo n.º 23
0
func (u *User) CheckLogin(db *gorp.DbMap, login string) (User, error) {
	var user = User{}
	ph, _ := phone.Normalize(login)
	if ph == "" {
		ph = login
	}
	if login == "" {
		return user, errors.New("User not found")
	}
	err := db.SelectOne(&user, "select * from User where Phone = ? or Email = ?"+
		" or NickName = ? limit 1", ph, login, login)
	if err != nil {
		return user, errors.New("User not found")
	}
	if user.Id == 0 {
		return user, errors.New("User not found")
	}
	return user, nil
}
Ejemplo n.º 24
0
func playerMove(msg Message, gameId string, playerId int, gs GameService, ws *websocket.Conn, db *gorp.DbMap, log *log.Logger) error {
	log.Printf("Sending move to host")
	turn := TicTacToe_Turn{}
	err := db.SelectOne(&turn, "select * from tictactoe_turn where game=? and player=?", gameId, playerId)
	if err != nil {
		log.Printf("Unable to get turn in move: %#v", err)
		return err
	}

	// the player move comes as an integer from [0-8] representing the location of the move
	// TODO: assert this is the case before saving
	turn.Move = int(msg["move"].(float64))
	_, err = db.Update(&turn)
	if err != nil {
		log.Printf("Failed to update moving player: %#v", err)
		return err
	}

	// send notice to the host that we've moved so it can attempt to resolve the current round
	gs.SendHost(gameId, msg)
	return nil
}
Ejemplo n.º 25
0
func GetGeoObject(db *gorp.DbMap, slug string) (*GeoObject, error) {
	g := new(GeoObject)
	err := db.SelectOne(g, "select * from GeoObject where Slug = ?", slug)
	return g, err
}
Ejemplo n.º 26
0
// helpers
func getBoard(gameId string, db *gorp.DbMap) (*TicTacToe_Board, error) {
	board := &TicTacToe_Board{}
	err := db.SelectOne(board, "select * from tictactoe_board where game=?", gameId)
	return board, err
}
Ejemplo n.º 27
0
func hostMove(msg Message, gameId string, playerId int, gs GameService, ws *websocket.Conn, db *gorp.DbMap, log *log.Logger) error {
	log.Printf("Checking player move")

	var players []*Player
	_, err := db.Select(&players, "select * from players where game=?", gameId)
	if err != nil {
		log.Printf("Failed to select players during move for game %v", gameId)
		return err
	}

	resolveRound := true
	for _, p := range players {
		if p.Role == Host {
			continue
		}
		turn := TicTacToe_Turn{}
		err = db.SelectOne(&turn, "select * from tictactoe_turn where game=? and player=?", gameId, p.Id)
		if err != nil {
			log.Printf("Couldn't get turn %#v", err)
			return err
		}

		if turn.Move == -1 {
			resolveRound = false
		}
	}
	if !resolveRound {
		log.Printf("Round cannot be resolved")
		return nil // not an error, just nothing to do
	}

	board, err := getBoard(gameId, db)
	if err != nil {
		log.Printf("Couldn't get board: %#v", err)
		return err
	}

	// all players have set their moves, update the board
	thisRound := []int{0, 0, 0, 0, 0, 0, 0, 0, 0}
	for _, p := range players {
		if p.Role == Host {
			continue
		}
		turn := TicTacToe_Turn{}
		err = db.SelectOne(&turn, "select * from tictactoe_turn where game=? and player=?", gameId, p.Id)
		if err != nil {
			log.Printf("Couldn't get turn %#v", err)
			return err
		}
		if thisRound[turn.Move] == 0 {
			thisRound[turn.Move] = p.Id
		} else {
			thisRound[turn.Move] = 0 // two players went in the same spot
		}
	}
	niceBoard, err := board.getBoard()
	if err != nil {
		log.Printf("Error getting board: %#v", err)
		return err
	}
	for i, v := range niceBoard {
		if v == 0 {
			niceBoard[i] = thisRound[i]
		}
	}

	board.setBoard(niceBoard)
	count, err := db.Update(board)
	if err != nil || count == 0 {
		log.Printf("Unable to save board after move: %v", err)
		return err
	}
	for _, p := range players {
		if p.Role == Host {
			continue
		}
		turn := TicTacToe_Turn{}
		err = db.SelectOne(&turn, "select * from tictactoe_turn where game=? and player=?", gameId, p.Id)
		if err != nil {
			log.Printf("Couldn't get turn %#v", err)
			return err
		}
		turn.Move = -1
		log.Printf("Resetting player %v turn", p.Id)
		count, err := db.Update(&turn)
		if count == 0 || err != nil {
			log.Printf("Failed to update player turn: %#v -- %#v", err, p.Id)
			return err
		}
	}
	gs.Broadcast(gameId, Message{
		"type":  "update",
		"board": niceBoard,
		"state": "start",
	})
	ws.WriteJSON(Message{
		"type":  "update",
		"board": niceBoard,
		"state": "start",
	})
	return nil
}
Ejemplo n.º 28
0
func PostersGetBySlug(db *gorp.DbMap, slug string) (Poster, error) {
	var p Poster
	err := db.SelectOne(&p, "select * from Poster where Slug = ?", slug)
	return p, err
}
Ejemplo n.º 29
0
func GetBySlug(db *gorp.DbMap, slug string) (ChangeLog, error) {
	var res ChangeLog
	err := db.SelectOne(&res, "select * from ChangeLog where Slug = ?", slug)
	res.Rate = res.Rate.GetRate(db, 6, res.Id)
	return res, err
}
Ejemplo n.º 30
0
func Get(db *gorp.DbMap, id int64) (ChangeLog, error) {
	var res ChangeLog
	err := db.SelectOne(&res, "select * from ChangeLog where Id = ?", id)
	res.Rate = res.Rate.GetRate(db, 6, res.Id)
	return res, err
}