func Get(UUID gocql.UUID) (*Fields, error) { var err error uuid := UUID.String() mutex.RLock() m, ok := Models[uuid] mutex.RUnlock() if !ok { m, err = Load(UUID) if err != nil { return nil, err } if m == nil { return nil, nil } mutex.Lock() m2, ok := Models[uuid] if ok { mutex.Unlock() return m2, nil } Models[uuid] = m mutex.Unlock() m.Update(model.Fields{ "IsLock": true, "LockServerUUID": LockServerUUID, }) } return m, nil }
func fuuidFunc(u gocql.UUID) string { if u == zeroUuid { return "" } else { return u.String() } }
func (querier Querier) QueryForPosts(subName string) ([]*Post, error) { var id gocql.UUID var title string var upvotes int var downvotes int var commentCount int var createdAt time.Time var updatedAt time.Time var posts []*Post iter := querier.Session.Query(`SELECT id, title, upvotes, downvotes, created_at, updated_at, comment_count FROM posts WHERE sub_id = ?`, subName).Iter() for iter.Scan(&id, &title, &upvotes, &downvotes, &createdAt, &updatedAt, &commentCount) { posts = append(posts, &Post{ id.String(), title, "", "", "", subName, upvotes, downvotes, commentCount, createdAt, updatedAt, }) } return posts, nil }
func Get(UUID gocql.UUID) *Server { s := &Server{UUID: UUID, Exists: false} var row = map[string]interface{}{} var uuid = UUID.String() if err := CQLSession.Query(`SELECT * FROM servers where server_uuid = ?`, uuid).MapScan(row); err != nil { if err != gocql.ErrNotFound { logger.Error(errors.New(err)) } return s } s.Exists = true s.IP = row["ip"].(string) s.Port = uint16(row["port"].(int)) t := time.Now().Unix() if t-row["live_ts"].(int64) > 10 { s.Exists = false } return s }
func (b *Fields) NCBuildingUpdate(uuid *gocql.UUID) string { return fmt.Sprintf(`{"command":"nc_building_update","planet_uuid":"%s","building":{"uuid":"%s","type":"%s","level":%d,"turn_on":%v,"x":%v,"y":%v,"upgrade_in_progress":%v,"upgrade_duration":%v,"upgrade_elapsed":%v}}`, uuid.String(), b.UUID.String(), b.Type, b.Level, b.TurnOn, b.X, b.Y, b.UpgradeInProgress, b.UpgradeDuration, b.UpgradeElapsed) }
func GetServer(serverUUID gocql.UUID) *Server { // todo: add mutex server, ok := servers[serverUUID.String()] if !ok { server = NewServer(serverUUID) if server == nil { return nil } servers[serverUUID.String()] = server } return server }
func (querier *Querier) GetPost(postID string) (*Post, error) { var id gocql.UUID var comment, title, link, sub string var upvotes int var downvotes int var commentCount int var createdAt time.Time var updatedAt time.Time if err := querier.Session.Query(`SELECT id, title, link, sub_id, comment, upvotes, downvotes, comment_count, created_at, updated_at FROM posts WHERE id = ? LIMIT 1`, postID).Consistency(gocql.One).Scan(&id, &title, &link, &sub, &comment, &upvotes, &downvotes, &commentCount, &createdAt, &updatedAt); err != nil { log.Println(err) return nil, err } return &Post{id.String(), title, link, comment, "", sub, upvotes, downvotes, commentCount, updatedAt, createdAt}, nil }
func (querier Querier) GetSubs() ([]*Sub, error) { var id gocql.UUID var name string var subscribers int var createdAt time.Time var updatedAt time.Time var subs []*Sub iter := querier.Session.Query(`SELECT id, name, subscribers, created_at, updated_at FROM subs`).Iter() for iter.Scan(&id, &name, &subscribers, &createdAt, &updatedAt) { subs = append(subs, &Sub{ id.String(), name, subscribers, createdAt, updatedAt, }) } return subs, nil }
func (querier Querier) GetCommentsByPostID(postIDToQuery string) ([]*Comment, map[string]*Comment, map[string][]string, error) { var id gocql.UUID var idAsString string var content string var parentID string var upvotes int var downvotes int var updatedAt time.Time commentLookup := make(map[string]*Comment) childrenLookup := make(map[string][]string) var comments []*Comment startTime := time.Now() iter := querier.Session.Query(`SELECT id, parent_id, content, upvotes, downvotes, updated_at FROM comments WHERE post_id = ?`, postIDToQuery).Iter() elapsed := time.Since(startTime) log.Printf("Querying: elapsed %f milliseconds\n", elapsed.Seconds()*1000.0) startTime = time.Now() // Timing building the tree for iter.Scan(&id, &parentID, &content, &upvotes, &downvotes, &updatedAt) { idAsString = id.String() comment := &Comment{idAsString, parentID, content, upvotes, downvotes, time.Now(), updatedAt, nil} comments = append(comments, comment) commentLookup[idAsString] = comment } sort.Sort(UpvoteSorter(comments)) for _, node := range comments { childrenLookup[node.ParentID] = append(childrenLookup[node.ParentID], node.ID) } elapsed = time.Since(startTime) log.Printf("Building the tree: elapsed %f milliseconds\n", elapsed.Seconds()*1000.0) if err := iter.Close(); err != nil { return nil, nil, nil, err } return comments, commentLookup, childrenLookup, nil }
func login(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json; charset=utf-8") if r.Method == "POST" { r.ParseForm() login := r.Form["login"][0] password := password_hash((r.Form["password"][0])) var existed_login string var existed_cookie gocql.UUID var cookie gocql.UUID if err := session.Query("SELECT login FROM users WHERE login = ? and password = ?", login, password).Consistency(gocql.One).Scan(&existed_login); err != nil { fmt.Println(err) } if existed_login != "" { if err := session.Query("SELECT cookie FROM cookies WHERE login = ?", login).Consistency(gocql.One).Scan(&existed_cookie); err != nil { if err == gocql.ErrNotFound { cookie, _ = gocql.RandomUUID() if err := session.Query("INSERT INTO cookies (login, cookie) VALUES (?, ?)", login, cookie).Exec(); err != nil { w.WriteHeader(500) return } } else { w.WriteHeader(500) return } } else { cookie = existed_cookie } w.Header().Set("Set-Cookie", "sessionToken="+cookie.String()) fmt.Fprintf(w, "{\"error\":\"\"}\n") } else { w.WriteHeader(403) fmt.Fprintf(w, "{\"error\":\"User or password is wrong\"}\n") return } } else { w.WriteHeader(405) fmt.Fprintf(w, "{\"error\":\"Allowed methods: POST\"}\n") } }
func Get(modelName string, UUID gocql.UUID) interface{} { t, ok := Models[modelName] if !ok { return nil } o := (t.Get(UUID.String())).(*Model) // o = o.(*Model) if o == nil { o = (t.New()).(*Model) o.UUID = UUID o.Load() o.Lock() if !o.Exists { return nil } } return o }
func NewServer(serverUUID gocql.UUID) *Server { s := &Server{isLocal: false} e := model_server.Get(serverUUID) if !e.Exists { logger.String(fmt.Sprintf("server %s not found in storage", serverUUID.String())) return nil } path := fmt.Sprintf("http://%s:%d/ws", e.IP, e.Port) logger.String(fmt.Sprintf("connect to: %s", path)) u, err := url.Parse(path) if err != nil { logger.String(fmt.Sprintf("%v", err)) // return err return nil } rawConn, err := net.Dial("tcp", u.Host) if err != nil { logger.String(fmt.Sprintf("%v", err)) // return err return nil } wsHeaders := http.Header{ "Origin": {"http://local.host:80"}, // your milage may differ "Sec-WebSocket-Extensions": {"permessage-deflate; client_max_window_bits, x-webkit-deflate-frame"}, "User-Agent": {"spacecrfat-agent"}, } wsConn, _, err := websocket.NewClient(rawConn, u, wsHeaders, 4096, 4096) if err != nil { logger.String(fmt.Sprintf("%v", err)) // return fmt.Errorf("websocket.NewClient Error: %s\nResp:%+v", err, resp) return nil } s.ws = wsConn s.ws.SetWriteDeadline(time.Now().Add(10 * time.Second)) err = s.ws.WriteMessage(websocket.TextMessage, []byte(fmt.Sprintf(`{"command":"auth","server_uuid":"%s"}`, localServer.UUID.String()))) if err != nil { logger.String(fmt.Sprintf("%v", err)) return nil } _, message, err := s.ws.ReadMessage() // s.ws.ReadMessage() if err != nil { if err != io.EOF { logger.Error(errors.New(err)) } } smessage := string(message) logger.String(fmt.Sprintf("star auth answer: %v", smessage)) go s.Reading() go s.Pinger() return s }