Exemplo n.º 1
0
func (t *Terminal) output() bool {
	if t.printQuery {
		fmt.Println(string(t.input))
	}
	if len(t.expect) > 0 {
		fmt.Println(t.pressed)
	}
	found := len(t.selected) > 0
	if !found {
		cnt := t.merger.Length()
		if cnt > 0 && cnt > t.cy {
			desc := t.merger.Get(t.cy).AsString(t.ansi)
			pair := strings.Split(desc, " - ")
			err := open.Run(pair[1])
			if err != nil {
				println(err)
			}
			found = true
		}
	} else {
		sels := make([]selectedItem, 0, len(t.selected))
		for _, sel := range t.selected {
			sels = append(sels, sel)
		}
		sort.Sort(byTimeOrder(sels))
		for _, sel := range sels {
			open.Run(*sel.text)
			//fmt.Println(*sel.text)
		}
	}
	return found
}
Exemplo n.º 2
0
func display(plan string) {
	handler := func(w http.ResponseWriter, r *http.Request) {
		defer func() {
			if recover_string := recover(); recover_string != nil {
				error_handler(w, r, http.StatusNotFound)
			}
		}()
		var fileName string
		if r.URL.Path == "/" {
			fileName = "2048/index.html"
		} else {
			fileName = "2048/" + r.URL.Path[1:]
		}
		if _, err := os.Stat(fileName); err == nil {
			// File exists
			http.ServeFile(w, r, fileName)
		} else {
			panic(fmt.Sprintf("File not found %s", fileName))
		}

	}
	http.HandleFunc("/", handler)
	wg := &sync.WaitGroup{}
	wg.Add(1)
	go http.ListenAndServe("localhost:8080", nil)
	open.Run("http://localhost:8080")
	wg.Wait()
}
Exemplo n.º 3
0
func (l *Login) HelpCreateToken(e *Env) (string, error) {
	for i := 0; i < 4; i++ {
		fmt.Fprintf(e.Out, `
Input your account key or press ENTER to generate a new one.
NOTE: on pressing ENTER we'll try to open the url:
	%q
in default browser.
`,
			keysURL,
		)
		fmt.Fprintf(e.Out, `Account Key: `)

		var token string
		fmt.Fscanf(e.In, "%s\n", &token)
		token = strings.TrimSpace(token)
		if token != "" {
			return token, nil
		}

		err := open.Run(keysURL)
		if err != nil {
			fmt.Fprintf(e.Err,
				`Sorry, we couldn’t open the browser for you.
Go here to generate an account key: %q
`,
				keysURL,
			)
		}
	}
	return "", stackerr.New("Account key cannot be empty. Please try again.")
}
Exemplo n.º 4
0
Arquivo: ui.go Projeto: kidaa/lantern
// openExternalUrl opens an external URL of one of our partners automatically
// at startup if configured to do so. It should only open the first time in
// a given session that Lantern is opened.
func openExternalUrl() {
	if openedExternal {
		log.Debugf("Not opening external URL again")
		return
	}
	defer func() {
		openedExternal = true
	}()

	path, s, err := packaged.ReadSettings()
	if err != nil {
		// Let packaged itself log errors as necessary.
		log.Debugf("Could not read yaml from %v: %v", path, err)
		return
	}

	var url string
	if s.StartupUrl == "" {
		return
	} else if strings.HasPrefix(s.StartupUrl, "https://www.facebook.com/manototv") {
		// Here we make sure to override any old manoto URLs with the latest.
		url = "https://www.facebook.com/manototv/app_128953167177144"
	} else {
		url = s.StartupUrl
	}
	time.Sleep(4 * time.Second)
	err = open.Run(url)
	if err != nil {
		log.Errorf("Error opening external page to `%v`: %v", uiaddr, err)
	}
}
Exemplo n.º 5
0
Arquivo: ui.go Projeto: shizhh/lantern
// Show opens the UI in a browser. Note we know the UI server is
// *listening* at this point as long as Start is correctly called prior
// to this method. It may not be reading yet, but since we're the only
// ones reading from those incoming sockets the fact that reading starts
// asynchronously is not a problem.
func Show() {
	go func() {
		err := open.Run(uiaddr)
		if err != nil {
			log.Errorf("Error opening page to `%v`: %v", uiaddr, err)
		}
		if externalUrl != "NO"+"_URL" && !openedExternal {
			time.Sleep(4 * time.Second)
			err = open.Run(externalUrl)
			if err != nil {
				log.Errorf("Error opening external page to `%v`: %v", uiaddr, err)
			}
			openedExternal = true
		}
	}()
}
Exemplo n.º 6
0
func getAccessToken(consumerKey, consumerSecret string) (a AccessToken, err error) {
	c := oauth.NewConsumer(
		consumerKey,
		consumerSecret,
		oauth.ServiceProvider{
			RequestTokenUrl:   "https://api.twitter.com/oauth/request_token",
			AuthorizeTokenUrl: "https://api.twitter.com/oauth/authorize",
			AccessTokenUrl:    "https://api.twitter.com/oauth/access_token",
		})

	requestToken, url, err := c.GetRequestTokenAndUrl("oob")
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("(1) Go to: " + url)
	fmt.Println("(2) Grant access, you should get back a verification code.")
	open.Run(url)
	fmt.Print("(3) Enter that verification code here: ")

	verificationCode := ""
	fmt.Scanln(&verificationCode)

	authToken, err := c.AuthorizeToken(requestToken, verificationCode)
	if err != nil {
		log.Fatal(err)
	}
	a.Token = authToken.Token
	a.Secret = authToken.Secret

	err = saveAccessToken(a)

	return
}
Exemplo n.º 7
0
func main() {
	err := open.Run(DuckDuckGo + strings.Join(os.Args[1:], Sep))

	if err != nil {
		log.Panic(err)
	}
}
Exemplo n.º 8
0
func readDropBoxAppConfig(appName string) (*DropBoxAppConfig, error) {
	s := scan.CliScan{
		Scans: []scan.Scan{
			{Name: "token",
				Value: "",
				Usage: "please your dropbox accessToken",
				Env:   "",
			},
		},
	}

	ac := appConfig.NewDefaultAppConfig(appName)
	data, err := ac.ReadAppConfig()
	accessToken := string(data)
	if err != nil || accessToken == "" {

		// OAuth jump
		open.Run(accessTokenURL)

		// Scan accessToken
		accessToken = s.Scan("token")

		// config write
		if err := ac.WriteAppConfig([]byte(accessToken)); err != nil {
			return nil, err
		}
	}

	return &DropBoxAppConfig{*ac}, nil
}
Exemplo n.º 9
0
func main() {
	flag.Parse()

	if flag.NArg() != 1 {
		print_usage(os.Args[0])
		os.Exit(1)
	}

	remotes, err := DetectRemote(flag.Arg(0))
	if err != nil {
		fmt.Fprintf(os.Stderr, "Error: %s\n", err.Error())
		os.Exit(1)
	}

	for _, r := range remotes {
		url, err := MangleURL(r.Url)
		if err != nil {
			fmt.Fprintf(os.Stderr, "remote:%s, %s\n", r.Name, err.Error())
			continue
		}

		open.Run(url)
		break
	}
}
Exemplo n.º 10
0
func (plugin OpenPlugin) runServiceOpen(cliConnection plugin.CliConnection, args []string) {
	output, err := cliConnection.CliCommandWithoutTerminalOutput("service", args[1], "--guid")
	if err != nil {
		fmt.Fprintln(os.Stdout, "error: service does not exist")
		os.Exit(1)
	}
	serviceInstanceGUID := strings.TrimSpace(output[0])

	output, err = cliConnection.CliCommandWithoutTerminalOutput("curl", fmt.Sprintf("/v2/service_instances/%s", serviceInstanceGUID))
	if err != nil {
		fmt.Fprintln(os.Stdout, "error: service does not exist")
		os.Exit(1)
	}
	jsonStr := ""
	for _, line := range output {
		jsonStr += line + "\n"
	}

	response := serviceInstanceResponse{}
	json.Unmarshal([]byte(jsonStr), &response)

	url := response.Entity.DashboardURL
	if url == "" {
		fmt.Println("No dashboard available")
	} else {
		open.Run(url)
	}
}
Exemplo n.º 11
0
func init() {
	// Filters is the default set of global filters.
	revel.Filters = []revel.Filter{
		revel.PanicFilter,             // Recover from panics and display an error page instead.
		revel.RouterFilter,            // Use the routing table to select the right Action
		revel.FilterConfiguringFilter, // A hook for adding or removing per-Action filters.
		revel.ParamsFilter,            // Parse parameters into Controller.Params.
		revel.SessionFilter,           // Restore and write the session cookie.
		revel.FlashFilter,             // Restore and write the flash cookie.
		revel.ValidationFilter,        // Restore kept validation errors and save new ones from cookie.
		revel.I18nFilter,              // Resolve the requested language
		HeaderFilter,                  // Add some security based headers
		revel.InterceptorFilter,       // Run interceptors around the action.
		revel.CompressFilter,          // Compress the result.
		revel.ActionInvoker,           // Invoke the action.
	}

	// register startup functions with OnAppStart
	// ( order dependent )
	// revel.OnAppStart(InitDB)
	// revel.OnAppStart(FillCache)
	// Create a link back to node-webkit using the environment variable
	// populated by golang-nw's node-webkit code
	revel.OnAppStart(func() { open.Run("http://localhost:9000") })

}
Exemplo n.º 12
0
func main() {
	var path string

	flag.Parse()

	if flag.NArg() != 1 {
		path = "./"
		// print_usage(os.Args[0])
		// os.Exit(1)
	} else {
		path = flag.Arg(0)
	}

	// remotes, err := DetectRemote(flag.Arg(0))
	remotes, err := DetectRemote(path)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Error: %s\n", err.Error())
		os.Exit(1)
	}

	for _, r := range remotes {
		url, err := MangleURL(r.Url)
		if err != nil {
			fmt.Fprintf(os.Stderr, "remote:%s, %s\n", r.Name, err.Error())
			continue
		}

		open.Run(url)
		break
	}
}
Exemplo n.º 13
0
func main() {
	input := bufio.NewScanner(os.Stdin)

	config := Config{}
	config_source, err := ioutil.ReadFile("config.json")
	if err != nil {
		fmt.Fprintf(os.Stderr, "Can't read config.json: %v\n", err.Error())
		os.Exit(1)
	}
	if err := json.Unmarshal([]byte(config_source), &config); err != nil {
		fmt.Fprintf(os.Stderr, "Can't decode config.json: %v\n", err.Error())
		os.Exit(1)
	}

	if config.ClientId == "" {
		fmt.Fprintf(os.Stderr, "Invalid client_id in config.json\n")
		os.Exit(1)
	}

	open.Run(fmt.Sprintf("https://oauth.vk.com/authorize?client_id=%s&scope=audio"+
		"&redirect_uri=https://oauth.vk.com/blank.html&display=page&response_type=token", config.ClientId))
	fmt.Printf("Enter url from browser window:\n")
	input.Scan()
	oauthResponse := input.Text()
	if access_token, err := parseOauthResponse(oauthResponse); err == nil {
		downloadMusic(access_token)
	} else {
		fmt.Fprintf(os.Stderr, "Error: %v\n", err.Error())
		os.Exit(1)
	}

}
Exemplo n.º 14
0
Arquivo: events.go Projeto: ovh/tatcli
func (ui *tatui) openInTatwebui() {
	msg := ui.currentListMessages[ui.selectedPaneMessages][ui.uilists[uiMessages][ui.selectedPaneMessages].position]
	base := strings.TrimSpace(viper.GetString("tatwebui-url"))

	if base == "" {
		ui.msg.Text = "You need to set TatWebui URL in your config file, see /set-tatwebui-url"
		ui.render()
		return
	}

	view := "standardview"

	// search view setted on topic parameters
	for _, p := range ui.currentTopic.Parameters {
		if p.Key == "tatwebui.view.restricted" && p.Value != "" {
			view = strings.TrimSpace(strings.Replace(p.Value, "-list", "", 1))
			break
		} else if p.Key == "tatwebui.view.default" && p.Value != "" {
			view = strings.TrimSpace(strings.Replace(p.Value, "-list", "", 1))
		}
	}
	if !strings.HasSuffix(base, "/") {
		view = "/" + view
	}
	url := fmt.Sprintf("%s%s/list%s?idMessage=%s", base, view, ui.currentTopic.Topic, msg.ID)
	open.Run(url)
}
Exemplo n.º 15
0
func handle(conn net.Conn) {
	defer conn.Close()
	log.Printf("Request from %s", conn.RemoteAddr())

	if !firewall.IsAllowed(conn.RemoteAddr()) {
		fmt.Fprintf(conn, "Connect is not allowed from %s", conn.RemoteAddr())
		return
	}

	line, err := bufio.NewReader(conn).ReadString('\000')

	if err != nil {
		log.Println(err)
		conn.Write([]byte(err.Error()))
		return
	}
	body := line[:len(line)-1]

	err = open.Run(string(body))
	if err != nil {
		log.Println(err)
		conn.Write([]byte(err.Error()))
		return
	}
}
Exemplo n.º 16
0
func doOpen(c *cli.Context) {
	remote := c.Args().Get(0)
	tree := c.Args().Get(1)

	gitconfig, configErr := NewGitConfig()
	if configErr != nil {
		fmt.Println(configErr)
		return
	}

	if remote == "" {
		result, currentBranchErr := gitconfig.RemoteURLFromCurrentBranch()
		if currentBranchErr != nil {
			fmt.Println(currentBranchErr)
			return
		}
		remote = result
	}

	githubUrl, remoteURLErr := gitconfig.RemoteURL(remote)
	if remoteURLErr != nil {
		fmt.Println(remoteURLErr)
	}

	var openURL string
	if tree != "" {
		openURL = fmt.Sprintf("%s/tree/%s", githubUrl, tree)
	} else {
		openURL = githubUrl
	}
	openErr := open.Run(openURL)
	if openErr != nil {
		fmt.Println(openErr)
	}
}
Exemplo n.º 17
0
func main() {
	port := flag.Int("p", 8080, "port to listen on")
	cache := flag.Bool("c", false, "enable caching")
	browser := flag.Bool("b", false, "open browser")

	flag.Parse()

	directory := flag.Arg(0)
	dirPath, err := filepath.Abs(directory)
	if err != nil {
		panic(err)
	}

	address := fmt.Sprintf(":%d", *port)

	ip, err := externalIP()
	if err != nil {
		fmt.Println(err)
		ip = "0.0.0.0"
	}

	url := fmt.Sprintf("http://%s%s", ip, address)
	fmt.Printf("Serving '%s/' on '%s'\n", dirPath, url)
	if *browser {
		open.Run(url)
	}
	// Blocks here
	log.Fatal(ServeDir(dirPath, address, *cache))
}
Exemplo n.º 18
0
func main() {

	flag.Parse()

	data := Data{
		"SVG -> PDF",
		time.Now().Format("_2 Jan 2006 15:04:05"),
		20150803,
		"Строка кириллицей",
		true,
	}

	var err error

	// Load template from file
	template, err := template.ParseFiles(*inputFile)
	chk(err)

	// Store template to buffer
	buf := new(bytes.Buffer)
	err = template.Execute(buf, data)
	chk(err)

	// Convert via external application
	// Install before use
	// # apt-get install librsvg2-bin
	// or
	// # apt-get install inkscape
	var cmd *exec.Cmd

	if *converter == "inkscape" {
		fmt.Println("Generate via inkscape")
		cmd = exec.Command("inkscape", "--without-gui", "/dev/stdin", "--export-pdf=/dev/stdout")
		if *outputPng != "" {
			cmd.Args = append(cmd.Args, "--export-png", *outputPng)
		}
	} else {
		fmt.Println("Generate via rsvg-convert")
		cmd = exec.Command("rsvg-convert", "-f", "pdf")
	}
	cmd.Stdin = bytes.NewReader(buf.Bytes())

	// Write pdf to file
	out, err := os.OpenFile(*outputFile, os.O_CREATE|os.O_WRONLY, 0666)
	chk(err)
	defer out.Close()
	cmd.Stdout = out

	timeStart := time.Now().UnixNano()
	err = cmd.Run() // Syncronous run external application
	chk(err)
	timeEnd := time.Now().UnixNano()

	fmt.Println("Conversion time (ms)", (timeEnd-timeStart)/1000000)

	// Open output file using the OS's default application
	open.Run(*outputFile)

}
Exemplo n.º 19
0
func main() {
	cmd := exec.Command("git", "rev-parse", "--abbrev-ref", "HEAD")
	out, e := cmd.Output()
	failOnError(e)

	val := strings.Trim(string(out), "f/#")
	open.Run("https://192.168.100.1/redmine/issues/" + val)
}
Exemplo n.º 20
0
func (u *URI) Open(param *param.OpenParam, _ *struct{}) error {
	conn := <-connCh
	uri := param.URI
	if param.TransLoopback {
		uri = u.translateLoopbackIP(param.URI, conn)
	}
	return open.Run(uri)
}
Exemplo n.º 21
0
Arquivo: ui.go Projeto: kidaa/lantern
// Show opens the UI in a browser. Note we know the UI server is
// *listening* at this point as long as Start is correctly called prior
// to this method. It may not be reading yet, but since we're the only
// ones reading from those incoming sockets the fact that reading starts
// asynchronously is not a problem.
func Show() {
	go func() {
		err := open.Run(uiaddr)
		if err != nil {
			log.Errorf("Error opening page to `%v`: %v", uiaddr, err)
		}
		openExternalUrl()
	}()
}
Exemplo n.º 22
0
func main() {
	if len(os.Args) != 2 {
		fmt.Fprintln(os.Stderr, "qiita-go [word]")
		os.Exit(1)
	}
	word := os.Args[1]
	url := "http://qiita.com/search?utf8=✓&sort=rel&q=" + word
	open.Run(url)
}
Exemplo n.º 23
0
func configureOA() {
	oa_url := base_url + "?scope=" + scope + "&client_id=" + client_id
	output("Creating token request for Slackcat")
	err := open.Run(oa_url)
	if err != nil {
		output("Please open the below URL in your browser to authorize SlackCat")
		output(oa_url)
	}
}
Exemplo n.º 24
0
func AuthUser(entity string, postType string) (client *tent.Client, err error) {
	var meta *tent.MetaPost

	// meta post
	meta, err = tent.Discover(entity)
	if err != nil {
		return
	}

	client = &tent.Client{Servers: meta.Servers}

	// app post
	post := tent.NewAppPost(&tent.App{
		Name: "Tent Scrobbler",
		URL:  "https://app.example.com",
		Types: tent.AppTypes{
			Write: []string{postType},
		},
		RedirectURI: "https://app.example.com/oauth",
		Scopes:      []string{"permissions"},
	})
	err = client.CreatePost(post)
	if err != nil {
		return
	}

	// credentials
	client.Credentials, _, err = post.LinkedCredentials()
	if err != nil {
		return
	}

	// redirect url
	oauthURL := meta.Servers[0].URLs.OAuthURL(post.ID, "randomState")

	fmt.Println("accept the authorisation request and paste the code back in")

	err = open.Run(oauthURL)
	if err != nil {
		return
	}

	// input code
	var code string
	_, err = fmt.Scanf("%s", &code)
	if err != nil {
		return
	}

	// request access token
	client.Credentials, err = client.RequestAccessToken(code)
	if err != nil {
		return
	}

	return client, nil
}
func (this *DbDumperManager) ShowDumpFromInstanceName(serviceInstance string, recent bool, dumpDateOrNumber string, seeAllDumps bool, tags string) error {
	selectedDump, err := this.selectDump(serviceInstance, recent, dumpDateOrNumber, seeAllDumps, tags)
	if err != nil {
		return err
	}
	if selectedDump.ShowURL == "" {
		return errors.New("This dump cannot be showed, generally this mean that the file is only in binary.")
	}
	return open.Run(selectedDump.ShowURL)
}
Exemplo n.º 26
0
func (o *Orange) Run(files ...string) {
	o.httpServer = NewHTTPServer(o.port)
	o.httpServer.Listen()

	for _, file := range files {
		addr := fmt.Sprintf("http://localhost:%d/%s", o.port, file)
		open.Run(addr)
	}

	<-o.stop
}
Exemplo n.º 27
0
func setupSysTrayReal() {

	systray.SetIcon(icon.Data)
	mUrl := systray.AddMenuItem("Go to Arduino Create (staging)", "Arduino Create")
	mDebug := systray.AddMenuItem("Open debug console", "Debug console")
	menuVer := systray.AddMenuItem("Agent version "+version+"-"+git_revision, "")
	mPause := systray.AddMenuItem("Quit Plugin", "")
	//mQuit := systray.AddMenuItem("Quit Plugin", "")

	menuVer.Disable()

	go func() {
		<-mPause.ClickedCh
		ports, _ := serial.GetPortsList()
		for _, element := range ports {
			spClose(element)
		}
		systray.Quit()
		*hibernate = true
		restart("")
	}()

	// go func() {
	// 	<-mQuit.ClickedCh
	// 	systray.Quit()
	// 	exit()
	// }()

	go func() {
		<-mDebug.ClickedCh
		open.Run("http://localhost:8989")
		logAction("log on")
	}()

	// We can manipulate the systray in other goroutines
	go func() {
		<-mUrl.ClickedCh
		open.Run("http://create-staging.arduino.cc")
	}()
}
Exemplo n.º 28
0
func Authorize(tokenDir, tokenFile string) {
	err := os.MkdirAll(tokenDir, 0777)
	if err != nil {
		fmt.Printf("Failed to create directory for the token at %s\n", tokenDir)
	}
	cachefile := filepath.Join(tokenDir, tokenFile)

	if clientId == "" {
		clientId = productionClientId
	}
	if clientSecret == "" {
		clientSecret = productionClientSecret
	}
	config := &oauth.Config{
		ClientId:     clientId,
		ClientSecret: clientSecret,
		RedirectURL:  redirectURL,
		Scope:        scope,
		AuthURL:      authURL,
		TokenURL:     tokenURL,
		TokenCache:   oauth.CacheFile(cachefile),
	}
	transport := &oauth.Transport{Config: config}
	_, err = config.TokenCache.Token()

	// do we already have access?
	if err != nil {

		url := config.AuthCodeURL("")
		e := open.Run(url)
		if e != nil {
			fmt.Printf("Counldn't open the browser because %s\n", e.Error())
			fmt.Println("Please open the following URL in your browser and paste the access code here:")
			fmt.Println(url)
		} else {
			fmt.Println("Openning the browser so you can approve the client access")
		}

		var s string
		fmt.Println("Authorization Code:")
		fmt.Scan(&s)

		_, err := transport.Exchange(s)
		if err != nil {
			log.Fatal("Exchange:", err)
		}

		fmt.Printf("Token is cached in %v\n", config.TokenCache)
		os.Exit(1)
	}
}
Exemplo n.º 29
0
func openSnippetWithEditor(s *Snippet) {
	if len(conf.Editor) > 0 {
		err := open.RunWith(s.Path, conf.Editor)
		if err != nil {
			log.Fatalf("can't open %s with %s. please check your settings.", s.Path, conf.Editor)
		}

	} else {
		err := open.Run(s.Path)
		if err != nil {
			log.Fatalf("can't open %s. please check your settings.", s.Path)
		}
	}
}
Exemplo n.º 30
0
func configureOA() {
	oa_url := base_url + "?scope=" + scope + "&client_id=" + client_id
	output("Creating token request for Slackcat")
	err := open.Run(oa_url)
	if err != nil {
		output("Please open the below URL in your browser to authorize SlackCat")
		output(oa_url)
	}
	//	_, err := fmt.Scanf("%s", &i)
	dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
	failOnError(err, "", true)
	fmt.Println(dir)
	os.Exit(0)
}