示例#1
0
func InitPlugin(createVM func() (*modules.JsVm, error)) *modules.Plugin {

	p1 := modules.Plugin{
		Name: "httplistener",
		Init: func(vm *modules.JsVm) otto.Value {
			obj, _ := vm.Object("({})")
			obj.Set("addr", ":8081")
			obj.Set("start", func(c otto.FunctionCall) otto.Value {
				addrObj, _ := obj.Get("addr")
				addr, _ := addrObj.ToString()

				go startServer(addr, createVM)
				return otto.TrueValue()
			})
			obj.Set("startAndWait", func(c otto.FunctionCall) otto.Value {
				addrObj, _ := obj.Get("addr")
				addr, _ := addrObj.ToString()

				startServer(addr, createVM)
				return otto.TrueValue()
			})
			return obj.Value()
		},
	}

	return &p1
}
示例#2
0
func (i *instance) loadplugin(name string) error {
	b, err := ioutil.ReadFile(name)
	_, filename := filepath.Split(name)

	if _, ok := i.Pluginfuncs[filename]; ok {
		delete(i.Pluginfuncs, filename)
		delete(i.Plugindocs, filename)
	}

	if err != nil {
		return err
	}

	m := make(map[string]otto.Value)
	i.js.Set("Subscribe", func(call otto.FunctionCall) otto.Value {
		if len(call.ArgumentList) >= 2 && call.ArgumentList[0].IsString() && call.ArgumentList[1].IsFunction() {
			name := call.ArgumentList[0].String()
			f := call.ArgumentList[1]
			if strings.HasPrefix(name, "regex:") {
				_, err := regexp.Compile(name[len("regex:"):])
				if err != nil {
					i.Irc.Privmsg(i.Irccfg.Channel, "Regex error: "+err.Error()+" - Regex subscribe was not successful")
					return otto.FalseValue()
				}
			}
			m[name] = f
			return otto.TrueValue()
		} else {
			return otto.FalseValue()
		}
	})

	md := make(map[string]string)
	i.js.Set("Doc", func(call otto.FunctionCall) otto.Value {
		if len(call.ArgumentList) >= 2 && call.ArgumentList[0].IsString() && call.ArgumentList[1].IsString() {
			name := call.ArgumentList[0].String()
			doc := call.ArgumentList[1].String()
			md[name] = doc
			return otto.TrueValue()
		} else {
			return otto.FalseValue()
		}
	})

	_, err = i.js.Run(string(b))
	i.js.Set("Subscribe", nil)
	i.js.Set("Doc", nil)

	if err != nil {
		fmt.Println(err.Error())
		return err
	} else {
		i.Pluginfuncs[filename] = m
		i.Plugindocs[filename] = md
		return nil
	}

}
示例#3
0
func registerVM(vm *modules.JsVm) otto.Value {
	obj, _ := vm.Object("({})")

	obj.Set("set", func(c otto.FunctionCall) otto.Value {
		key, _ := c.Argument(0).ToString()
		val, _ := c.Argument(1).ToString()
		kvCache[key] = val
		return otto.TrueValue()
	})
	obj.Set("get", func(c otto.FunctionCall) otto.Value {
		key, _ := c.Argument(0).ToString()
		val, ok := kvCache[key]
		if !ok {
			return otto.UndefinedValue()
		}
		retV, _ := otto.ToValue(val)
		return retV
	})

	obj.Set("all", func(c otto.FunctionCall) otto.Value {
		kvObj, err := vm.Object("({})")
		for k, v := range kvCache {
			kvObj.Set(k, v)
		}
		return modules.ToResult(vm, kvObj, err)
	})

	obj.Set("load", func(c otto.FunctionCall) otto.Value {
		path, _ := c.Argument(0).ToString()
		content, err := ioutil.ReadFile(path)
		if err != nil {
			return modules.ToResult(vm, nil, err)
		}
		err = json.Unmarshal(content, &kvCache)
		if err != nil {
			return modules.ToResult(vm, nil, err)
		}

		return otto.TrueValue()
	})

	obj.Set("save", func(c otto.FunctionCall) otto.Value {
		path, _ := c.Argument(0).ToString()
		content, _ := json.Marshal(kvCache)
		ioutil.WriteFile(path, content, 0777)
		return otto.TrueValue()
	})

	obj.Set("remove", func(c otto.FunctionCall) otto.Value {
		key, _ := c.Argument(0).ToString()
		delete(kvCache, key)
		return otto.TrueValue()
	})
	return obj.Value()
}
示例#4
0
func ResponseWriterToJso(o *otto.Object, w http.ResponseWriter) {
	o.Set("write", func(c otto.FunctionCall) otto.Value {
		text, _ := c.Argument(0).ToString()
		w.Write([]byte(text))
		return otto.TrueValue()
	})
	o.Set("writeHeader", func(c otto.FunctionCall) otto.Value {
		statusCode, _ := c.Argument(0).ToInteger()
		w.WriteHeader(int(statusCode))
		return otto.TrueValue()
	})
}
示例#5
0
func InjectLevelDB(jsEngine *JSEngine, db *leveldb.DB) {
	jsEngine.Run("var db = {};")
	dbValue, _ := jsEngine.Get("db")
	dbObj := dbValue.Object()
	dbObj.Set("put", func(call otto.FunctionCall) otto.Value {
		key, err := call.Argument(0).ToString()
		if err != nil {
			log.Println("Error:", err.Error())
			return otto.FalseValue()
		}
		value, err := call.Argument(1).ToString()
		if err != nil {
			log.Println("Error:", err.Error())
			return otto.FalseValue()
		}

		err = db.Put([]byte(key), []byte(value), nil)
		if err != nil {
			log.Println("Error:", err.Error())
			return otto.FalseValue()
		}
		return otto.TrueValue()
	})
	dbObj.Set("get", func(call otto.FunctionCall) otto.Value {
		key, err := call.Argument(0).ToString()
		if err != nil {
			log.Println("Error:", err.Error())
			return otto.FalseValue()
		}
		data, err := db.Get([]byte(key), nil)
		if err != nil {
			log.Println("Error:", err.Error())
			return otto.FalseValue()
		}
		v, _ := otto.ToValue(string(data))
		return v
	})
	dbObj.Set("remove", func(call otto.FunctionCall) otto.Value {
		key, err := call.Argument(0).ToString()
		if err != nil {
			log.Println("Error:", err.Error())
			return otto.FalseValue()
		}
		err = db.Delete([]byte(key), nil)
		if err != nil {
			log.Println("Error:", err.Error())
			return otto.FalseValue()
		}
		return otto.TrueValue()
	})
}
示例#6
0
// Add Response API
func plurk_AddResponse(call otto.FunctionCall) otto.Value {

	plurkID, _ := call.Argument(0).ToInteger()
	message, _ := call.Argument(1).ToString()
	qualifier, _ := call.Argument(2).ToString()

	if plurkID == 0 {
		logger.Error("Plurk ID not specify, add response failed!")
		return otto.FalseValue()
	}

	if len(message) <= 0 || message == "undefined" {
		logger.Error("No plurk content specify, add response failed!")
		return otto.FalseValue()
	}

	if qualifier == "undefined" {
		qualifier = ":"
	}

	responses := client.GetResponses()
	res, err := responses.ResponseAdd(int(plurkID), message, qualifier)

	if err != nil {
		logger.Error("Add response failed, because %s", err.Error())
	}

	logger.Info("Add response success, content is %s", res.RawContent)

	return otto.TrueValue()
}
示例#7
0
func InitPlugin() *modules.Plugin {

	p1 := modules.Plugin{
		Name: "mail",
		Init: func(vm *modules.JsVm) otto.Value {
			o, _ := vm.Object("({})")

			o.Set("loadMailSettings", func(c otto.FunctionCall) otto.Value {
				loadSettings(vm)
				return otto.TrueValue()
			})
			o.Set("send", func(c otto.FunctionCall) otto.Value {
				loadSettings(vm)
				recv, _ := c.Argument(0).ToString()
				subject, _ := c.Argument(1).ToString()
				msg, _ := c.Argument(2).ToString()

				err := sendmail(recv, subject, msg, "")

				return modules.ToResult(vm, true, err)
			})
			return o.Value()
		},
	}

	return &p1
}
示例#8
0
func (pm *PluginManager) InitUtilsJSBridge() {
	bridge := &pmUtilsJSBridge{
		GetPage: func(call otto.FunctionCall) otto.Value {
			var err error
			switch {
			case len(call.ArgumentList) == 1 && call.ArgumentList[0].IsString():
				if page, err := utils.GetPage(call.Argument(0).String()); err == nil {
					if val, err := pm.js.ToValue(page); err == nil {
						return val
					}
				}
				pm.log.Printf("[UTILS] GetPage errored: %s\n", err)
			case len(call.ArgumentList) == 3 && call.ArgumentList[0].IsString() && call.ArgumentList[1].IsString() && call.ArgumentList[2].IsString():
				if page, err := utils.GetPageWithAuth(call.Argument(0).String(), call.Argument(1).String(), call.Argument(2).String()); err == nil {
					if val, err := pm.js.ToValue(page); err == nil {
						return val
					}
				}
				pm.log.Printf("[UTILS] GetPageWithAuth errored: %s\n", err)
			}
			return otto.FalseValue()
		},
		ExtractURL: func(call otto.FunctionCall) otto.Value {
			var err error
			if len(call.ArgumentList) == 1 && call.ArgumentList[0].IsString() {
				if url, err := utils.ExtractURL(call.Argument(0).String()); err == nil {
					if val, err := pm.js.ToValue(url); err == nil {
						return val
					}
				}
				pm.log.Printf("[UTILS] ExtractURL errored: %s\n", err)
			}
			return otto.FalseValue()
		},
		ExtractTitle: func(call otto.FunctionCall) otto.Value {
			var err error
			if len(call.ArgumentList) == 1 && call.ArgumentList[0].IsString() {
				if title, err := utils.ExtractTitle(call.Argument(0).String()); err == nil {
					if val, err := pm.js.ToValue(title); err == nil {
						return val
					}
				}
				pm.log.Printf("[UTILS] ExtractTitle errored: %s\n", err)
			}
			return otto.FalseValue()
		},
		Sleep: func(call otto.FunctionCall) otto.Value {
			var err error
			if len(call.ArgumentList) == 1 && call.ArgumentList[0].IsNumber() {
				if i, err := call.Argument(0).ToInteger(); err == nil {
					utils.Sleep(i)
					return otto.TrueValue()
				}
				pm.log.Printf("[UTILS] Sleep errored: %s\n", err)
			}
			return otto.FalseValue()
		},
	}
	pm.js.Set("UTILS", bridge)
}
示例#9
0
func registerVM(vm *modules.JsVm) otto.Value {
	watcher, err := fsnotify.NewWatcher()
	//defer watcher.Close()
	if err != nil {
		log.Println(pluginName + " " + err.Error())
	}
	obj, _ := vm.Object("({})")

	obj.Set("watchDir", func(c otto.FunctionCall) otto.Value {
		path, _ := c.Argument(0).ToString()
		err := watcher.Add(path)
		return modules.ToResult(vm, true, err)
	})

	obj.Set("start", func(c otto.FunctionCall) otto.Value {
		log.Println(pluginName + " start")
		go func() {
			for {
				select {
				case ev := <-watcher.Events:
					log.Println("event:", ev.String())
				case err := <-watcher.Errors:
					log.Println("error:", err)
				}
			}
		}()
		return otto.TrueValue()
	})
	return obj.Value()
}
示例#10
0
// Add Plurk API
func plurk_AddPlurk(call otto.FunctionCall) otto.Value {
	message, _ := call.Argument(0).ToString()
	qualifier, _ := call.Argument(1).ToString()
	lang, _ := call.Argument(2).ToString()

	// No message specify, return error
	if len(message) <= 0 {
		return otto.FalseValue()
	}

	// Default qualifier
	if qualifier == "undefined" {
		qualifier = ":"
	}

	if lang == "undefined" {
		lang = "en"
	}

	timeline := client.GetTimeline()
	res, err := timeline.PlurkAdd(message, qualifier, make([]int, 0), false, lang, true)

	if err != nil {
		logger.Error("Add Plurk failed, because %s", err.Error())
		return otto.FalseValue()
	}

	logger.Info("New plurk added, content is %s", res.RawContent)

	return otto.TrueValue()
}
示例#11
0
func (js *jsre) unlock(call otto.FunctionCall) otto.Value {
	addr, err := call.Argument(0).ToString()
	if err != nil {
		fmt.Println(err)
		return otto.FalseValue()
	}
	seconds, err := call.Argument(2).ToInteger()
	if err != nil {
		fmt.Println(err)
		return otto.FalseValue()
	}
	arg := call.Argument(1)
	var passphrase string
	if arg.IsUndefined() {
		fmt.Println("Please enter a passphrase now.")
		passphrase, err = readPassword("Passphrase: ", true)
		if err != nil {
			utils.Fatalf("%v", err)
		}
	} else {
		passphrase, err = arg.ToString()
		if err != nil {
			fmt.Println(err)
			return otto.FalseValue()
		}
	}
	am := js.ethereum.AccountManager()
	err = am.TimedUnlock(common.FromHex(addr), passphrase, time.Duration(seconds)*time.Second)
	if err != nil {
		fmt.Printf("Unlock account failed '%v'\n", err)
		return otto.FalseValue()
	}
	return otto.TrueValue()
}
示例#12
0
// Sleep will block the console for the specified number of seconds.
func (b *bridge) Sleep(call otto.FunctionCall) (response otto.Value) {
	if call.Argument(0).IsNumber() {
		sleep, _ := call.Argument(0).ToInteger()
		time.Sleep(time.Duration(sleep) * time.Second)
		return otto.TrueValue()
	}
	return throwJSException("usage: sleep(<number of seconds>)")
}
示例#13
0
文件: executor.go 项目: postman0/xep
func NewExecutor(s stream.Stream) *Executor {
	e := &Executor{
		incomingScripts: make(chan string),
		outgoingMsgs:    make(chan string),
		incomingEvents:  make(chan IncomingEvent),
		eventHandlers:   make(map[string]map[string]otto.Value),
	}
	e.xmppStream = s
	e.vm = otto.New()

	send := func(call otto.FunctionCall) otto.Value {
		str, _ := call.Argument(0).ToString()
		e.outgoingMsgs <- str
		return otto.UndefinedValue()
	}

	addHandler := func(call otto.FunctionCall) otto.Value {
		evtName, err := call.Argument(0).ToString()
		handlerName, err := call.Argument(1).ToString()
		if err != nil {
			return otto.FalseValue()
		}
		val := call.Argument(2)
		if !val.IsFunction() {
			return otto.FalseValue()
		}
		handlers, ok := e.eventHandlers[evtName]
		if !ok {
			e.eventHandlers[evtName] = map[string]otto.Value{handlerName: val}
		} else {
			handlers[handlerName] = val
		}
		return otto.TrueValue()
	}

	listHandlers := func(call otto.FunctionCall) otto.Value {
		evtName, err := call.Argument(0).ToString()
		if err != nil {
			return otto.UndefinedValue()
		}
		list := []string{}
		for handlerName := range e.eventHandlers[evtName] {
			list = append(list, handlerName)
		}
		val, err := e.vm.ToValue(list)
		if err != nil {
			return otto.UndefinedValue()
		} else {
			return val
		}
	}

	chatLibrary, _ := e.vm.Object("Chat = {};")
	chatLibrary.Set("send", send)
	chatLibrary.Set("addEventHandler", addHandler)
	chatLibrary.Set("listEventHandlers", listHandlers)
	return e
}
示例#14
0
func registerVM(vm *modules.JsVm) otto.Value {
	obj, _ := vm.Object("({})")
	obj.Set("sleep", func(c otto.FunctionCall) otto.Value {
		sec, _ := c.Argument(0).ToFloat()
		time.Sleep(time.Duration(sec) * time.Millisecond)
		return otto.TrueValue()
	})
	return obj.Value()
}
示例#15
0
// Sleep will halt the console for arg[0] seconds.
func (self *Jeth) Sleep(call otto.FunctionCall) (response otto.Value) {
	if len(call.ArgumentList) >= 1 {
		if call.Argument(0).IsNumber() {
			sleep, _ := call.Argument(0).ToInteger()
			time.Sleep(time.Duration(sleep) * time.Second)
			return otto.TrueValue()
		}
	}
	return throwJSExeception("usage: sleep(<sleep in seconds>)")
}
示例#16
0
文件: otto.go 项目: hattya/aster
func os_rename(call otto.FunctionCall) otto.Value {
	if 2 <= len(call.ArgumentList) {
		src, _ := call.ArgumentList[0].ToString()
		dst, _ := call.ArgumentList[1].ToString()
		if os.Rename(src, dst) != nil {
			return otto.TrueValue()
		}
	}
	return otto.UndefinedValue()
}
示例#17
0
/*
Executes a JS script from inside the currently executing JS code.
Should only be called from inside an RPC routine.
*/
func (self *JSRE) loadScript(call otto.FunctionCall) otto.Value {
	file, err := call.Argument(0).ToString()
	if err != nil {
		return otto.FalseValue()
	}
	if err := self.execWithoutEQ(file); err != nil { // loadScript is only called from inside js
		fmt.Println("err:", err)
		return otto.FalseValue()
	}

	return otto.TrueValue()
}
示例#18
0
func (pm *PluginManager) InitDebugJSBridge() {
	bridge := &pmDebugJSBridge{
		StackTrace: func(call otto.FunctionCall) otto.Value {
			if len(call.ArgumentList) == 0 {
				debug.PrintStack()
				return otto.TrueValue()
			}
			return otto.FalseValue()
		},
	}
	pm.js.Set("DEBUG", bridge)
}
示例#19
0
// SleepBlocks will wait for a specified number of new blocks or max for a
// given of seconds. sleepBlocks(nBlocks[, maxSleep]).
func (self *Jeth) SleepBlocks(call otto.FunctionCall) (response otto.Value) {
	nBlocks := int64(0)
	maxSleep := int64(9999999999999999) // indefinitely

	nArgs := len(call.ArgumentList)

	if nArgs == 0 {
		throwJSExeception("usage: sleepBlocks(<n blocks>[, max sleep in seconds])")
	}

	if nArgs >= 1 {
		if call.Argument(0).IsNumber() {
			nBlocks, _ = call.Argument(0).ToInteger()
		} else {
			throwJSExeception("expected number as first argument")
		}
	}

	if nArgs >= 2 {
		if call.Argument(1).IsNumber() {
			maxSleep, _ = call.Argument(1).ToInteger()
		} else {
			throwJSExeception("expected number as second argument")
		}
	}

	// go through the console, this will allow web3 to call the appropriate
	// callbacks if a delayed response or notification is received.
	currentBlockNr := func() int64 {
		result, err := call.Otto.Run("eth.blockNumber")
		if err != nil {
			throwJSExeception(err.Error())
		}
		blockNr, err := result.ToInteger()
		if err != nil {
			throwJSExeception(err.Error())
		}
		return blockNr
	}

	targetBlockNr := currentBlockNr() + nBlocks
	deadline := time.Now().Add(time.Duration(maxSleep) * time.Second)

	for time.Now().Before(deadline) {
		if currentBlockNr() >= targetBlockNr {
			return otto.TrueValue()
		}
		time.Sleep(time.Second)
	}

	return otto.FalseValue()
}
示例#20
0
func (p *Plugin) jsEnv(event *irc.Event) otto.Value {
	obj, _ := p.js.Object("({})")
	obj.Set("event", p.eventToValue(event))
	obj.Set("log", func(call otto.FunctionCall) otto.Value {
		if len(call.ArgumentList) == 1 && call.ArgumentList[0].IsString() {
			p.log.Println(call.ArgumentList[0].String())
			return otto.TrueValue()
		} else {
			return otto.FalseValue()
		}
	})
	return obj.Value()
}
示例#21
0
func InitPlugin() *modules.Plugin {

	p1 := modules.Plugin{
		Name: "tasks",
		Init: func(vm *modules.JsVm) otto.Value {
			obj, _ := vm.Object("({})")
			obj.Set("addTask", func(c otto.FunctionCall) otto.Value {
				t := TaskBlock{}
				t.Name, _ = c.Argument(0).ToString()
				startTimeStr := c.Argument(1).String()
				startTime, _ := time.Parse(time.RFC1123, startTimeStr)
				t.Start = startTime
				fs := c.Argument(2)
				t.Func = func(tb *TaskBlock) {
					val, err := fs.Call(otto.Value{})
					tb.Done = true
					if err != nil {
						tb.ErrorText = err.Error()
						log.Println(err)
					}
					tb.SuccessText, _ = val.ToString()
					if tb.Repeat > 0 {
						tb.Start.Add(time.Second * time.Duration(tb.Repeat))
					}
				}
				tasks = append(tasks, &t)
				return otto.TrueValue()
			})

			obj.Set("startTasks", func(c otto.FunctionCall) otto.Value {
				Start()
				return otto.TrueValue()
			})
			return obj.Value()
		},
	}

	return &p1
}
示例#22
0
func (js *jsre) addPeer(call otto.FunctionCall) otto.Value {
	nodeURL, err := call.Argument(0).ToString()
	if err != nil {
		fmt.Println(err)
		return otto.FalseValue()
	}
	err = js.ethereum.AddPeer(nodeURL)
	if err != nil {
		fmt.Println(err)
		return otto.FalseValue()
	}
	return otto.TrueValue()
}
示例#23
0
文件: files.go 项目: jmptrader/ottox
// RegisterMethodFileOpen registers a method that is capable of opening files.
//
// Response object:
//
//     {
//       ok: true|false,
//       reader: "readFile" // the method to use to read from the file
//     }
//
// To read the entire file into a variable:
//
//     // in Go...
//     RegisterMethodFileOpen(js, "openFile")
//
//     // in the script...
//     var file = openFile("filename"); // open the file
//     var read = eval(file.reader); // get the reader method
//     var close = eval(file.closer); // get the closer method
//
//     var fileContents = read(-1); // read everything
//     close(); // close the file
//
func RegisterMethodFileOpen(runtime *otto.Otto, methodName string) error {

	runtime.Set(methodName, func(call otto.FunctionCall) otto.Value {

		// check the arguments
		if len(call.ArgumentList) != 1 {
			raiseError(runtime, "%s takes 1 arguments: %s(filename)", methodName, methodName)
			return otto.UndefinedValue()
		}

		// get the arguments
		var filename string
		var err error
		if filename, err = call.Argument(0).ToString(); err != nil {
			raiseError(runtime, "%s first argument must be a string containing the filename", methodName)
			return otto.UndefinedValue()
		}

		// open the file
		var file io.ReadCloser
		if file, err = os.Open(filename); err != nil {
			raiseError(runtime, "Failed to open file '%s': %s", filename, err)
			return otto.UndefinedValue()
		}

		// add the reader
		var readerMethodName string = generateMethodName("fileRead")
		NewReader(runtime, readerMethodName, file)

		// add the closer
		var closerMethodName string = generateMethodName("fileClose")
		runtime.Set(closerMethodName, func(call otto.FunctionCall) otto.Value {
			if err := file.Close(); err != nil {
				raiseError(runtime, "Failed to close file '%s': %s", filename, err)
				return otto.FalseValue()
			}
			return otto.TrueValue()
		})

		var response otto.Value
		if response, err = makeMap(runtime, map[string]interface{}{"reader": readerMethodName, "closer": closerMethodName, "ok": true}); err != nil {
			raiseError(runtime, "%s failed to make response map.", methodName)
			return otto.UndefinedValue()
		}

		// done
		return response
	})

	return nil
}
示例#24
0
func (js *jsre) startMining(call otto.FunctionCall) otto.Value {
	_, err := call.Argument(0).ToInteger()
	if err != nil {
		fmt.Println(err)
		return otto.FalseValue()
	}
	// threads now ignored
	err = js.ethereum.StartMining()
	if err != nil {
		fmt.Println(err)
		return otto.FalseValue()
	}
	return otto.TrueValue()
}
示例#25
0
// SleepBlocks will block the console for a specified number of new blocks optionally
// until the given timeout is reached.
func (b *bridge) SleepBlocks(call otto.FunctionCall) (response otto.Value) {
	var (
		blocks = int64(0)
		sleep  = int64(9999999999999999) // indefinitely
	)
	// Parse the input parameters for the sleep
	nArgs := len(call.ArgumentList)
	if nArgs == 0 {
		throwJSException("usage: sleepBlocks(<n blocks>[, max sleep in seconds])")
	}
	if nArgs >= 1 {
		if call.Argument(0).IsNumber() {
			blocks, _ = call.Argument(0).ToInteger()
		} else {
			throwJSException("expected number as first argument")
		}
	}
	if nArgs >= 2 {
		if call.Argument(1).IsNumber() {
			sleep, _ = call.Argument(1).ToInteger()
		} else {
			throwJSException("expected number as second argument")
		}
	}
	// go through the console, this will allow web3 to call the appropriate
	// callbacks if a delayed response or notification is received.
	blockNumber := func() int64 {
		result, err := call.Otto.Run("eth.blockNumber")
		if err != nil {
			throwJSException(err.Error())
		}
		block, err := result.ToInteger()
		if err != nil {
			throwJSException(err.Error())
		}
		return block
	}
	// Poll the current block number until either it ot a timeout is reached
	targetBlockNr := blockNumber() + blocks
	deadline := time.Now().Add(time.Duration(sleep) * time.Second)

	for time.Now().Before(deadline) {
		if blockNumber() >= targetBlockNr {
			return otto.TrueValue()
		}
		time.Sleep(time.Second)
	}
	return otto.FalseValue()
}
示例#26
0
func TestExist(t *testing.T) {

	js := otto.New()

	assert.False(t, Exist(js, "myVar"))

	js.Set("myVar", otto.TrueValue())
	assert.True(t, Exist(js, "myVar"), "true should exist")

	js.Set("myVar", otto.FalseValue())
	assert.True(t, Exist(js, "myVar"), "false still exists")

	js.Set("myVar", otto.UndefinedValue())
	assert.False(t, Exist(js, "myVar"), "undefined doesn't exist")

}
示例#27
0
func (js *jsre) importChain(call otto.FunctionCall) otto.Value {
	if len(call.ArgumentList) == 0 {
		fmt.Println("err: require file name")
		return otto.FalseValue()
	}
	fn, err := call.Argument(0).ToString()
	if err != nil {
		fmt.Println(err)
		return otto.FalseValue()
	}
	if err := utils.ImportChain(js.ethereum.ChainManager(), fn); err != nil {
		fmt.Println("Import error: ", err)
		return otto.FalseValue()
	}
	return otto.TrueValue()
}
示例#28
0
文件: environ.go 项目: lytics/cayley
func newWorker(qs graph.QuadStore) *worker {
	env := otto.New()
	wk := &worker{
		qs:    qs,
		env:   env,
		limit: -1,
	}
	graph, _ := env.Object("graph = {}")
	env.Run("g = graph")

	graph.Set("Vertex", func(call otto.FunctionCall) otto.Value {
		call.Otto.Run("var out = {}")
		out, err := call.Otto.Object("out")
		if err != nil {
			glog.Error(err.Error())
			return otto.TrueValue()
		}
		out.Set("_gremlin_type", "vertex")
		args := argsOf(call)
		if len(args) > 0 {
			out.Set("string_args", args)
		}
		wk.embedTraversals(env, out)
		wk.embedFinals(env, out)
		return out.Value()
	})
	env.Run("graph.V = graph.Vertex")

	graph.Set("Morphism", func(call otto.FunctionCall) otto.Value {
		call.Otto.Run("var out = {}")
		out, _ := call.Otto.Object("out")
		out.Set("_gremlin_type", "morphism")
		wk.embedTraversals(env, out)
		return out.Value()
	})
	env.Run("graph.M = graph.Morphism")

	graph.Set("Emit", func(call otto.FunctionCall) otto.Value {
		value := call.Argument(0)
		if value.IsDefined() {
			wk.send(&Result{val: &value})
		}
		return otto.NullValue()
	})

	return wk
}
示例#29
0
func registerVM(vm *JsVm) otto.Value {

	obj, _ := vm.Object("({})")

	obj.Set("run", func(c otto.FunctionCall) otto.Value {
		go func() {
			cFunc := c.ArgumentList[0]
			arg := make([]interface{}, 1)
			arg[0] = cFunc
			_, err := vm.Call(`Function.call.call`, nil, cFunc)
			fmt.Println(err)
		}()
		return otto.TrueValue()
	})

	return obj.Value()
}
示例#30
0
文件: otto.go 项目: hattya/aster
func os_mkdir(call otto.FunctionCall) otto.Value {
	if 1 <= len(call.ArgumentList) {
		path, _ := call.ArgumentList[0].ToString()
		var perm os.FileMode
		v := call.Argument(1)
		if v.IsNumber() {
			i, _ := v.ToInteger()
			perm = os.FileMode(i)
		}
		if perm == 0 {
			perm = os.FileMode(0777)
		}
		if os.MkdirAll(path, perm) != nil {
			return otto.TrueValue()
		}
	}
	return otto.UndefinedValue()
}