Exemplo n.º 1
0
Arquivo: main.go Projeto: Shadey/Leo
func GetWeather(city string, state string) {
	json_link := fmt.Sprintf("%s/hourly/q/%s/%s.json", API_LINK, state, city)
	resp, err := http.Get(json_link)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Fatal(err)
	}
	v, err := jason.NewObjectFromBytes(body)
	if err != nil {
		log.Fatal(err)
	}
	hourlyForecast, err := v.GetObjectArray("hourly_forecast")
	if err != nil {
		log.Fatal(err)
	}
	for _, hourCast := range hourlyForecast {
		stringhour, _ := hourCast.GetString("FCTTIME", "hour")
		temp, _ := hourCast.GetString("temp", "english")
		hour, _ := strconv.Atoi(stringhour)
		if hour == time.Now().Hour() {
			SendWeather(temp)
			break
		}
	}
}
Exemplo n.º 2
0
// Fetch commands
func (s *Client) PollCmds() {
	bytes, err := s._get(fmt.Sprintf("client/%s/cmds", url.QueryEscape(s.Id)))
	if err == nil {
		obj, jerr := jason.NewObjectFromBytes(bytes)
		if jerr == nil {
			status, statusE := obj.GetString("status")
			// Re-auth
			if statusE != nil || status != "OK" {
				log.Println(string(bytes))
				log.Println("Re-authenticate with server")
				s.AuthServer()
				return
			}

			// List commands
			cmds, _ := obj.GetObjectArray("cmds")
			for _, cmd := range cmds {
				id, _ := cmd.GetString("Id")
				command, _ := cmd.GetString("Command")
				signature, _ := cmd.GetString("Signature")
				templateId, _ := cmd.GetString("TemplateId")
				timeout, _ := cmd.GetInt64("Timeout")
				cmd := newCmd(command, int(timeout))
				cmd.ClientId = client.Id
				cmd.TemplateId = templateId
				cmd.Id = id
				cmd.Signature = signature
				cmd.Execute(s)
			}
		}
	} else {
		// In case of fast error back off a bit
		time.Sleep(1 * time.Second)
	}
}
Exemplo n.º 3
0
func extractBlogPosts() map[string]*BlogPost {
	outcome := make(map[string]*BlogPost)
	rawContent, readErr := ioutil.ReadFile(appConfiguration["saved_data_filename"].StringValue)

	if readErr == nil {
		json, _ := jason.NewObjectFromBytes(rawContent)

		for k1, _ := range json.Map() {
			hash := make(map[string]int)
			author, _ := json.GetString(k1, "author")
			headline, _ := json.GetString(k1, "headline")
			date, _ := json.GetInt64(k1, "date")
			contentHash, _ := json.GetObject(k1, "contentHash")
			brief, _ := json.GetString(k1, "brief")

			post := BlogPost{
				k1,
				author,
				headline,
				time.Unix(date, 0),
				hash,
				brief,
			}

			for k2, v2 := range contentHash.Map() {
				n, _ := v2.Int64()
				hash[k2] = int(n)
			}

			outcome[k1] = &post
		}
	}

	return outcome
}
Exemplo n.º 4
0
func listContainers() {

	response := instainerGet("/containers")

	defer response.Body.Close()
	contents, err := ioutil.ReadAll(response.Body)
	check(err)
	v, err := jason.NewObjectFromBytes(contents)
	data, err := v.GetObject("data")

	permanents, err := data.GetObjectArray("permanents")
	nonpermanents, err := data.GetObjectArray("nonPermanents")

	banner.Print("instainer")
	fmt.Println("")
	fmt.Println("")

	fmt.Println("Permanent Containers")
	fmt.Println("")

	fmt.Printf("%-32s %-52s %-32s %-24s\n", "CONTAINER ID", "NAME", "IMAGE NAME", "CREATED")

	for _, container := range permanents {

		containerId, err := container.GetString("id")
		name, err := container.GetString("name")
		imageName, err := container.GetString("imageName")
		createdTime, err := container.GetString("createdTime")

		check(err)

		fmt.Printf("%-32s %-52s %-32s %-24s\n", containerId, name, imageName, createdTime)

	}
	fmt.Println("")
	fmt.Println("")

	fmt.Println("Non-Permanent Containers")
	fmt.Println("")

	fmt.Printf("%-32s %-52s %-32s %-24s\n", "CONTAINER ID", "NAME", "IMAGE NAME", "CREATED")

	for _, container := range nonpermanents {

		containerId, err := container.GetString("id")
		name, err := container.GetString("name")
		imageName, err := container.GetString("imageName")
		createdTime, err := container.GetString("createdTime")

		check(err)

		fmt.Printf("%-32s %-52s %-32s %-24s\n", containerId, name, imageName, createdTime)

	}
}
Exemplo n.º 5
0
func BenchmarkJasonSmall(b *testing.B) {
	for i := 0; i < b.N; i++ {
		json, _ := jason.NewObjectFromBytes(smallFixture)

		json.GetString("uuid")
		json.GetFloat64("tz")
		json.GetString("ua")
		json.GetFloat64("st")

		nothing()
	}
}
Exemplo n.º 6
0
func twitchDecode(stream []byte) string {
	datajson, _ := jason.NewObjectFromBytes(stream)
	game, err := datajson.GetString("stream", "game")
	status, err := datajson.GetString("stream", "channel", "status")
	url, err := datajson.GetString("stream", "channel", "url")
	viewers, err := datajson.GetInt64("stream", "viewers")
	streamname, err := datajson.GetString("stream", "channel", "name")
	if err != nil {
		return "Not Online or API server is down(probably not online)!"
	}

	return url + " " + streamname + " is online with " + strconv.Itoa(int(viewers)) + " viewers, Playing: " + game + "!  " + status + "\n"

}
Exemplo n.º 7
0
func GetLanguageConfig(lang string) LanguageConfig {
	raw, _ := ioutil.ReadFile("./config.json")
	decoded, _ := jason.NewObjectFromBytes([]byte(raw))
	time, _ := decoded.GetInt64("Languages", lang, "Time")
	memory, _ := decoded.GetInt64("Languages", lang, "Memory")
	compile, _ := decoded.GetString("Languages", lang, "Compile")
	run, _ := decoded.GetString("Languages", lang, "Run")
	file, _ := decoded.GetString("FileName")
	return LanguageConfig{
		Time:            time,
		Memory:          memory,
		Compile:         compile,
		Run:             run,
		FilePlaceholder: file,
	}
}
Exemplo n.º 8
0
func BenchmarkJasonMedium(b *testing.B) {
	for i := 0; i < b.N; i++ {
		json, _ := jason.NewObjectFromBytes(mediumFixture)

		json.GetString("person.name.fullName")
		json.GetFloat64("person.github.followers")
		json.GetObject("company")
		arr, _ := json.GetObjectArray("person.gravatar.avatars")

		for _, el := range arr {
			el.GetString("url")
		}

		nothing()
	}
}
func main() {

	// Use the same library and method we defined before
	body := controller.GetHosts("https://sandboxapic.cisco.com")

	// Use the JSON library, jason, to do the heavy lifting of creating go objects
	v, _ := jason.NewObjectFromBytes(body)

	// Since the result is an array of objects, we need to use GetObjectArray()
	r, _ := v.GetObjectArray("response")

	// Loop over the objects
	for _, obj := range r {

		// Use the jason library's GetString() method to get the right elements of the
		// returned JSON.
		//
		// Example JSON
		// {
		//   "connectedInterfaceId": "30bb14c1-8fb6-45c4-8f6d-5b845a7f448c",
		//   "connectedInterfaceName": "GigabitEthernet2/0/2",
		//   "connectedNetworkDeviceId": "7895a45f-47aa-42ee-9d06-c66d3b784594",
		//   "connectedNetworkDeviceIpAddress": "40.0.2.18",
		//   "hostIp": "40.0.5.12",
		//   "hostMac": "00:50:56:8A:27:A3",
		//   "hostType": "WIRED",
		//   "id": "8f41bef8-698c-4701-af14-471e910ed9ff",
		//   "lastUpdated": "September 29, 2014 1:54:13 PM PDT",
		//   "numUpdates": 1,
		//   "source": 200,
		//   "userStatus": "Active",
		//   "vlanId": "1"
		// }

		iFace, err := obj.GetString("connectedInterfaceId")
		deviceType, err := obj.GetString("hostType")

		log.Println("id: " + iFace + " type: " + deviceType)

		if err != nil {
			log.Println(err)
		}
	}

}
Exemplo n.º 10
0
func jsonDecode(data []byte) int {
	updateidreturn := 1
	datajson, _ := jason.NewObjectFromBytes(data)
	result, _ := datajson.GetObjectArray("result")
	for _, results := range result {
		userid, _ := results.GetInt64("message", "from", "id")
		chatid, _ := results.GetInt64("message", "chat", "id")
		updateid, _ := results.GetInt64("update_id")
		text, _ := results.GetString("message", "text")
		username, _ := results.GetString("message", "from", "username")
		firstname, _ := results.GetString("message", "from", "first_name")
		lastname, _ := results.GetString("message", "from", "last_name")
		fmt.Printf("[%d/%d]%s %s(%s): %s\n", userid, chatid, firstname, lastname, username, text)

		go interpret(int(chatid), text)
		updateidreturn = int(updateid)
	}
	return updateidreturn
}
Exemplo n.º 11
0
func FBLogin(w http.ResponseWriter, r *http.Request) {
	// grab the code fragment

	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	code := r.FormValue("code")

	ClientId := "137453133278122" // change this to yours
	ClientSecret := "ee16109c966f12014bbcfccb4547813c"
	RedirectURL := "http://localhost:8080/FBLogin"

	accessToken := GetAccessToken(ClientId, code, ClientSecret, RedirectURL)

	response, err := http.Get("https://graph.facebook.com/me?fields=id,email,first_name,last_name&access_token=" + accessToken.Token)

	// handle err. You need to change this into something more robust
	// such as redirect back to home page with error message
	if err != nil {
		w.Write([]byte(err.Error()))
	}

	str := readHttpBody(response)
	//fmt.Println(str)
	// dump out all the data
	// w.Write([]byte(str))

	// see https://www.socketloop.com/tutorials/golang-process-json-data-with-jason-package
	user, _ := jason.NewObjectFromBytes([]byte(str))

	id, _ := user.GetString("id")
	email, _ := user.GetString("email")
	fbFirstName, _ := user.GetString("first_name")
	fbLastName, _ := user.GetString("last_name")

	w.Write([]byte(fmt.Sprintf("Username %s %s ID is %s and email is %s<br>", fbFirstName, fbLastName, id, email)))

	img := "https://graph.facebook.com/" + id + "/picture?width=180&height=180"

	//w.Write([]byte("Photo is located at " + img + "<br>"))
	// see https://www.socketloop.com/tutorials/golang-download-file-example on how to save FB file to disk

	w.Write([]byte("<img src='" + img + "'>"))
}
Exemplo n.º 12
0
// Ping server
func (s *Client) PingServer() {
	bytes, e := s._get(fmt.Sprintf("client/%s/ping?tags=%s&hostname=%s", url.QueryEscape(s.Id), url.QueryEscape(strings.Join(conf.GetTags(), ",")), url.QueryEscape(s.Hostname)))
	if e == nil {
		obj, jerr := jason.NewObjectFromBytes(bytes)
		if jerr == nil {
			status, statusE := obj.GetString("status")
			serverInstanceId, _ := obj.GetString("server_instance_id")

			// Ping failed, re-authenticate
			if statusE != nil || status != "OK" {
				log.Println(string(bytes))
				log.Println("Re-authenticate with server")
				s.AuthServer()
			} else {
				// Only log a connect if the instance ID changed
				if len(s.ConnectedServerInstanceId) == 0 || s.ConnectedServerInstanceId != serverInstanceId {
					s.ConnectedServerInstanceId = serverInstanceId
					log.Println(fmt.Sprintf("Client registered with server %s", s.ConnectedServerInstanceId))
				}
			}
		}
	}
}
Exemplo n.º 13
0
// Auth server, token is used for verifying commands
// @todo This function needs more logging in failure scenarios
func (s *Client) AuthServer() {
	b, e := s._req("POST", fmt.Sprintf("client/%s/auth", url.QueryEscape(s.Id)), nil)
	if e == nil {
		obj, jerr := jason.NewObjectFromBytes(b)
		if jerr == nil {
			// Get signature
			token, et := obj.GetString("token")
			if et != nil || len(token) < 1 {
				return
			}

			// Get token signatur
			tokenSignature, ets := obj.GetString("token_signature")
			if ets != nil || len(tokenSignature) < 1 {
				return
			}

			// Verify token signature with our secure token
			hasher := sha256.New()
			hasher.Write([]byte(token))
			hasher.Write([]byte(conf.Token))
			expectedTokenSignature := base64.URLEncoding.EncodeToString(hasher.Sum(nil))

			// The same?
			if tokenSignature != expectedTokenSignature {
				log.Println("ERROR! Token signature from server is invalid, communication between server and client might be tampered with")
				return
			}

			// Store token if it is valid
			s.mux.Lock()
			s.AuthToken = token
			s.mux.Unlock()
			log.Printf("Client authenticated with server")
		}
	}
}
Exemplo n.º 14
0
Arquivo: where.go Projeto: aiyi/go
func (f *Filter) parseWhere(str string) (err error) {
	where := &Where{}
	f.where = where

	if str == "" {
		return
	}

	root, err := jason.NewObjectFromBytes([]byte(str))
	if err != nil {
		fmt.Println("parse json failed")
		return err
	}

	oa, _ := root.GetObjectArray("$or")
	if oa == nil {
		c, err := parseCondition(root)
		if err != nil {
			fmt.Println("parseCondition failed")
			return err
		}

		*where = append(*where, c)
	} else {
		for _, o := range oa {
			c, err := parseCondition(o)
			if err != nil {
				fmt.Println("parseCondition failed")
				return err
			}

			*where = append(*where, c)
		}
	}

	return nil
}
Exemplo n.º 15
0
		BeforeEach(func() {
			ImportHoverflyRecords(jsonRequestResponsePair1)
			ImportHoverflyRecords(jsonRequestResponsePair2)
			ImportHoverflyRecords(jsonRequestResponsePairTemplate)
			SetHoverflyResponseDelays("testdata/delays.json")
		})

		It("Should get all the Hoverfly simulation data in one JSON file", func() {
			req := sling.New().Get(hoverflyAdminUrl + "/api/v2/simulation")
			res := DoRequest(req)
			Expect(res.StatusCode).To(Equal(200))
			responseJson, err := ioutil.ReadAll(res.Body)
			Expect(err).To(BeNil())

			jsonObject, err := jason.NewObjectFromBytes(responseJson)
			Expect(err).To(BeNil())

			metaObject, err := jsonObject.GetObject("meta")
			Expect(err).To(BeNil())
			schemaVersion, err := metaObject.GetString("schemaVersion")
			Expect(err).To(BeNil())
			Expect(schemaVersion).To(Equal("v1"))
			hoverflyVersion, err := metaObject.GetString("hoverflyVersion")
			Expect(err).To(BeNil())
			Expect(hoverflyVersion).ToNot(BeNil())
			timeExported, err := metaObject.GetString("timeExported")
			Expect(err).To(BeNil())
			Expect(timeExported).ToNot(BeNil())

			dataObject, err := jsonObject.GetObject("data")
Exemplo n.º 16
0
func main() {
	// Get mongo url from config.json, otherwise default to 127.0.0.1
	mongo := "127.0.0.1"
	bitcannonPort := "1337"
	bitcannonBindIp := "0.0.0.0"
	f, err := ioutil.ReadFile("config.json")
	if err != nil {
		log.Println("[!!!] Config not loaded")
	} else {
		json, err := jason.NewObjectFromBytes(f)
		if err == nil {
			// Get mongo connection details
			val, err := json.GetString("mongo")
			if err == nil {
				mongo = val
			}
			// Get desired port
			val, err = json.GetString("bitcannonPort")
			if err == nil {
				bitcannonPort = val
			}
			// Get archive sources
			arc, err := json.GetObjectArray("archives")
			if err == nil {
				archives = arc
			}
			// Get trackers
			trac, err := json.GetStringArray("trackers")
			if err == nil {
				trackers = trac
			}
			// Get scraping enabled
			scrape, err := json.GetBoolean("scrapeEnabled")
			if err == nil {
				config.ScrapeEnabled = scrape
			}
			// Get scrape delay
			scrapeDelay, err := json.GetInt64("scrapeDelay")
			if err == nil {
				config.ScrapeDelay = int(scrapeDelay)
			}
			// Get desired listening host
			val, err = json.GetString("bitcannonBindIp")
			if err == nil {
				bitcannonBindIp = val
			}
		}
	}
	// Try to connect to the database
	log.Println("[OK!] Connecting to Mongo at " + mongo)
	torrentDB, err = NewTorrentDB(mongo)
	if err != nil {
		log.Println("[ERR] I'm sorry! I Couldn't connect to Mongo.")
		log.Println("      Please make sure it is installed and running.")
		return
	}
	defer torrentDB.Close()

	if len(os.Args) > 1 {
		importFile(os.Args[1])
		enterExit()
	} else {
		runServer(bitcannonPort, bitcannonBindIp)
	}
}
Exemplo n.º 17
0
func createContainer(dockerName string, volumeRequest []string, envVariables []string) {

	m := &RunParams{VolumeRequests: volumeRequest, EnvVariables: envVariables}
	b, err := json.Marshal(m)

	response := instainerPost("/container/run?image="+dockerName, string(b))

	defer response.Body.Close()

	contents, err := ioutil.ReadAll(response.Body)
	check(err)
	v, err := jason.NewObjectFromBytes(contents)
	data, err := v.GetObject("data")

	username, err := data.GetString("gitUser")
	password, err := data.GetString("gitPassword")

	banner.Print("instainer")
	fmt.Println("")
	fmt.Println("")

	color.Green("------------Git Information------------")
	color.Yellow("Git User      = %s", username)
	color.Yellow("Git Password  = %s", password)
	fmt.Println("")
	fmt.Println("")

	color.Green("----------Volumes Information----------")
	volumes, err := data.GetObjectArray("volumes")
	for _, volume := range volumes {
		mntDir, err := volume.GetString("mntDir")
		gitUrl, err := volume.GetString("gitUrl")
		check(err)
		color.Blue("    %s", mntDir)
		color.Yellow("    Git URL  = %s", gitUrl)
		fmt.Println("")
	}
	fmt.Println("")

	color.Green("------------Port Information------------")
	ports, err := data.GetObjectArray("ports")

	for _, port := range ports {
		dockerPort, err := port.GetString("dockerPort")
		instainerPort, err := port.GetString("instainerPort")
		check(err)
		color.Blue("  Container Port    %s", dockerPort)
		color.Yellow("  Instainer Port    instainer.io:%s", instainerPort)
		fmt.Println("")
	}
	fmt.Println("")

	envVariablesData, err := data.GetStringArray("envVariables")

	if len(envVariablesData) > 0 {
		color.Green("---------Environment Variables----------")

		for _, variable := range envVariablesData {
			color.Yellow("    Variable=Value      = %s", variable)
		}
	}
	fmt.Println("")
	fmt.Println("")
	fmt.Println("Successfully deployed!")
	fmt.Println("")
	fmt.Println("")

	check(err)
}
Exemplo n.º 18
0
func (srv *Server) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	defer req.Body.Close()

	if req.Method != "POST" {
		msg := "Github hook request is POST only"
		http.Error(w, msg, http.StatusMethodNotAllowed)
		fmt.Println(msg)
		return
	}

	if req.URL.Path != srv.Path {
		msg := "Invalid Path"
		http.Error(w, msg, http.StatusNotFound)
		fmt.Println(msg)
		return
	}

	eventType := req.Header.Get("X-GitHub-Event")
	if eventType != "push" && eventType != "pull_request" {
		w.Write([]byte(fmt.Sprintf("Evernt Type %s is not supported", eventType)))
		return
	}

	body, err := ioutil.ReadAll(req.Body)
	if err != nil {
		http.Error(w, "Fail to read req.Body", http.StatusBadRequest)
	}

	if srv.Secret != "" {
		sig := req.Header.Get("X-Hub-Signature")

		if sig == "" {
			http.Error(w, "Missing X-Hub-Signature", http.StatusForbidden)
			return
		}

		mac := hmac.New(sha1.New, []byte(srv.Secret))
		mac.Write(body)
		expected := "sha1=" + hex.EncodeToString(mac.Sum(nil))
		// hmac Equal won't leak through timing side-channel
		if !hmac.Equal([]byte(expected), []byte(sig)) {
			http.Error(w, "Secret not match", http.StatusForbidden)
			return
		}
	}

	request, err := jason.NewObjectFromBytes(body)
	if err != nil {
		http.Error(w, "Bad Request", http.StatusBadRequest)
		return
	}

	// https://developer.github.com/v3/activity/events/types/#pushevent
	// (*jason.Object)(0xc20803b590)({"added":["test.go"],"author":{"email":"*****@*****.**","name":"naituida","username":"******"},"committer":{"email":"*****@*****.**","name":"naituida","username":"******"},"distinct":true,"id":"76fa79bab843450020bd73fbba0b30741f99055f","message":"init push","modified":[],"removed":[],"timestamp":"2015-09-11T02:22:02-04:00","url":"https://github.com/dyzz/gothubhook/commit/76fa79bab843450020bd73fbba0b30741f99055f"}) }

	var log string

	if eventType == "push" {
		repo, _ := request.GetString("repository", "name")
		ref, _ := request.GetString("ref")
		chunks := strings.Split(ref, "/")
		branch := chunks[len(chunks)-1]

		commits, _ := request.GetObjectArray("commits")
		for _, commit := range commits {
			author, _ := commit.GetString("author", "name")
			msg, _ := commit.GetString("message")
			date, _ := commit.GetString("timestamp")
			event := NewEvent(author, repo, branch, "commit", msg, date, "push")
			log = event.String()
			w.Write([]byte(log))
		}
	}

	// https://developer.github.com/v3/activity/events/types/#pullrequestevent
	if eventType == "pull_request" {
		action, _ := request.GetString("action")
		number, _ := request.GetInt64("number")
		pq, _ := request.GetObject("pull_request")
		msg, _ := pq.GetString("title")
		date, _ := pq.GetString("updated_at")
		author, _ := pq.GetString("user", "login")
		repo, _ := request.GetString("repository", "name")
		event := NewEvent(author, repo, "#"+strconv.Itoa(int(number)), action, msg, date, "pullrequest")
		log = event.String()
		w.Write([]byte(log))
	}

	fmt.Println(log)
	AppendLog(log)
}
Exemplo n.º 19
0
func reqWithBufferio(conn *net.TCPConn, data string, times int) {

	req_ready_byte, _ := protocol.Packet(data)
	conn.Write(req_ready_byte)

	var i int
	i = 0
	sid := ""
	str := `{ "cmd":"socket.getSession"}`

	reader := bufio.NewReader(conn)
	for {
		msg, err := reader.ReadString('\n')
		if err != nil {
			fmt.Println(conn.RemoteAddr().String(), " connection error: ", err)
			conn.Close()
			return
		}

		if msg == "" {
			continue
		}

		msg_json, errjson := jason.NewObjectFromBytes([]byte(msg))
		if errjson != nil {
			//fmt.Println( " errjson  :",  errjson.Error() )
			continue
		}
		cmd, _ := msg_json.GetString("cmd")
		//fmt.Printf( " msg: %s\n", msg )
		if cmd == "socket.user_login" {
			sid, _ = msg_json.GetString("data")
			//fmt.Printf( " sid: %s\n", sid )
			str = fmt.Sprintf(`{ "cmd":"socket.getSession","params":{"sid":"%s"} }`, sid)
			session_req_byte, _ := protocol.Packet(str)
			conn.Write(session_req_byte)
			//time.Sleep(10 * time.Millisecond )
			checkError(err)

		}
		if cmd == "socket.getSession" && sid != "" {

			// session_str,  _ := msg_json.GetString("data" )
			//session_json, _ := jason.NewObjectFromBytes( []byte(session_str) )
			//sid ,_= session_json.GetString("msg","Sid")
			//fmt.Printf( " sid: %s\n", sid )
			str = fmt.Sprintf(`{ "cmd":"socket.getSession","params":{"sid":"%s"} }`, sid)
			session_req_byte, _ := protocol.Packet(str)
			conn.Write(session_req_byte)
			checkError(err)
			i++
			time.Sleep(10 * time.Millisecond)
			if i > times {
				conn.Close()
				fmt.Println(" i : ", i)
				fmt.Println(" conn close! ", i, "\n")
				break
			}
		}

	}

	conn.Close()

}
Exemplo n.º 20
0
func reqWithJson(conn *net.TCPConn, data string, times int) {

	_, err := conn.Write([]byte(data + "\n"))
	checkError(err)
	var i int
	i = 0
	sid := ""
	str := `{ "cmd":"socket.getSession"}`
	d := json.NewDecoder(conn)
	for {

		var msg interface{}

		err := d.Decode(&msg)
		if err != nil {

			conn.Close()
			fmt.Println("d.Decode(&msg) ", err.Error())
			break
		}
		json_encode, err_encode := json.Marshal(msg)
		if err_encode != nil {
			fmt.Println("json.Marshal error:", err_encode.Error())
			conn.Close()
			break
		}
		response_str := string(json_encode)

		//fmt.Printf( " response: %s\n", response_str )
		msg_json, errjson := jason.NewObjectFromBytes([]byte(response_str))
		checkError(errjson)
		cmd, _ := msg_json.GetString("cmd")
		//fmt.Printf( " cmd: %s\n", cmd )
		if cmd == "socket.user_login" {
			sid, _ = msg_json.GetString("data", "sid")
			//fmt.Printf( " sid: %s\n", sid )
			str = fmt.Sprintf(`{ "cmd":"socket.getSession","params":{"sid":"%s"} }`, sid)
			str = str + "\n"
			//fmt.Println( " post : ", str )
			_, err = conn.Write([]byte(str))
			//time.Sleep(10 * time.Millisecond )
			checkError(err)

		}
		if cmd == "socket.getSession" {

			_, err = conn.Write([]byte(str + "\n"))
			checkError(err)
			i++
			time.Sleep(10 * time.Millisecond)
			if i >= times {
				//conn.Close()
				fmt.Println(" i : ", i)
				fmt.Println(" conn close! ", i, "\n")
				break
			}
		}
		//ch <- &SocketResponse{ data, string(response_str), err}
	}
	//conn.Close()

}
Exemplo n.º 21
0
func (c *appContext) FBLogin(w http.ResponseWriter, r *http.Request) {
	// grab the code fragment

	code := r.FormValue("code")

	RedirectURL := c.domain + "/FBLogin"

	accessToken := GetAccessToken(c.fbclientid, code, c.fbsecret, RedirectURL)

	response, err := http.Get("https://graph.facebook.com/me?access_token=" + accessToken.Token)

	// handle err. You need to change this into something more robust
	// such as redirect back to home page with error message
	if err != nil {
		w.Write([]byte(err.Error()))
	}

	str := readHTTPBody(response)
	log.Println(str)
	us, err := jason.NewObjectFromBytes([]byte(str))
	if err != nil {
		log.Println(err)
	}

	id, err := us.GetString("id")
	if err != nil {
		log.Println(err)
	}

	email, err := us.GetString("email")
	if err != nil {
		log.Println(err)
	}

	name, err := us.GetString("name")
	if err != nil {
		log.Println(err)
	}

	img := "https://graph.facebook.com/" + id + "/picture?width=180&height=180"
	log.Println("It got this far; the ID is")
	log.Println(id)

	u := User{
		Name:  name,
		PID:   id,
		Email: email,
		Image: img,
	}

	user, err := c.Authenticate(&u, "facebook")
	log.Println(user)
	if err != nil {
		log.Println(err)
	}

	// create a signer for rsa 256
	t := jwt.New(jwt.GetSigningMethod("RS256"))

	// set our claims
	t.Claims["AccessToken"] = user.Permission
	t.Claims["User"] = user

	// set the expire time
	// see http://tools.ietf.org/html/draft-ietf-oauth-json-web-token-20#section-4.1.4

	t.Claims["exp"] = time.Now().Add(time.Hour * 99999).Unix()
	tokenString, err := t.SignedString(c.signKey)

	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		fmt.Fprintln(w, "Sorry, error while Signing Token!")
		log.Printf("Token Signing error: %v\n", err)
		return
	}

	// i know using cookies to store the token isn't really helpfull for cross domain api usage
	// but it's just an example and i did not want to involve javascript
	http.SetCookie(w, &http.Cookie{
		Name:       c.token,
		Value:      tokenString,
		Path:       "/",
		RawExpires: "0",
	})

	http.Redirect(w, r, "/", http.StatusFound)
}
Exemplo n.º 22
0
//  Worker using REQ socket to do load-balancing
//
func hubWorkeDispath(msg []byte, conn *net.TCPConn) {

	//  Process messages as they arrive

	//fmt.Println( "hubWorkeDispath:", string(msg) )

	// 角色登录成功后
	ret_json, _ := jason.NewObjectFromBytes(msg)
	cmd, _ := ret_json.GetString("cmd")

	if cmd == "get_enable" {

		conn.Write([]byte(string(global.AppConfig.Enable)))
		conn.Close()
	}

	if cmd == "enabled" {
		global.AppConfig.Enable = 1
		conn.Write([]byte(string(global.AppConfig.Enable)))
	}

	if cmd == "disabled" {
		global.AppConfig.Enable = 0
		conn.Write([]byte(string(global.AppConfig.Enable)))
	}

	// 创建场景
	if cmd == "create_channel" {

		name, _ := ret_json.GetString("name")
		log.Debug(" join_channel ", name)

		go area.CreateChannel(name, name)
		global.Channels[name] = ""

		conn.Write([]byte(`ok`))
	}

	// 销毁场景
	if cmd == "remove_channel" {

		id, _ := ret_json.GetString("name")
		log.Debug("remove_channel:", id)
		area.RemovChannel(id)
		conn.Write([]byte(`ok`))

	}
	// 加入到一个场景中
	if cmd == "join_channel" {

		sid, _ := ret_json.GetString("sid")
		name, _ := ret_json.GetString("name")
		log.Debug("join_channel:", sid, name)

		// 如果场景不存在,则返回错误
		exist := area.CheckChannelExist(name)
		if !exist {

			conn.Write([]byte(`error,channel not exist`))

		} else {

			// 检查会话用户是否加入过此场景
			have_joined := area.CheckUserJoinChannel(name, sid)

			// 如果还没有加入场景,则订阅
			if !have_joined {

				user_conn := area.GetConn(sid)
				channel_host := global.Channels[name]
				log.Debug(" join_channel ", user_conn, channel_host, sid)
				user_wsconn := area.GetWsConn(sid)

				// 会话如果属于socket
				if user_conn != nil {
					go area.SubscribeChannel(name, user_conn, sid)
				}
				// 会话如果属于websocket
				if user_wsconn != nil {
					go area.SubscribeWsChannel(name, user_wsconn, sid)
				}
				var userJoinedChannels = make([]string, 0, 1000)
				tmp, ok := global.SyncUserJoinedChannels.Get(sid)
				if ok {
					userJoinedChannels = tmp.([]string)
				}
				userJoinedChannels = append(userJoinedChannels, name)
				global.SyncUserJoinedChannels.Set(sid, userJoinedChannels)
			}

			conn.Write([]byte(`ok`))
		}

	}

	if cmd == "leave_channel" {

		sid, _ := ret_json.GetString("sid")
		name, _ := ret_json.GetString("name")
		log.Debug("remove_channel:", sid, name)
		// 离开场景则关闭此订阅
		go area.UnSubscribeChannel(name, sid)

		user_channels, exist := global.UserChannels[sid]
		if exist {
			for i := 0; i < len(user_channels); i++ {
				if user_channels[i] == name {
					user_channels = append(user_channels[:i], user_channels[i+1:]...)
					global.UserChannels[sid] = user_channels
					break
				}
			}
		}

		log.Debug("userChannels's ", sid, ":", global.UserChannels[sid])
		log.Debug("hub_worker leave_channel:", sid, name)
		conn.Write([]byte(`ok`))
	}

	if cmd == "kick" {
		sid, _ := ret_json.GetString("sid")
		user_conn := area.GetConn(sid)
		if user_conn != nil {
			// 发送消息退出
			user_conn.Write([]byte(`{"cmd":"error_","data":{"ret":0,"msg":"Server kicked " }}`))
			user_conn.Close()
			area.DeleteConn(sid)
		}

		user_wsconn := area.GetWsConn(sid)
		if user_wsconn != nil {
			// 发送消息退出
			websocket.Message.Send(user_wsconn, `{"cmd":"error_","data":{"ret":0,"msg":"Server kicked " }}`)
			area.DeleteWsConn(sid)
		}
		area.UserUnSubscribeChannel(sid)
		area.DeleteUserssion(sid)
		conn.Write([]byte(`ok`))
	}
	if cmd == "push" {

		sid, _ := ret_json.GetString("sid")
		push_data, _ := ret_json.GetString("data")

		user_conn := area.GetConn(sid)
		if user_conn != nil {
			user_conn.Write([]byte(fmt.Sprintf("%s\r\n", push_data)))
		}
		user_wsconn := area.GetWsConn(sid)
		if user_wsconn != nil {
			websocket.Message.Send(user_wsconn, fmt.Sprintf("%s\r\n", push_data))
		}

		log.Debug("hub_worker push to  --------------->:", sid, push_data)
		conn.Write([]byte(`ok`))
	}

	if cmd == "broatcast" {

		channel, _ := ret_json.GetString("id")
		data, _ := ret_json.GetString("data")
		area.Broatcast(channel, data)
		log.Debug("hub_worker broadcast to :", channel, "   ", data)
		conn.Write([]byte(`ok`))
	}

	if cmd == "get_channels" {

		js1, _ := json2.Marshal(global.Channels)
		fmt.Println("(global.Channels:", (global.Channels))
		conn.Write(js1)
		conn.Close()
	}

	if cmd == "get_session" {

		sid, _ := ret_json.GetString("sid")
		user_session, exist := global.SyncUserSessions.Get(sid)
		js1 := []byte(`{}`)
		if exist {
			js1, _ = json2.Marshal(user_session)
		}
		conn.Write(js1)
		conn.Close()
	}

	if cmd == "get_all_session" {

		var UserSessions = map[string]*z_type.Session{}
		for item := range global.SyncUserSessions.IterItems() {
			UserSessions[item.Key] = item.Value.(*z_type.Session)
		}
		js1, _ := json2.Marshal(UserSessions)
		conn.Write(js1)
		conn.Close()

	}

	if cmd == "update_session" {

		sid, _ := ret_json.GetString("sid")
		data, _ := ret_json.GetString("data")
		tmp, user_session_exist := global.SyncUserSessions.Get(sid)
		var user_session *z_type.Session
		if user_session_exist {
			user_session = tmp.(*z_type.Session)
			user_session.User = data
			global.SyncUserSessions.Set(sid, user_session)
		}

		log.Info("User Session  :", sid, user_session)
		conn.Write([]byte(`ok`))
	}

	if cmd == "get_user_join_channels" {

		sid, _ := ret_json.GetString("sid")
		js1 := []byte(`[]`)

		tmp, ok := global.SyncUserJoinedChannels.Get(sid)
		if ok {
			userJoinedChannels := tmp.([]string)
			js1, _ = json2.Marshal(userJoinedChannels)

		}
		// 发送消息退出
		conn.Write(js1)
		conn.Close()

	}

}
Exemplo n.º 23
0
func upCompose(dockerComposeFile string) {
	dat, err := ioutil.ReadFile(dockerComposeFile)
	check(err)
	response := instainerPost("/compose/up", string(dat))

	defer response.Body.Close()
	contents, err := ioutil.ReadAll(response.Body)
	check(err)

	fmt.Println(string(contents))

	v, err := jason.NewObjectFromBytes(contents)
	data, err := v.GetObjectArray("data")

	banner.Print("instainer")
	fmt.Println("")
	fmt.Println("")

	for _, container := range data {
		username, err := container.GetString("gitUser")
		password, err := container.GetString("gitPassword")

		name, err := container.GetString("name")
		containerId, err := container.GetString("id")

		fmt.Println("Container Name ", name)
		fmt.Println("Container Id  ", containerId)

		fmt.Println("")
		color.Green("------------Git Information------------")
		color.Yellow("Git User      = %s", username)
		color.Yellow("Git Password  = %s", password)
		fmt.Println("")
		fmt.Println("")

		color.Green("----------Volumes Information----------")
		volumes, err := container.GetObjectArray("volumes")
		for _, volume := range volumes {
			mntDir, err := volume.GetString("mntDir")
			gitUrl, err := volume.GetString("gitUrl")
			check(err)
			color.Blue("    %s", mntDir)
			color.Yellow("    Git URL  = %s", gitUrl)
			fmt.Println("")
		}
		fmt.Println("")

		color.Green("------------Port Information------------")
		ports, err := container.GetObjectArray("ports")

		for _, port := range ports {
			dockerPort, err := port.GetString("dockerPort")
			instainerPort, err := port.GetString("instainerPort")
			check(err)
			color.Blue("  Container Port    %s", dockerPort)
			color.Yellow("  Instainer Port    instainer.io:%s", instainerPort)
			fmt.Println("")
		}
		fmt.Println("")

		envVariablesData, err := container.GetStringArray("envVariables")

		if len(envVariablesData) > 0 {
			color.Green("---------Environment Variables----------")

			for _, variable := range envVariablesData {
				color.Yellow("    Variable=Value      = %s", variable)
			}
		}
		fmt.Println("")
		fmt.Println("")
		check(err)
	}

	fmt.Println("Successfully deployed!")
	fmt.Println("")
	fmt.Println("")

}
Exemplo n.º 24
0
func workerTaskWithBufferio(index string, host string, port int) {

	r := rand.New(rand.NewSource(time.Now().UnixNano()))
	idf := fmt.Sprintf("%d%d", r.Intn(9999), rand.Intn(99999))

	fmt.Println(" worker_task tcpAddr:  \n", fmt.Sprintf(host+":%d", port))

	tcpAddr, err := net.ResolveTCPAddr("tcp4", fmt.Sprintf(host+":%d", port))
	checkError(err)
	conn, err := net.DialTCP("tcp", nil, tcpAddr)
	checkError(err)
	//defer conn.Close()
	time.Sleep(10 * time.Millisecond)
	worker_ready := fmt.Sprintf(`%s||%s||%s||%s`, global.DATA_WORKER_CONNECT, "", idf, "")
	fmt.Println("worker_ready:", worker_ready)
	conn.Write([]byte(worker_ready + "\n"))

	cmd := ""
	client_idf := ""
	worker_idf := ""
	task_data := ""

	reader := bufio.NewReader(conn)
	for {
		msg, err := reader.ReadString('\n')
		//fmt.Println( "worker_task recive 5:", msg  )
		if err != nil {
			fmt.Println("worker_task ", " connection error: ", err.Error())
			conn.Close()
			return
		}
		if msg == "" {
			continue
		}

		//fmt.Println("worker_task from ", worker_idf, " receive str:", string(msg))

		ret_arr := strings.Split(msg, "||")

		if len(ret_arr) < 4 {
			//fmt.Println("workeDispath data length error!")
			continue
		}

		//fmt.Println("worke task arr :", ret_arr)
		cmd = ret_arr[0]
		client_idf = ret_arr[1]
		worker_idf = ret_arr[2]
		task_data = ret_arr[3]
		//fmt.Println("worke task cmd :", cmd )
		if cmd == global.DATA_REQ_MSG {

			worker_json, errjson := jason.NewObjectFromBytes([]byte(task_data))
			checkError(errjson)

			//  do some thing
			cmd, _ = worker_json.GetString("cmd")
			//fmt.Printf(" worker_task logic cmd: %s\n", cmd)

			json := fmt.Sprintf(`{"cmd":"%s","data":"%s"}`, cmd, client_idf)
			data := fmt.Sprintf(`%s||%s||%s||%s`, global.DATA_WORKER_REPLY, client_idf, worker_idf, json)
			//fmt.Println(" post : ", data)
			_, err = conn.Write([]byte(data + "\n"))
			checkError(err)
			//time.Sleep(10 * time.Millisecond)

		}
		if cmd == global.DATA_WORKER_CONNECT {

			fmt.Printf(" worker %s  ready!\n", worker_idf)

		}

	}
}
Exemplo n.º 25
0
func appv2(res http.ResponseWriter, req *http.Request) {
	go func() {
		fmt.Println("Spam Detector Active")
		pub = pubnub.NewPubNub(publish_key, subscribe_key, secret_key, cipher_key, ssl) //create a pub/sub subscription

		q, err := pub.Subscribe(chanName, nil) // subscribe to the channel messages are being sent into
		if err != nil {
			panic(err)
		}
		timer := time.NewTimer(10 * time.Second) //for heap clean up

		for {

			select {
			case u := <-q: // if the subscribed channel has a message ready to process
				{

					if u == nil {
						fmt.Println("Ignore message")
						continue
					}
					b := u.(map[string]interface{})
					//fmt.Println(b["properties"])
					//fmt.Println(b)
					c, _ := json.Marshal(b["properties"])

					v, err := jason.NewObjectFromBytes(c)

					if err != nil {
						continue
					}
					//eventType, err := v.GetString("event")
					_, err = v.GetBoolean("isaudio")

					if err != nil {
						//fmt.Println("message is not a girl")
						continue
					} else {
						//fmt.Println("ISAUDIO: ", chck)
					}

					if err == nil {

						toUser, _ := v.GetString("touserName")
						fromUser, _ := v.GetString("fromuserName")
						msg, _ := v.GetString("text")

						//fmt.Println("To:", toUser, "From", fromUser, "Message:", msg)
						//go sendMail(toUser, fromUser, msg)

						go handleMsg(msg, toUser, fromUser) // Handle on new thread

						//go handleMsg(msg, string(fulljson)) // Handle on new thread

					}
				}

			case <-timer.C:
				{

					debug.FreeOSMemory()
					timer.Reset(1 * time.Hour)

				}

			}

		}
	}()
	r := render.New()
	r.JSON(res, http.StatusOK, map[string]string{"Server": "Server has Started"})
}