Example #1
0
func DoSync() {
	host := util.CouchHost()
	dbName := "user-" + util.CurrentUser()
	ldb := pouchdb.New(dbName)
	rdb := pouchdb.New(host + "/" + dbName)
	result, err := pouchdb.Replicate(rdb, ldb, pouchdb.Options{})
	console.Log("error = %j", err)
	console.Log("result = %j", result)
}
Example #2
0
func CordovaLogin() bool {
	console.Log("CordovaLogin()")
	js.Global.Get("facebookConnectPlugin").Call("login", []string{}, func() {
		console.Log("Success logging in")
	}, func() {
		console.Log("Failure logging in")
	})
	console.Log("Leaving CordovaLogin()")
	return false
}
Example #3
0
func BeforeTransition(event *jquery.Event, ui *js.Object) bool {
	console.Log("sync BEFORE")

	go func() {
		container := jQuery(":mobile-pagecontainer")
		jQuery("#syncnow", container).On("click", func() {
			console.Log("Attempting to sync something...")
			go DoSync()
		})
		jQuery(".show-until-load", container).Hide()
		jQuery(".hide-until-load", container).Show()
	}()

	return true
}
Example #4
0
func ConsoleEvent(name string, event *jquery.Event, data *js.Object) {
	page := data.Get("toPage").String()
	if page == "[object Object]" {
		page = data.Get("toPage").Call("jqmData", "url").String()
	}
	console.Log("Event: %s, Current page: %s", name, page)
}
Example #5
0
func CordovaLogin() bool {
	console.Log("CordovaLogin()")
	js.Global.Get("facebookConnectPlugin").Call("login", []string{}, func() {
		console.Log("Success logging in")
		u, err := repo.CurrentUser()
		if err != nil {
			fmt.Printf("No user logged in?? %s\n", err)
		} else {
			// To make sure the DB is initialized as soon as possible
			u.DB()
		}
	}, func() {
		console.Log("Failure logging in")
	})
	console.Log("Leaving CordovaLogin()")
	return false
}
Example #6
0
func (g *gateway) handleBallInPlayMessage(v *vector) {
	console.Log(fmt.Sprintf("handling ball in play message - y pos: %d, angle: %v, speed: %v\n", v.yPos, v.angle, v.speed))

	// Note angle is always specified as if for the LEFT side player, the RIGHT side player
	// will do the inverse.

	g.canvas.ballStart(v)
}
Example #7
0
// Listen attaches the Handler to the window and begins listening for the specified
// jQuery event, reterning an EventListener object
func Listen(event string, handler Handler) *EventListener {
	console.Log("Adding jQuery event listener")
	listener := func(event *jquery.Event, data *js.Object) bool {
		return handler.HandleEvent(event, data, url.Values{})
	}
	jquery.NewJQuery(js.Global.Get("document")).On(event, listener)
	return &EventListener{event: event, listener: listener}
}
Example #8
0
func CheckAuth(h jqeventrouter.Handler) jqeventrouter.Handler {
	return jqeventrouter.HandlerFunc(func(event *jquery.Event, ui *js.Object) bool {
		console.Log("CheckAuth")
		uri := util.JqmTargetUri(ui)
		console.Log("Auth URI = %s", uri)
		if uri != "/login.html" && util.CurrentUser() == "" {
			console.Log("nobody's logged in")
			// Nobody's logged in
			ui.Set("toPage", "login.html")
			event.StopImmediatePropagation()
			console.Log("Attempting to re-trigger the event")
			jquery.NewJQuery(":mobile-pagecontainer").Trigger("pagecontainerbeforechange", ui)
			return true
		}
		console.Log("Auth allowing to proceed")
		return h.HandleEvent(event, ui)
	})
}
Example #9
0
func initjQueryMobile() {
	jQuery(document).On("mobileinit", func() {
		console.Log("mobileinit")
		MobileInit()
	})
	// This is what actually loads jQuery Mobile. We have to register our 'mobileinit'
	// event handler above first, though.
	js.Global.Call("postInit")
}
Example #10
0
func (g *gateway) handlePlayMessage(side string) {
	dSide := strings.ToUpper(side)

	console.Log(fmt.Sprintf("handling play message - side: %s\n", dSide))

	g.statusEl.SetTextContent("Playing (" + dSide + ")")

	g.canvas.reset(dSide)
}
Example #11
0
func initCordova(wg *sync.WaitGroup) {
	if !cordova.IsMobile() {
		return
	}
	wg.Add(1)
	document.Call("addEventListener", "deviceready", func() {
		defer wg.Done()
		console.Log("Cordova device ready")
	}, false)
}
Example #12
0
func main() {
	console.Log("in main()")

	var wg sync.WaitGroup

	initjQuery(&wg)
	initCordova(&wg)
	// 	state := clientstate.New()
	// 	api := flashback.New(jQuery("link[rel=flashback]").Get(0).Get("href").String())
	// 	ctx := context.Background()
	//	ctx = context.WithValue(ctx, "cordova", cordova)
	// 	ctx = context.WithValue(ctx, "AppState", state)
	// 	ctx = context.WithValue(ctx, "api", api)
	// 	ctx = context.WithValue(ctx, "couchhost", jQuery("link[rel=flashbackdb]").Get(0).Get("href").String())

	// Wait for the above modules to initialize before we initialize jQuery Mobile
	wg.Wait()
	console.Log("Done with main()")
	initjQueryMobile()
}
Example #13
0
func (g *gateway) handleMessage(msg []byte) {
	m := string(msg)

	parts := strings.Split(m, ",")

	if parts[0] == "P" {
		g.handlePlayMessage(parts[1])
	} else if parts[0] == "B" {
		// 1 = y position
		// 2 = angle
		// 3 = speed
		v, err := newVectorFromStrings(parts[1], parts[2], parts[3])
		if err != nil {
			console.Log(err.Error())
		}

		g.handleBallInPlayMessage(v)
	} else {
		console.Log(fmt.Sprintf("unsupported message: %s\n", m))
	}
}
Example #14
0
func printLog(prefix string, printTrace bool, message string, v ...interface{}) {

	mess := fmt.Sprintf("%s %s %s", time.Now().Format(timeFormat), prefix, fmt.Sprintf(message, v...))

	switch prefix {
	case WarnPrefix:
		console.Warn(mess)
	case ErrPrefix:
		console.Error(mess)
	default:
		console.Log(mess)
	}
}
Example #15
0
func Read() {
	db := pouchdb.New("flashback")
	var newState = State{}
	if err := db.Get("_local/state", &newState, pouchdb.Options{}); err != nil {
		if pouchdb.IsNotExist(err) {
			// File not found, no problem
		} else {
			state.lastError = err
			console.Log(err)
			return
		}
	}
	state = &newState
	state.lastRead = time.Now()
}
Example #16
0
// MobileInit is run after jQuery Mobile's 'mobileinit' event has fired
func MobileInit() {
	jQMobile = js.Global.Get("jQuery").Get("mobile")

	// Disable hash features
	jQMobile.Set("hashListeningEnabled", false)
	jQMobile.Set("pushStateEnabled", false)
	jQMobile.Get("changePage").Get("defaults").Set("changeHash", false)

	DebugEvents()
	RouterInit()

	jQuery(document).On("pagecontainerbeforechange", func(event *jquery.Event, ui *js.Object) {
		console.Log("last beforechange event handler")
	})
	jQuery(document).One("pagecreate", func(event *jquery.Event) {
		console.Log("Enhancing the panel")
		// This should only be executed once, to initialize our "external"
		// panel. This is the kind of thing that should go in document.ready,
		// but I don't have any guarantee that document.ready will run after
		// mobileinit
		jQuery("body>[data-role='panel']").Underlying().Call("panel").Call("enhanceWithin")
	})
	console.Log("Done with MobileInit()")
}
Example #17
0
func BeforeTransition(event *jquery.Event, ui *js.Object) bool {
	console.Log("login BEFORE")
	api := flashback.New()

	go func() {
		providers := api.GetLoginProviders()
		container := jQuery(":mobile-pagecontainer")
		for rel, href := range providers {
			li := jQuery("li."+rel, container)
			li.Show()
			a := jQuery("a", li)
			if cordova.IsMobile() {
				console.Log("Setting on click event")
				a.On("click", CordovaLogin)
			} else {
				a.SetAttr("href", href+"?return="+jsbuiltin.EncodeURIComponent(js.Global.Get("location").Get("href").String()))
			}
		}
		jQuery(".show-until-load", container).Hide()
		jQuery(".hide-until-load", container).Show()
	}()

	return true
}
Example #18
0
func (mux *EventMux) HandleEvent(event *jquery.Event, data *js.Object, _ url.Values) bool {
	rawUri := mux.getUri(event, data)
	reqUri, err := url.ParseRequestURI(rawUri)
	if err != nil {
		fmt.Printf("Error parsing path '%s': %s\n", rawUri, err)
		return true
	}
	console.Log("URI = %s", rawUri)
	for path, entry := range mux.paths {
		if reqUri.Path == path {
			// We found a match!
			return entry.h.HandleEvent(event, data, reqUri.Query())
		}
	}
	return true
}
Example #19
0
func newGateway() *gateway {
	win := dom.GetWindow()
	doc := win.Document()

	wsEndpoint := doc.GetElementByID("ws-endpoint").(dom.HTMLElement).TextContent()
	statusEl := doc.GetElementByID("status").(dom.HTMLElement)

	canvas := newCanvas(doc.GetElementByID("board").(*dom.HTMLCanvasElement))

	statusEl.SetTextContent("Connecting")
	conn := connect(wsEndpoint)
	statusEl.SetTextContent("Waiting To Play")

	wsSend := make(chan string)

	gw := &gateway{conn: conn, send: wsSend, statusEl: statusEl, canvas: canvas}

	// start send loop (send over websocket to server)
	go func(s chan string) {
		for {
			msg := <-gw.send

			_, err := conn.Write([]byte(msg))
			if err != nil {
				console.Error(err.Error())
			}
		}
	}(wsSend)

	// listen for canvas events
	go func() {
		for {
			e := <-canvas.event

			parts := strings.Split(e, ",")
			if parts[0] == "L" {
				gw.processLostEvent()
			} else if parts[0] == "N" {
				gw.processNetExchangeEvent(e)
			} else {
				console.Log(fmt.Sprintf("unsupported event: %s\n", e))
			}
		}
	}()

	return gw
}
Example #20
0
func CreateAndDial(address string) *Client {
	var WebSocketClient = js.Global.Get("require").Invoke("ws")
	var client = new(Client)
	client.subscribes = make(map[string]chan Response)
	client.websocket = WebSocketClient.New(address)
	var ready = make(chan bool)
	client.websocket.Call("on", "open", func() {
		console.Log("open")
		ready <- true
	})
	<-ready
	client.websocket.Call("on", "message", func(message *js.Object) {
		go func() {
			client.receiveMessage(message)
		}()
	})

	return client
}
Example #21
0
func connect(wsEndpoint string) *websocket.Conn {
	count := 0

	ticker := time.NewTicker(time.Duration(1) * time.Second)
	defer ticker.Stop()

	// connect
	for {
		count++

		console.Log(fmt.Printf("trying to connect to server at %s, attempt %d", wsEndpoint, count))

		conn, err := websocket.Dial(wsEndpoint) // Blocks until connection is established
		if err == nil {
			return conn
		}
		console.Error(err.Error())

		<-ticker.C
	}
}
Example #22
0
func GenerateCode(target, options string) (string, string) {
	var globalOptions GlobalOptions
	var curlOptions common.CurlOptions
	curlOptions.Init()

	parser := flags.NewParser(&globalOptions, flags.Default)
	curlCommand, err := parser.AddCommand("curl",
		"Generate code from curl options",
		"This command has almost same options of curl and generate code",
		&curlOptions)

	if !strings.HasPrefix(options, "curl ") {
		options = "curl " + options
	}
	args := shell.Parse(options)

	urls, err := parser.ParseArgs(args)
	if err != nil {
		console.Log(err)
		return "", err.Error()
	}
	if len(urls) > 1 {
		return "", "It accept only one url. Remained urls are ignored:" + strings.Join(urls, ", ")
	}
	if parser.Active == curlCommand {
		// --url option has higher priority than params.
		if curlOptions.Url == "" {
			if len(urls) > 0 {
				curlOptions.Url = urls[0]
			} else {
				console.Error("Both --url option and url parameters are missing")
				return "", "Both --url option and url parameters are missing"
			}
		}
		sourceCode, _, _, _ := generator.GenerateCode(target, &curlOptions)
		return html.EscapeString(sourceCode), ""
	}
	return "", ""
}
Example #23
0
func ConsolePageEvent(name string, event *jquery.Event) {
	console.Log("Event: %s", name)
}
Example #24
0
func (g *gateway) processNetExchangeEvent(eventMsg string) {
	console.Log(fmt.Printf("processing net exchange event - %s\n", eventMsg))
	g.send <- eventMsg
}
Example #25
0
File: d3.go Project: nplanel/d3
//Style modifies the CSS attribute prop of the selection.  The function
//is passed each element of the data set to use in computing the value.
func (self *selectionImpl) Style(prop PropertyName, f func(js.Object) string) Selection {
	console.Log("calling style", self.obj, prop, f)
	return &selectionImpl{
		self.obj.Call("style", string(prop), f),
	}
}
Example #26
0
func dumpLog(values ...interface{}) {
	console.Log(values...)
}
Example #27
0
func Console(args ...interface{}) {
	console.Log(args...)
}