Пример #1
1
func (svc *Service) SendRoomHistory(so socketio.Socket, uid, room string, last int) {
	v := svc.Rooms[room]
	k := room
	start := len(v.Messages) - last
	if last == 0 || start < 0 {
		start = 0
	}

	//send chat history
	history := "{\"history\":["
	for j := start; j < len(v.Messages); j++ {
		history += v.Messages[j].String()
		if j < len(v.Messages)-1 {
			history += ","
		}
	}
	history += "]}"

	h, _ := gabs.ParseJSON([]byte("{}"))
	m, _ := gabs.ParseJSON([]byte(history))

	h.SetP(m.Path("history").Data(), "history")
	h.SetP(k, "room")
	h.SetP(v.FriendlyName, "name")
	so.Emit("history", h.String())
}
Пример #2
0
func (svc *Service) JoinRoom(so socketio.Socket, uid string, room string) {
	v := svc.Rooms[room]
	k := room

	//check for permission
	_, ok := v.MemberUIDs[uid]
	if !ok {
		return
	}

	so.Join(k)

	jo, _ := gabs.ParseJSON([]byte("{}"))
	jo.SetP(v.MaxExpTime.String(), "maxexptime")
	jo.SetP(v.MinExpTime.String(), "minexptime")
	jo.SetP(k, "room")
	jo.SetP(v.FriendlyName, "name")

	so.Emit("join", jo.String())

	bc, _ := gabs.ParseJSON([]byte("{}"))
	bc.SetP(svc.Users[uid].Token.Path("nick").Data().(string), "nick")
	bc.SetP(uid, "uid")
	bc.SetP(k, "room")
	bc.SetP(v.FriendlyName, "name")
	so.BroadcastTo(k, "joined", bc.String())
}
Пример #3
0
func TestPutStatementWithConflictID(t *testing.T) {
	m := martini.Classic()

	sess, err := mgo.Dial(miscs.GlobalConfig.MongoDB.URL)
	defer sess.Close()
	if err != nil {
		t.Fatalf("%v", err)
	}
	c := New(sess)

	m.Put("/:user/:app/statements", c.StoreStatement)
	stmt1, err := gabs.ParseJSON([]byte(singleStatement01))
	if err != nil {
		t.Fatal(err)
	}
	stmt2, err := gabs.ParseJSON([]byte(singleStatement02))
	if err != nil {
		t.Fatal(err)
	}

	// set same ID
	statementID := uuid.NewV4().String()
	_, err = stmt1.SetP(statementID, "id")
	if err != nil {
		t.Fatal(err)
	}
	_, err = stmt2.SetP(statementID, "id")
	if err != nil {
		t.Fatal(err)
	}

	// 1
	resp := httptest.NewRecorder()
	req, _ := http.NewRequest("PUT",
		"/test/test/statements?statementId="+statementID,
		strings.NewReader(stmt1.String()),
	)
	req.Header.Add("X-Experience-API-Version", "1.0.2")

	m.ServeHTTP(resp, req)

	if got, expected := resp.Code, http.StatusNoContent; got != expected {
		t.Fatalf("Expected %v response code from put single statement; got %d", expected, got)
	}

	// 2
	resp = httptest.NewRecorder()
	req, _ = http.NewRequest("PUT",
		"/test/test/statements?statementId="+statementID,
		strings.NewReader(stmt2.String()),
	)
	req.Header.Add("X-Experience-API-Version", "1.0.2")

	m.ServeHTTP(resp, req)

	if got, expected := resp.Code, http.StatusConflict; got != expected {
		t.Fatalf("Expected %v response code from put single statement; got %d", expected, got)
	}
}
Пример #4
0
func testGetMultStatementOfGroup(t *testing.T, group *gabs.Container) {
	db := initDatabase(t)
	defer db.Close()
	mart := initHandler(db)

	ids := []string{
		uuid.NewV4().String(),
		uuid.NewV4().String(),
		uuid.NewV4().String(),
		uuid.NewV4().String(),
	}

	stmt, err := gabs.ParseJSON([]byte(statetmentAgentBoilerplate))
	fatalIfError(t, err)

	stmtSlice := []*gabs.Container{
		appendAccount(t, stmt),
		appendMbox(t, stmt),
		appendMboxSHA1(t, stmt),
		appendOpenID(t, stmt),
	}

	for i := 0; i < len(ids); i++ {
		putStatement(t, mart, stmtSlice[i].String(), ids[i])

		var s interface{}
		err = json.Unmarshal([]byte(stmtSlice[i].Search("actor").String()), &s)
		fatalIfError(t, err)
		err = group.ArrayAppendP(s, "actor.member")
		fatalIfError(t, err)
	}

	// construct query
	v := &url.Values{}
	//t.Log(group.Search("actor").String())
	v.Add("agent", group.Search("actor").String())

	resp := getStatement(t, mart, v)
	//t.Log(string(resp))
	respstmt, err := gabs.ParseJSON(resp)
	fatalIfError(t, err)
	cnt, err := respstmt.ArrayCount("statements")
	fatalIfError(t, err)

	if cnt != len(ids) {
		t.Fatalf("Expected %d statements in response; got %d", len(ids), cnt)
	}

	children, err := respstmt.S("statements").Children()
	fatalIfError(t, err)
	for idx, stm := range children {
		if id, ok := stm.Search("id").Data().(string); !ok || id != ids[idx] {
			t.Fatalf("Got invalid order of statement array")
		}
	}
}
Пример #5
0
func TestGetStatementWithCanonicalFormat(t *testing.T) {
	db := initDatabase(t)
	defer db.Close()
	mart := initHandler(db)

	id1 := uuid.NewV4().String()

	stmt, err := gabs.ParseJSON([]byte(singleStatementWithLangMap))
	fatalIfError(t, err)

	vsuffix := uuid.NewV4().String()
	verbID := "http://example.com/realglobe/XAPIprofile/test-" + vsuffix
	_, err = stmt.SetP(verbID, "verb.id")
	fatalIfError(t, err)

	putStatement(t, mart, stmt.String(), id1)

	// construct query
	v := &url.Values{}
	v.Add("verb", verbID)
	v.Add("format", "canonical")

	respstmt, err := gabs.ParseJSON(getStatement(t, mart, v))
	fatalIfError(t, err)
	cnt, err := respstmt.ArrayCount("statements")
	fatalIfError(t, err)

	if cnt != 1 {
		t.Fatalf("Expected 1 statements in response; got %d", cnt)
	}

	// check ID
	s0, err := respstmt.ArrayElement(0, "statements")
	fatalIfError(t, err)
	if id, ok := s0.Search("id").Data().(string); !ok || id != id1 {
		t.Fatalf("Got invalid statement")
	}

	// check LangMaps
	scale, err := s0.ArrayElement(0, "object", "definition", "scale")
	fatalIfError(t, err)
	if _, ok := scale.Search("description", "ja-JP").Data().(string); !ok {
		t.Fatalf("ja-JP field not found")
	}
	if _, ok := scale.Search("description", "en-US").Data().(string); ok {
		t.Fatalf("en-US field is in response (not removed)")
	}

	if _, ok := s0.Search("object", "definition", "description", "ja-JP").Data().(string); !ok {
		t.Fatalf("ja-JP field not found")
	}
	if _, ok := s0.Search("object", "definition", "description", "en-US").Data().(string); ok {
		t.Fatalf("en-US field is in response (not removed)")
	}
}
Пример #6
0
func testGetMultStatementWithRelatedAgents(t *testing.T, agent map[string]interface{}) {
	db := initDatabase(t)
	defer db.Close()
	mart := initHandler(db)

	id1 := uuid.NewV4().String()
	id2 := uuid.NewV4().String()

	stmt, err := gabs.ParseJSON([]byte(singleStatementWithMember))
	fatalIfError(t, err)

	dprefix := uuid.NewV4().String()
	mailto := "mailto:test.group@" + dprefix + ".realglobe.example.com"
	_, err = stmt.SetP(mailto, "actor.mbox")
	fatalIfError(t, err)

	actor, err := gabs.Consume(agent)
	fatalIfError(t, err)
	err = stmt.ArrayAppendP(actor.Data(), "actor.member")
	fatalIfError(t, err)

	putStatement(t, mart, stmt.String(), id1)
	putStatement(t, mart, stmt.String(), id2)

	// construct query
	v := &url.Values{}
	v.Add("agent", actor.String())
	v.Add("related_agents", "true")

	respstmt, err := gabs.ParseJSON(getStatement(t, mart, v))
	fatalIfError(t, err)
	cnt, err := respstmt.ArrayCount("statements")
	fatalIfError(t, err)

	if cnt != 2 {
		t.Fatalf("Expected 2 statements in response; got %d", cnt)
	}

	s0, err := respstmt.ArrayElement(0, "statements")
	fatalIfError(t, err)
	if id, ok := s0.Search("id").Data().(string); !ok || id != id1 {
		t.Fatalf("Got invalid order of statement array")
	}

	s1, err := respstmt.ArrayElement(1, "statements")
	fatalIfError(t, err)
	if id, ok := s1.Search("id").Data().(string); !ok || id != id2 {
		t.Fatalf("Got invalid order of statement array")
	}
}
Пример #7
0
func MachineSshKey(machine string) string {
	// StorePath has changed in docker-machine 0.5, switch accordingly.
	machineInfo, machineErr := RunMachineCommand("inspect", machine)
	if machineErr != nil {
		LogError(machineErr.Error())
	}

	infoJson, infoErr := gabs.ParseJSON([]byte(machineInfo))
	if infoErr != nil {
		LogError("could not load machine info from `docker-machine`.")
	}

	// Docker Machine 0.5.1 has a direct key.
	storepath, ok := infoJson.Path("Driver.Driver.SSHKeyPath").Data().(string)
	if ok {
		return storepath
	}

	// Docker Machine 0.5 has it in a sub-folder.
	storepath, ok = infoJson.Path("Driver.StorePath").Data().(string)
	if ok {
		return storepath + "/machines/" + infoJson.Path("Driver.MachineName").Data().(string) + "/id_rsa"
	}

	storepath, ok = infoJson.Path("StorePath").Data().(string)

	if !ok {
		LogError("could not determine SSH key path from `docker-machine`.")
	}

	return storepath + "/id_rsa"
}
Пример #8
0
func request(ip string, url string) (*gabs.Container, error) {
	var data *gabs.Container
	url = fmt.Sprintf(url, ip)

	resp, err := http.Get(url)
	if err != nil {
		return data, err
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return data, err
	}

	jsonbody, err := gabs.ParseJSON(body)
	if err != nil {
		fmt.Println(err.Error())
		fmt.Println("gets data is not JSON structure")
		fmt.Println(string(body))
		os.Exit(0)
		// return data, err
	}
	return jsonbody, nil
}
Пример #9
0
func (*ParserUnive) Parse() ([]Library, error) {
	url := "http://static.unive.it/sitows/index/personebiblioteche"

	res, err := http.Get(url)
	if err != nil {
		log.Fatal(err)
	}
	defer res.Body.Close()

	body, _ := ioutil.ReadAll(res.Body)
	json, _ := gabs.ParseJSON(body)
	children, _ := json.ChildrenMap()

	libraries := []Library{}
	for key, child := range children {
		takenPlaces, _ := strconv.Atoi(child.Search("persone").Data().(string))
		totalPlaces, _ := strconv.Atoi(child.Search("max").Data().(string))

		library := Library{
			MappingID:   key,
			TakenPlaces: takenPlaces,
			TotalPlaces: totalPlaces,
		}
		libraries = append(libraries, library)
	}

	return libraries, nil
}
Пример #10
0
func parseAnswear(answear string) {
	m := Main{}
	p := Parametr{}
	mainItem := make([]Item, 0)
	jsonParsed, err := gabs.ParseJSON([]byte(answear))
	if err != nil {
		return
	}
	p.parametr = jsonParsed.Search("main", "param", "param").Data().([]interface{})[0].(string)
	p.typeParametr = jsonParsed.Search("main", "param", "t").Data().([]interface{})[0].(string)

	//childreItem - items for key "i"

	childrenItem, _ := jsonParsed.Search("main", "i").Children()

	//children - array with main key "i"

	children := childrenItem[0]

	//resultChildren - final array with our keys "p","t","ti"

	resultChildren, _ := children.Children()
	var item Item
	for _, child := range resultChildren {
		item.parametr = child.Data().(map[string]interface{})["p"].(string)
		item.typeItem = child.Data().(map[string]interface{})["t"].(string)
		item.title = child.Data().(map[string]interface{})["ti"].(string)
		mainItem = append(mainItem, item)
	}
	m.items = mainItem
	m.parametr = p
	fmt.Println(m)
}
Пример #11
0
func jsonSocketWrapper(so socketio.Socket, checkUser bool, f soHandlerJSON) soHandler {
	return soHandler(func(msg string) {
		defer func() {
			if err := recover(); err != nil {
				const size = 64 << 10
				buf := make([]byte, size)
				buf = buf[:runtime.Stack(buf, false)]
				log.Printf("socket error %v: %s", err, buf)
			}
		}()

		g, err := gabs.ParseJSON([]byte(msg))
		if err != nil {
			log.Println(err)
			return
		}

		uid := ""
		ok := false
		if checkUser {
			uid, ok = service.ExtractAndCheckToken(so, g)
			if !ok {
				return
			}
			service.Users[uid].LastAct = time.Now()
		}

		f(uid, g)
	})
}
Пример #12
0
func NewSensor(wg sync.WaitGroup, sensor *MPSensor) {
	defer wg.Done()

	hkSwitch := GetHKSwitch(sensor)
	hkSwitch.ticker = time.NewTicker(30 * time.Second)

	for {
		<-hkSwitch.ticker.C

		log.Printf("[INFO] Updating %s", hkSwitch.accessory.Info.Name.GetValue())

		urlString := fmt.Sprintf("http://%s/sensors/%d", viper.GetString("Host"), hkSwitch.sensor.port)
		req, _ := newRequest("GET", urlString, nil)

		res, _ := client.Do(req)
		defer res.Body.Close()
		jsonBytes, _ := ioutil.ReadAll(res.Body)

		jsonParsed, _ := gabs.ParseJSON(jsonBytes)
		output := jsonParsed.Path("sensors").Index(0).Path("output").Data().(float64) != 0

		hkSwitch.sensor.output = output
		hkSwitch.accessory.Switch.On.SetValue(output)
	}
}
Пример #13
0
func Connect() {
	var wg sync.WaitGroup

	authenticate()

	urlString := fmt.Sprintf("http://%s/sensors", viper.GetString("Host"))
	req, _ := newRequest("GET", urlString, nil)

	res, _ := client.Do(req)
	defer res.Body.Close()
	jsonBytes, _ := ioutil.ReadAll(res.Body)

	jsonParsed, _ := gabs.ParseJSON(jsonBytes)
	children, _ := jsonParsed.Search("sensors").Children()
	wg.Add(len(children))
	for _, child := range children {
		port := uint8(child.Path("port").Data().(float64))
		output := child.Path("output").Data().(float64) != 0

		log.Printf("[INFO] Discovered Sensor %d", port)

		sensor := &MPSensor{port, output}
		go NewSensor(wg, sensor)
	}

	wg.Wait()
}
Пример #14
0
// The markup contains a JSON object with all the data for Bloomberg's page
// and it is all on one line, so here I split the markup up into lines,
// scan until find the one that has the variable in it, chop off the start
// of the line which leaves just the JSON object which I can then parse
// and extract the useful data from.
func (this bloomberg) makePrice(markup string) entities.Price {
	for _, line := range strings.Split(markup, "\n") {
		if strings.Index(line, "bootstrappedData: ") > -1 {
			jsonv := []byte(line[18:len(line)])
			jsonParsed, err := gabs.ParseJSON(jsonv)
			if err != nil {
				fmt.Fprintln(os.Stderr, "Could not parse the Bloomberg page: ", err)
				os.Exit(1)
			}
			children, ok := jsonParsed.Children()
			if ok != nil {
				fmt.Fprintln(os.Stderr, "Could not parse the Bloomberg page")
				os.Exit(1)
			}
			for _, child := range children {
				if !child.Exists("basicQuote", "price") {
					continue
				}
				price := child.Path("basicQuote.price").Data().(float64)
				date := child.Path("basicQuote.priceDate").Data().(string)
				parsedDate, _ := time.Parse("1/2/2006", date)
				timed := child.Path("basicQuote.priceTime").Data().(string)
				parsedTime, _ := time.Parse("3:04 PM", timed)
				newPrice := entities.NewPrice(parsedDate, parsedTime, string(this),
					strconv.FormatFloat(price, 'f', -1, 64),
				)
				return newPrice
			}
		}
	}
	return entities.Price{}
}
Пример #15
0
func init() {
	/* Initialise configuration instance, w/ GABS. */

	log.Debug("Initialise configuration instance")

	// This has to be a absolute path.
	configurationPath := os.Getenv("RESTAPI_CONFIG")

	// Ascertain if the configuration path is inputted.

	log.Debug("Testing if the configuration path is inputted.")
	if _, err := os.Stat(configurationPath); os.IsNotExist(err) {
		log.Crit("The configuration file does not exist!",
			log.Ctx{"File": configurationPath})
		os.Exit(1)
	}

	log.Debug("Reading configuration file into RAM.")
	configurationFile, err := ioutil.ReadFile(configurationPath)
	if err != nil {
		log.Error("The JSON config could not be loaded..",
			log.Ctx{"Error": err.Error()})
		os.Exit(1)
	}

	log.Debug("Parsing configuration file into a GABS instance.")
	config, err = gabs.ParseJSON(configurationFile)
	if err != nil {
		log.Error("The JSON config could not be parsed.",
			log.Ctx{"Error": err.Error()})
		os.Exit(1)
	}

	/* Finish initializing the configuration instance */
}
Пример #16
0
func hbuser(user string) {
	resp, err := http.Get("http://hummingbird.me/api/v1/users/" + user)
	if err != nil {
		message <- "Request Error"
	}
	defer resp.Body.Close()
	res, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		message <- "Request Error"
	}
	jsn, _ := gabs.ParseJSON(res)
	name := jsn.S("name").Data()
	if name == nil {
		name = "?"
	}
	life := jsn.S("life_spent_on_anime").Data()
	if life == nil {
		life = "0"
	}
	last := jsn.S("last_library_update").Data()
	if last == nil {
		last = "?"
	}

	message <- name.(string) + ": Time spent watching anime: " + strconv.FormatFloat(life.(float64)/60/24/30, 'f', 2, 64) + " months. Last Update: " + last.(string)
}
Пример #17
0
func pollMessage(queueUrl string) {
	sqsClient := sqs.New(&aws.Config{Region: aws.String("us-east-1")})

	req := &sqs.ReceiveMessageInput{QueueURL: aws.String(queueUrl)}

	result, err := sqsClient.ReceiveMessage(req)

	if nil != err {
		panic(err)
	} else {
		parsedResponse, err := gabs.ParseJSON([]byte(*result.Messages[0].Body))

		if nil != err {
			panic(err)
		}

		var payload string

		payload = parsedResponse.Path("Message").Data().(string)

		fmt.Println(unpretty(payload))

		deleteRequest := &sqs.DeleteMessageInput{QueueURL: aws.String(queueUrl), ReceiptHandle: aws.String(*result.Messages[0].ReceiptHandle)}

		_, err = sqsClient.DeleteMessage(deleteRequest)

		if nil != err {
			panic(err)
		}
	}
}
Пример #18
0
func main() {
	// Load config
	file, err := os.Open("gakin.json")
	if err != nil {
		fmt.Printf("[*] Unable to load config: %s\n", err.Error())
	}

	cfg, err := ioutil.ReadAll(file)
	if err != nil {
		fmt.Printf("[*] Configure error: %s\n", err.Error())
	}
	r, err := gabs.ParseJSON(cfg)
	if err != nil {
		fmt.Printf("[*] Configure error: %s\n", err.Error())
	}

	messages = make(map[string]string)

	sauce_key = r.S("sauce_key").Data().(string)

	irchndl, _ := r.S("irc").Children()
	for _, icon := range irchndl {
		server, _ := icon.S("server").Data().(string)
		channel, _ := icon.S("channel").Data().(string)
		nickname, _ := icon.S("nickname").Data().(string)

		go IRCConnection(server, channel, nickname)
	}

	http.HandleFunc("/", HandlePost)

	endpoint, _ := r.S("endpoint").Data().(string)

	http.ListenAndServe(endpoint, nil)
}
Пример #19
0
func (svc *Service) BroadcastUserLeave(room string, uid string, so socketio.Socket) {
	bc, _ := gabs.ParseJSON([]byte("{}"))
	bc.SetP(svc.Users[uid].Token.Path("uid").Data().(string), "uid")
	bc.SetP(room, "room")
	so.BroadcastTo(room, "leave", bc.String())
	so.Emit("leave", bc.String())
}
Пример #20
0
func parseMapFile(filePath string) *Map {
	mapData, err := ioutil.ReadFile(filePath)
	if err != nil {
		log.Fatal(err)
	}

	jsonParsed, err := gabs.ParseJSON(mapData)
	if err != nil {
		log.Fatal(err)
	}

	mapWidth := int(jsonParsed.Path("width").Data().(float64))
	// Only first layer from Tiled data is used, rest ignored
	firstMapLayer := jsonParsed.Search("layers", "data").Index(0)
	tileTypes, _ := firstMapLayer.Children()

	m := Map{}
	for index, tileType := range tileTypes {
		x, y := calcTileCoords(index, mapWidth)
		tile := Tile{X: x, Y: y, Type: int(tileType.Data().(float64))}
		m.addTile(&tile)
	}

	return &m
}
Пример #21
0
func RequestUserData() {

	// Execute the get request
	res, err := http.Get("https://" + school + ".zportal.nl/api/v3/users/~me?access_token=" + access_token)

	// Check if an error has occurec
	if err == nil {

		resByte, _ := ioutil.ReadAll(res.Body)

		// Cleanup
		defer res.Body.Close()

		jsonParsed, err := gabs.ParseJSON(resByte)

		userData, _ = jsonParsed.Path("response.data").Children()

		// TODO: Do more error checking
		if err != nil {

			setError(ERROR_UNKNOWN, err.Error())
		}

	} else {

		if strings.Contains(err.Error(), "No address associated with hostname") {

			setError(ERROR_CONNECTION, err.Error())
		} else {

			setError(ERROR_UNKNOWN, err.Error())
		}
	}
}
Пример #22
0
// Handles incoming requests.
func handleRequest(conn net.Conn, logicConn net.Conn, db gorm.DB) {

	// Make a buffer to hold incoming data.
	buf := make([]byte, 1024)

	// Read the incoming connection into the buffer.
	reqLen, err := conn.Read(buf)
	println(string(reqLen))
	if err != nil {
		fmt.Println("Error reading:", err.Error())
	}

	n := bytes.Index(buf, []byte{0})

	// getting the json! up yours, rust.
	jsonParsed, err := gabs.ParseJSON(buf[:n-1])
	println("This is a message: " + jsonParsed.String())

	// save in db
	savePlayerAction(*jsonParsed, db)

	// write to logic server
	// TODO: check if that will communicate over sockets
	// TODO: can this be its goroutine?
	_, err = logicConn.Write([]byte(jsonParsed.String()))
	if err != nil {
		println("Write to server failed: ", err.Error())
		os.Exit(1)
	}

	conn.Close()
}
Пример #23
0
func main() {
	jsonParsed, _ := gabs.ParseJSON([]byte(`{
    "smaller":100000,
    "bigger":1000000
  }`))

	log.Println("=>", jsonParsed.String())
}
Пример #24
0
func TestGetMultStatementWithSinceUntil(t *testing.T) {
	db := initDatabase(t)
	defer db.Close()
	mart := initHandler(db)

	id1 := uuid.NewV4().String()
	id2 := uuid.NewV4().String()
	id3 := uuid.NewV4().String()

	stmt, err := gabs.ParseJSON([]byte(singleStatement01))
	fatalIfError(t, err)

	vsuffix := uuid.NewV4().String()
	verbID := "http://example.com/realglobe/XAPIprofile/test-" + vsuffix
	_, err = stmt.SetP(verbID, "verb.id")
	fatalIfError(t, err)

	putStatement(t, mart, stmt.String(), id1)
	since := time.Now()
	time.Sleep(time.Millisecond)
	putStatement(t, mart, stmt.String(), id2)
	time.Sleep(time.Millisecond)
	until := time.Now()
	putStatement(t, mart, stmt.String(), id3)

	// construct query
	v := &url.Values{}
	v.Add("verb", verbID)
	v.Add("since", since.Format(time.RFC3339Nano))
	v.Add("until", until.Format(time.RFC3339Nano))

	respstmt, err := gabs.ParseJSON(getStatement(t, mart, v))
	fatalIfError(t, err)
	cnt, err := respstmt.ArrayCount("statements")
	fatalIfError(t, err)

	if cnt != 1 {
		t.Fatalf("Expected 1 statements in response; got %d", cnt)
	}

	s0, err := respstmt.ArrayElement(0, "statements")
	fatalIfError(t, err)
	if id, ok := s0.Search("id").Data().(string); !ok || id != id2 {
		t.Fatalf("Got invalid order of statement array")
	}
}
Пример #25
0
func TestGetMultStatementWithAscending(t *testing.T) {
	db := initDatabase(t)
	defer db.Close()
	mart := initHandler(db)

	id1 := uuid.NewV4().String()
	id2 := uuid.NewV4().String()

	stmt, err := gabs.ParseJSON([]byte(singleStatement01))
	fatalIfError(t, err)

	vsuffix := uuid.NewV4().String()
	verbID := "http://example.com/realglobe/XAPIprofile/test-" + vsuffix
	_, err = stmt.SetP(verbID, "verb.id")
	fatalIfError(t, err)

	putStatement(t, mart, stmt.String(), id1)
	putStatement(t, mart, stmt.String(), id2)

	// construct query
	v := &url.Values{}
	v.Add("verb", verbID)
	v.Add("ascending", "true")

	respstmt, err := gabs.ParseJSON(getStatement(t, mart, v))
	fatalIfError(t, err)
	cnt, err := respstmt.ArrayCount("statements")
	fatalIfError(t, err)

	if cnt != 2 {
		t.Fatalf("Expected 2 statements in response; got %d", cnt)
	}

	s1, err := respstmt.ArrayElement(1, "statements")
	fatalIfError(t, err)
	if id, ok := s1.Search("id").Data().(string); !ok || id != id1 {
		t.Fatalf("Got invalid order of statement array")
	}

	s0, err := respstmt.ArrayElement(0, "statements")
	fatalIfError(t, err)
	if id, ok := s0.Search("id").Data().(string); !ok || id != id2 {
		t.Fatalf("Got invalid order of statement array")
	}
}
Пример #26
0
func parseGeoIPResponse(response *http.Response) (*gabs.Container, error) {
	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return nil, err
	}

	return gabs.ParseJSON(body)
}
Пример #27
0
func TestGetMultStatementWithActorGroupOpenID(t *testing.T) {
	group, err := gabs.ParseJSON([]byte(statetmentAgentBoilerplate))
	fatalIfError(t, err)
	_, err = group.SetP("Group", "actor.objectType")
	fatalIfError(t, err)
	_, err = group.Array("actor", "member")
	fatalIfError(t, err)

	testGetMultStatementOfGroup(t, appendOpenID(t, group))
}
Пример #28
0
func TestGetMultStatementWithRegistration(t *testing.T) {
	db := initDatabase(t)
	defer db.Close()
	mart := initHandler(db)

	id1 := uuid.NewV4().String()
	id2 := uuid.NewV4().String()

	stmt, err := gabs.ParseJSON([]byte(singleStatement02))
	fatalIfError(t, err)

	registrationID := uuid.NewV4().String()
	_, err = stmt.SetP(registrationID, "context.registration")
	fatalIfError(t, err)

	putStatement(t, mart, stmt.String(), id1)
	putStatement(t, mart, stmt.String(), id2)

	// construct query
	v := &url.Values{}
	v.Add("registration", registrationID)

	respstmt, err := gabs.ParseJSON(getStatement(t, mart, v))
	fatalIfError(t, err)
	cnt, err := respstmt.ArrayCount("statements")
	fatalIfError(t, err)

	if cnt != 2 {
		t.Fatalf("Expected 2 statements in response; got %d", cnt)
	}

	s0, err := respstmt.ArrayElement(0, "statements")
	fatalIfError(t, err)
	if id, ok := s0.Search("id").Data().(string); !ok || id != id1 {
		t.Fatalf("Got invalid order of statement array")
	}

	s1, err := respstmt.ArrayElement(1, "statements")
	fatalIfError(t, err)
	if id, ok := s1.Search("id").Data().(string); !ok || id != id2 {
		t.Fatalf("Got invalid order of statement array")
	}
}
Пример #29
0
func TestPutStatementAndCheckAuthority(t *testing.T) {
	m := martini.Classic()

	sess, err := mgo.Dial(miscs.GlobalConfig.MongoDB.URL)
	defer sess.Close()
	if err != nil {
		t.Fatalf("%v", err)
	}
	c := New(sess)

	m.Get("/:user/:app/statements", acceptlang.Languages(), c.FindStatement)
	m.Put("/:user/:app/statements", c.StoreStatement)
	stmt := singleStatement01

	resp := httptest.NewRecorder()
	statementID := uuid.NewV4().String()
	req, _ := http.NewRequest("PUT",
		"/test/test/statements?statementId="+statementID,
		strings.NewReader(stmt),
	)
	req.Header.Add("X-Experience-API-Version", "1.0.2")
	req.Header.Add("X-Edo-Ta-Id", "example-ta-id")
	req.Header.Add("X-Edo-User-Id", "example-user-id")

	m.ServeHTTP(resp, req)

	if got, expected := resp.Code, http.StatusNoContent; got != expected {
		t.Fatalf("Expected %v response code from put single statement; got %d", expected, got)
	}

	resp2 := httptest.NewRecorder()
	req2, _ := http.NewRequest("GET", "/test/test/statements?statementId="+statementID, nil)
	req2.Header.Add("X-Experience-API-Version", "1.0.2")

	m.ServeHTTP(resp2, req2)

	if got, expected := resp2.Code, http.StatusOK; got != expected {
		t.Fatalf("Expected %v response code from get single statement; got %d", expected, got)
	}

	body, err := ioutil.ReadAll(resp2.Body)
	fatalIfError(t, err)

	rstmt, err := gabs.ParseJSON(body)
	fatalIfError(t, err)

	v, ok := rstmt.Path("authority.account.homePage").Data().(string)
	if !ok || v != "example-ta-id" {
		t.Fatal("Field authority.account.homePage is invalid or not found in get response")
	}
	v, ok = rstmt.Path("authority.account.name").Data().(string)
	if !ok || v != "example-user-id" {
		t.Fatal("Field authority.account.name is invalid or not found in get response")
	}
}
Пример #30
0
func sauce(imgurl string) {
	resp, err := http.Get("https://saucenao.com/search.php?db=999&output_type=2&testmode=1&numres=16&url=" + imgurl + "&api_key=" + sauce_key)
	if err != nil {
		message <- "Request Error"
	}
	defer resp.Body.Close()
	res, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		message <- "Request Error"
	}
	jsn, _ := gabs.ParseJSON(res)
	results, _ := jsn.S("results").Children()
	cnt := 1
	for _, child := range results {
		header := child.S("header")
		data := child.S("data")

		sim := header.S("similarity").Data()
		if sim == nil {
			sim = "?"
		}
		index_num := header.S("index_id").Data().(float64)
		index_name := header.S("index_name").Data()
		if index_name == nil {
			index_name = "?"
		}

		src_pxurl := "http://www.pixiv.net/member_illust.php?mode=medium\u0026illust_id="

		source := ""
		artist := "?"
		title := "?"

		if index_num == 9 {
			src := data.S("source").Data()
			if src != nil {
				source = src.(string)
			}
			artists, _ := data.S("creator").Children()
			artist = artists[0].Data().(string)
		} else if index_num == 5 {
			source = src_pxurl + data.S("pixiv_id").Data().(string)
			title = data.S("title").Data().(string)
			artist = data.S("member_name").Data().(string)
		}

		message <- "[" + sim.(string) + "% Match] " + index_name.(string) + " Title: " + title + " Artist: " + artist + " Src: " + source

		if cnt == 2 {
			break
		}
		cnt += 1
	}
}