def __init__(self, obj): super().__init__("div") self.container = Div("diritem") for field in DIR_ITEM_FIELDS: self[field[1]] = obj[field[0]] fdiv = Div(field[1]) self[field[1] + "div"] = fdiv self.container.a(fdiv) if self.isdir: self.container.ac("isdir") self.filenamelabel = Div().html(self.filename) self.filenamediv.a([self.filenamelabel]) self.deletebutton = None if self.filename == "..": self.filenamediv.ac("parent") else: self.deletebutton = Button("Delete").ac("delete") self.isdirdiv.a(self.deletebutton) self.mtimediv.html( __new__(Date(self.mtime * 1000)).toLocaleString()) if self.isdir: self.sizediv.html("dir") else: self.editbutton = Button("Edit") self.filenamediv.a(self.editbutton) self.sizediv.html(self.size) if self.rwx: self.rwxdiv.html(self.rwx) self.a(self.container)
def buildconfigdiv(self): self.configdiv = Div() self.configdiv.a(Button("Serialize", self.serializeconfig)) self.configdiv.a(Button("Store cloud", self.storecloud)) self.configdiv.a(Button("Retrieve cloud", self.retrievecloud)) self.configschema = Schema(self.schemaconfig) self.configdiv.a(self.configschema)
def build(self, text, seed): setseed(seed) self.contentdiv.x().pad(3) self.textarea = TextArea().w(1000).h(200) self.textarea.setText(text) self.controlpanel = Div() self.controlpanel.a(Button("Store", self.store)) if self.isadmin: self.contentdiv.a(self.textarea) self.contentdiv.a(self.controlpanel) self.rootnode = Forumnode( self, { "move": "startpos", "uci": None, "owner": "Wolfram_EP", "comment": "Forum game", "fen": "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1", "parent": None, "isadmin": self.isadmin }) self.contentdiv.a(self.rootnode) self.buildrec(self.rootnode, self.forumgame) #self.rootnode.e.scrollIntoView(True) self.parenttabpane.setscroll() self.contentdiv.sa("draggable", True).cm().ae("dragstart", self.dragstart)
def drawmovearrow(self, move, args = {}): if move is None: return strokecolor = args.get("strokecolor", "#FFFF00") linewidth = args.get("linewidth", 0.2) * self.squaresize headwidth = args.get("headwidth", 0.2) * self.squaresize headheight = args.get("headheight", 0.2) * self.squaresize tomv = self.squarecoordsmiddlevect(self.flipawaresquare(move.tosq)) frommv = self.squarecoordsmiddlevect(self.flipawaresquare(move.fromsq)) if False: self.movecanvas.lineWidth(linewidth) self.movecanvas.strokeStyle(strokecolor) self.movecanvas.fillStyle(strokecolor) self.movecanvas.drawline(frommv, tomv) dv = Vect(headwidth, headheight) self.movecanvas.fillRect(tomv.m(dv), tomv.p(dv)) if not ( move.prompiece.isempty() ): pf = 4 dvp = Vect(linewidth * pf, linewidth * pf) move.prompiece.color = self.turn() ppdiv = Div().pa().cp().ac(getclassforpiece(move.prompiece, self.piecestyle)).w(linewidth * 2 * pf).h(linewidth * 2 * pf) ppdiv.pv(tomv.m(dvp)) self.piececanvashook.a(ppdiv) arrow = Arrow(frommv, tomv, { "linewidth": linewidth, "pointwidth": headheight * 4, "pointheight": headheight * 4, "color": strokecolor }) self.arrowdiv.a(arrow)
def build(self): self.x().ac("pgninfocontainer") self.tcdiv = Div().ac("pgninfotcdiv").html("{} {}".format(self.timecontrol, self.variant)) self.whitediv = Div().ac("pgninfoplayerdiv").html(self.playerlink(self.white)) self.whiteelodiv = Div().ac("pgninfoplayerelodiv").html("{} {}".format(self.whiteelo, self.whiteratingdiff)) if self.meblack(): self.whitediv.ac("pgninfotheyplayerdiv") self.blackdiv = Div().ac("pgninfoplayerdiv").html(self.playerlink(self.black)) self.blackelodiv = Div().ac("pgninfoplayerelodiv").html("{} {}".format(self.blackelo, self.blackratingdiff)) if self.mewhite(): self.blackdiv.ac("pgninfotheyplayerdiv") self.resultdiv = Div().ac("pgninforesultdiv").html(self.result) self.iddiv = Div().ac("pgninfoiddiv").html(self.id) self.iddiv.ae("mousedown", self.idclicked) mescore = self.mescore() if mescore == 1: self.ac("pgninfowhitewin") elif mescore == 0: self.ac("pgninfoblackwin") else: self.ac("pgninfodraw") self.a([self.tcdiv, self.whitediv, self.whiteelodiv, self.blackdiv, self.blackelodiv, self.resultdiv, self.iddiv]) if self.id == localStorage.getItem("pgninfo/idclicked"): self.bds("dashed").bdw("6").bdc("#00f") return self
def __init__(self, args = {}): super().__init__("div") self.container = Div("processinput") self.buttonlabel = args.get("buttonlabel", "Submit") self.entercallback = args.get("entercallback", None) self.textinput = TextInput().setentercallback(self.entercallback) self.submitbutton = Button(self.buttonlabel, self.onenter) self.container.a([self.textinput, self.submitbutton]) self.a(self.container)
def __init__(self): super().__init__("div") self.messagediv = Div().disp("inline-block").pad(3).ff("monospace") self.contentdiv = Div() self.a([self.messagediv, self.contentdiv]) self.reqfenunderway = False self.reqnode = None self.requestforumgame() self.ae("mousemove", self.mousemove) self.ae("mouseup", self.mouseup) self.ae("mouseleave", self.mouseleave)
def __init__(self, args): super().__init__("div") self.BARWIDTH = args.get("barwidth", 20) self.BARSEPARATION = int(self.BARWIDTH * 1.1) self.YHEIGHT = args.get("yheight", 2) self.CLUSTER = args.get("cluster", 50) self.data = args.get("data", []) first = True for d in self.data: mind = d["min"] maxd = d["max"] if first: miny = mind maxy = maxd first = False else: if mind < miny: miny = mind if maxd > maxy: maxy = maxd miny = miny - ( miny % self.CLUSTER ) maxy = maxy - ( maxy % self.CLUSTER ) + self.CLUSTER chartwidth = self.BARSEPARATION * len(self.data) self.w(chartwidth) range = maxy - miny chartheight = range * self.YHEIGHT self.h(chartheight) self.pr().bc("#ffc") for i in range(1, range / self.CLUSTER): rt = maxy - ( i * self.CLUSTER ) yt = i * self.CLUSTER * self.YHEIGHT linediv = Div().pa().t(yt).l(0).w(chartwidth).h(1).bc("#000") ratingdiv = Div().pa().t(yt + 5).ms().html(rt) self.a([ linediv, ratingdiv ]) i = 0 for d in self.data: mind = d["min"] minr = range - ( mind - miny ) mint = minr * self.YHEIGHT maxd = d["max"] maxr = range - ( maxd - miny ) maxt = maxr * self.YHEIGHT open = d["open"] openr = range - ( open - miny ) opent = openr * self.YHEIGHT close = d["close"] closer = range - ( close - miny ) closet = closer * self.YHEIGHT xcoord = i * self.BARSEPARATION bardiv = Div().pa().t(min(opent, closet)).l(xcoord + 1).w(self.BARWIDTH).h(abs(opent - closet)).bc(cpick(opent < closet, "#f00", "#0f0")) minmaxdiv = Div().pa().t(maxt).l(xcoord + int(self.BARWIDTH / 2) - 1 + 1).w(2).h(mint - maxt).bc("#007") self.a([ minmaxdiv, bardiv ]) i += 1
def __init__(self, args={}): super().__init__("div") self.ac("dirbrowser") self.id = args.get("id", None) self.drive = args.get("drive", False) self.editclickedcallback = args.get("editclickedcallback", None) self.pathlist = [] self.listing = [] self.filesdiv = SplitPane({"controlheight": 40}) self.pathlabel = Div("pathlabel") self.createfilebutton = Button("Create file", self.createfileclicked) self.createdirbutton = Button("Create dir", self.createdirclicked) self.refreshbutton = Button("Refresh", self.refreshclicked) self.filesdiv.controlpanel.a([ self.pathlabel, self.createfilebutton, self.createdirbutton, self.refreshbutton ]) if self.drive: self.ziptocloudbutton = Button("Zip to cloud", self.ziptocloudclicked) self.unzipfromcloudbutton = Button("Unzip from cloud", self.unzipfromcloudclicked) self.filesdiv.controlpanel.a( [self.ziptocloudbutton, self.unzipfromcloudbutton]) self.filescontentdiv = Div() self.filesdiv.setcontentelement(self.filescontentdiv) self.editor = Editor() self.editor.reloadbutton.ae("mousedown", self.reloadclicked) self.editor.savebutton.ae("mousedown", self.saveclicked) self.uploader = FileUploader({ "url": "/dirbrowserupload", "accept": "*", "acceptdisplay": "file", "drive": self.drive, "dirbrowseruploadedcallback": self.dirbrowseruploadedcallback, "dirbrowsergetpathcallback": self.path, "getuid": getconn().getuid }) self.tabs = TabPane({ "id": self.id + "tabpane", "tabs": [ Tab("files", "Files", self.filesdiv), Tab("edit", "Edit", self.editor), Tab("upload", "Upload", self.uploader), ], "selected": "files" }) self.tabs.controlpanel.ac("subcontrolpanel") self.a(self.tabs) self.requestdirlist()
def __init__(self, args = {}): super().__init__("div") self.text = args.get("text", "") self.kind = args.get("kind", "normal") self.prompt = args.get("prompt", None) self.container = Div("logitem") self.container.ac(self.kind) self.promptspan = Span().ac("prompt") if self.prompt: self.promptspan.html(self.prompt) self.textspan = Span().html(escapeHTML(self.text)).ac(self.kind) self.container.a([self.promptspan, self.textspan]) self.a(self.container)
def __init__(self, args={}): super().__init__("div") self.id = args.get("id", "doc") self.startpage = args.get("startpage", "contents") self.showcontentslink = args.get("showcontentslink", True) self.mdconv = __new__(showdown.Converter()) self.docdiv = Div("docdiv") self.srcdiv = Div("srcdiv") self.a(self.docdiv) getconn().sioreq({ "kind": "getdoc", "owner": self.id, "data": self.startpage, "switchtodoctab": False })
def __init__(self, args = {}): super().__init__("div") self.controlheight = args.get("controlheight", 100) self.container = Div(["splitpane", "container"]) self.controlpanel = Div(["splitpane", "controlpanel"]) self.contentdiv = Div(["splitpane", "contentdiv"]) self.container.a([self.controlpanel, self.contentdiv]) self.contentelement = Div() self.minwidth = args.get("minwidth", 400) self.mincontentheight = args.get("mincontentheight", 200) self.resize(args.get("width", 600), args.get("height", 400)) self.fillwindow = args.get("fillwindow", False) if self.fillwindow: window.addEventListener("resize", self.resizetowindow) self.resizetowindow() self.a(self.container)
def build(self): self.configsplitpane = SplitPane({"controlheight": 50}) self.configdiv = Div("largesheet") self.configsplitpane.controlpanel.a([ Button("Serialize config", self.serializeconfig).ac("controlbutton"), Button("Serialize localstorage", self.serializelocalstorage).ac("controlbutton"), Button("Sync localstorage", self.synclocalstorage).ac("controlbutton") ]) self.configsplitpane.controlpanel.ac("subcontrolpanel") self.configschema = Schema(self.schemaconfig) self.configdiv.a(self.configschema) self.configsplitpane.setcontentelement(self.configdiv) self.x().a(self.configsplitpane)
def setmybots(self, obj): botprofiles = obj["mybots"] self.botresultdiv.x() __pragma__("jsiter") for id in botprofiles: botprofile = botprofiles[id] self.botresultdiv.a(Div().html("{} {}".format( botprofile["username"], cpick(botprofile["online"], "online", "offline"))).fs(25).pad(5)) self.botresultdiv.a(Div().html( "follow {} games {} last move {}".format( botprofile["nbFollowers"], botprofile["count"]["all"], botprofile["lastmoveago"])).fs(20).pad(3)) self.botresultdiv.a(Div().html("last players {}".format( botprofile["lastplayers"])).fs(20).pad(3)) __pragma__("nojsiter")
def __init__(self, key, displayname, element, clickedcallback): super().__init__("div") self.key = key self.displayname = displayname self.element = element self.clickedcallback = clickedcallback self.container = Div(["tab", "container", "noselect"]).html(displayname) self.a(self.container)
class SplitPane(e): def resize(self, width = None, height = None): if not ( width is None ): self.width = max(width, self.minwidth) if not ( height is None ): self.height = height self.contentheight = max(self.height - self.controlheight, self.mincontentheight) self.height = self.controlheight + self.contentheight self.container.w(self.width).h(self.height) self.controlpanel.w(self.width).h(self.controlheight) self.contentdiv.w(self.width).h(self.contentheight) sbw = getScrollBarWidth() self.contentinnerwidth = self.width - sbw self.contentinnerheight = self.contentheight - sbw self.contentdiv.x().a(self.contentelement) try: self.contentelement.resize(self.contentinnerwidth, self.contentinnerheight) except: pass return self def setcontentelement(self, contentelement): self.contentelement = contentelement self.resize(self.width, self.height) return self def resizetowindow(self): self.resize(window.innerWidth, window.innerHeight) return self def __init__(self, args = {}): super().__init__("div") self.controlheight = args.get("controlheight", 100) self.container = Div(["splitpane", "container"]) self.controlpanel = Div(["splitpane", "controlpanel"]) self.contentdiv = Div(["splitpane", "contentdiv"]) self.container.a([self.controlpanel, self.contentdiv]) self.contentelement = Div() self.minwidth = args.get("minwidth", 400) self.mincontentheight = args.get("mincontentheight", 200) self.resize(args.get("width", 600), args.get("height", 400)) self.fillwindow = args.get("fillwindow", False) if self.fillwindow: window.addEventListener("resize", self.resizetowindow) self.resizetowindow() self.a(self.container)
def highlightsquare(self, sq, bc, op): if op == 0: return margin = self.squaresize * 0.1 hsize = self.squaresize - 2 * margin sqhdiv = self.sqhdivs[sq.hashkey()] if op > sqhdiv["cumop"]: sqhdiv["cumop"] = op sqhdiv["div"].x().a(Div().pa().t(margin).l(margin).w(hsize).h(hsize).bc(bc).op(sqhdiv["cumop"]))
def __init__(self): super().__init__("div") self.editdiv = SplitPane({"controlheight": 40}) self.pathlabel = Div("pathlabel") self.editdiv.controlpanel.a(self.pathlabel) self.reloadbutton = Button("Reload") self.savebutton = Button("Save") self.editdiv.controlpanel.a([self.reloadbutton, self.savebutton]) self.edittextarea = EditTextarea() self.editdiv.setcontentelement(self.edittextarea) self.a(self.editdiv)
def __init__(self, args): super().__init__("div") self.show = args.get("show", False) self.parent = args.get("parent", BasicBoard({})) self.store = args.get("store", "") self.color = args.get("color", WHITE) self.container = args.get("containerdiv", Div()) self.container.ac("noselect") self.piecesize = args.get("piecesize", self.parent.piecesize) self.muldivsize = int(self.piecesize / 2) self.a(self.container) self.setstore(self.store)
def build(self): self.root.innerHTML = "" self.buildconfigdiv() self.signupdiv = Div() if self.authenabled: self.buildsignupdiv() self.profiletab = Tab("profile", "Profile", self.signupdiv) self.mainelement = TabPane({ "id": "maintabpane", "fillwindow": True, "tabs": [ Tab("main", "Main", Div("contentplaceholder").html("Main.")), Tab("config", "Config", self.configdiv), Tab("upload", "Upload", FileUploader({"url": "/upload"})), Tab("log", "Log", Div("contentplaceholder").html("Log.")), self.profiletab, Tab("about", "About", Div("contentplaceholder").html("About.")) ], "selected": "upload" }) self.root.appendChild(self.mainelement.e)
def build(self): self.x() self.droparea = Div("fileuploaddroparea") self.form = Form().ac("fileuploadform") self.desc = P().ac("fileuploadp").html("Upload {}s with the file dialog or by dragging and dropping them onto the dashed region".format(self.acceptdisplay)) self.fileinput = FileInput().ac("fileuploadfileelem").setmultiple(self.multiple).setaccept(self.accept) self.fileinput.sa("id", "fileinputelement") self.fileinput.ae("change", self.fileinputchanged) self.button = Label().ac("fileuploadbutton").sa("for", "fileinputelement").html("Select some {}s".format(self.acceptdisplay)) self.form.a([self.desc, self.fileinput, self.button]) self.droparea.a(self.form) for eventname in ["dragenter", "dragover", "dragleave", "drop"]: self.droparea.ae(eventname, self.preventdefaults) for eventname in ["dragenter", "dragover"]: self.droparea.ae(eventname, self.highlight) for eventname in ["dragleave", "drop"]: self.droparea.ae(eventname, self.unhighlight) self.droparea.ae("drop", self.handledrop) self.info = Div("fileuploadinfo") self.infoitems = [] self.a([self.droparea, self.info])
def authstatechanged(self, user): self.user = user self.passwordinput.setText("") if user: self.displayName = user.displayName self.email = user.email self.emailVerified = user.emailVerified self.photoURL = user.photoURL self.isAnonymous = user.isAnonymous self.uid = user.uid self.providerData = user.providerData print("user", self.displayName, self.email) print(self.providerData) self.nameinfodiv = Div().html("name : <span class='{}'>{}</span>".format(cpick(self.displayName, "uiinfo", "uiinfored"), getelse(self.displayName,"<NA>"))).pt(5) self.emailinfodiv = Div().html("email : <span class='{}'>{}</span>".format(cpick(self.email, "uiinfo", "uiinfored"), getelse(self.email, "<NA>"))) self.verifiedinfodiv = Div().html("status : <span class='{}'>{}</span>".format(cpick(self.userverified(), "uiinfo", "uiinfored"), self.userstatusverbal())) self.photourldiv = Div().html("photo url : <span class='{}'>{}</span>".format(cpick(self.photoURL, "uiinfo", "uiinfored"), getelse(self.photoURL,"<NA>"))) self.uidinfodiv = Div().html("uid : <span class='uiinfo'>{}</span>".format(self.uid)).pb(8) self.userinfodiv.x().a([self.nameinfodiv, self.emailinfodiv, self.verifiedinfodiv, self.photourldiv, self.uidinfodiv]) self.emailinput.setText(self.email) self.displaynameinput.setText(self.displayName) self.photourlinput.setText(self.photoURL) self.photodiv.x() if self.photoURL: self.photodiv.html("<img src='{}'></img>".format(self.photoURL)) else: print("no user") self.userinfodiv.x().a([ Div().html("Please sign up or sign in !"), Button("Sign in anonymously", self.signinanonymously()) ]) self.setprofiletab() self.userinfodiv.fs(cpick(self.user, 10, 14))
def buildprominput(self): promkinds = prompiecekindsforvariantkey(self.variantkey) promsq = self.dragmove.tosq.copy() dir = cpick(promsq.rank >= ( self.numranks / 2 ), -1, 1) ppks = prompiecekindsforvariantkey(self.variantkey) for ppk in ppks: fapromsq = self.flipawaresquare(promsq) pp = Piece(ppk, self.turn()) psqdiv = Div().pa().cp().zi(150).w(self.squaresize).h(self.squaresize).ac("boardpromotionsquare") psqdiv.pv(self.squarecoordsvect(fapromsq)) ppdiv = Div().pa().cp().zi(200).w(self.piecesize).h(self.piecesize).ac(getclassforpiece(pp, self.piecestyle)) ppdiv.pv(self.piececoordsvect(fapromsq)).ae("mousedown", self.prompiececlickedfactory(ppk)) self.container.a([psqdiv, ppdiv]) promsq = promsq.p(Square(0, dir))
class ProcessInput(e): def onenter(self): self.textinput.rc("textinputediting") if self.entercallback: self.entercallback() def getText(self): return self.textinput.getText() def setText(self, content): self.textinput.setText(content) return self def __init__(self, args = {}): super().__init__("div") self.container = Div("processinput") self.buttonlabel = args.get("buttonlabel", "Submit") self.entercallback = args.get("entercallback", None) self.textinput = TextInput().setentercallback(self.entercallback) self.submitbutton = Button(self.buttonlabel, self.onenter) self.container.a([self.textinput, self.submitbutton]) self.a(self.container)
class Log(e): def __init__(self, args = {}): super().__init__("div") self.items = [] self.container = Div() self.a(self.container) def build(self): self.container.x() for item in self.items: self.container.a(item) def log(self, item): newitems = [item] i = 1 for olditem in self.items: if i < MAX_LOGITEMS: newitems.append(olditem) i += 1 else: break self.items = newitems self.build() ######################################################
def buildsignupdiv(self): self.signupdiv = Div() self.signupmaildiv = Div("signupmaildiv") self.emaillabel = Span().html("Email:") self.emailinput = TextInput().ac("profiletextinput").w(250) self.passwordlabel = Span().html("Password:"******"profiletextinput").w(100) self.helpbutton = Button("Help", self.helpcallback).ac("helpbutton") self.signinbutton = Button("Sign in", self.signincallback) self.signoutbutton = Button("Sign out", self.signoutcallback) self.signupbutton = Button("Sign up", self.signupcallback) self.sendverificationbutton = Button("Send verification", self.sendverificationcallback) self.resetpasswordbutton = Button("Reset password", self.resetpasswordcallback) self.linkgooglebutton = Button("Link Google", self.linkgooglecallback) self.linkmailbutton = Button("Link Email", self.linkmailcallback) self.userinfodiv = Div("userinfodiv") self.signupmaildiv.a([ self.helpbutton, self.emaillabel, self.emailinput, self.passwordlabel, self.passwordinput, self.signinbutton, self.signoutbutton, self.signupbutton, self.sendverificationbutton, self.resetpasswordbutton, self.linkgooglebutton, self.linkmailbutton ]) self.userdetailsdiv = Div("userdetailsdiv") self.displaynamelabel = Span().html("Display name:") self.displaynameinput = TextInput().ac("profiletextinput").w(250) self.photourllabel = Span().html("Photo url:") self.photourlinput = TextInput().ac("profiletextinput").w(250) self.updatedisplaynamebutton = Button("Update display name", self.updatedisplaynamecallback) self.updatephotourlbutton = Button("Update photo url", self.updatephotourlcallback) self.userdetailsdiv.a([ self.displaynamelabel, self.displaynameinput, self.updatedisplaynamebutton, self.photourllabel, self.photourlinput, self.updatephotourlbutton ]) self.photodiv = Div("photodiv") self.signupdiv.a([ self.signupmaildiv, self.userdetailsdiv, self.userinfodiv, self.photodiv ]) self.firebaseuidiv = Div().sa("id", "firebaseuidiv") self.signupdiv.a(self.firebaseuidiv)
class Connection: def signincallback(self): email = self.emailinput.getText() password = self.passwordinput.getText() print("signing in user with", email, password) firebase.auth().signInWithEmailAndPassword(email, password).then( lambda: print("ok"), lambda error: window.alert("{}".format(error))) def signoutcallback(self): if firebase.auth().currentUser: print("signing out") firebase.auth().signOut() else: window.alert("Already signed out.") def signupcallback(self): email = self.emailinput.getText() password = self.passwordinput.getText() print("signing up user with", email, password) firebase.auth().createUserWithEmailAndPassword(email, password).then( lambda: print("ok"), lambda error: window.alert("{}".format(error))) def sendverificationcallback(self): email = self.emailinput.getText() firebase.auth().currentUser.sendEmailVerification().then( lambda: window.alert("Verification email has been sent to {} !". format(email)), lambda error: window.alert("{}".format(error))) def resetpasswordcallback(self): email = self.emailinput.getText() firebase.auth().sendPasswordResetEmail(email).then( lambda: window.alert("Password reset email has been sent to {} !". format(email)), lambda error: window.alert("{}".format(error))) def updatedisplaynamecallback(self): getconn().sioreq({ "kind": "updateuserdisplayname", "displayname": self.displaynameinput.getText(), "uid": self.uid }) def updatephotourlcallback(self): getconn().sioreq({ "kind": "updateuserphotourl", "photourl": self.photourlinput.getText(), "uid": self.uid }) def linkgoogleok(self, result): print(result) window.alert("Account linked with Google !") location.reload() def linkmailok(self, usercred): print(usercred) window.alert("Account linked with Email !") location.reload() def linkgooglecallback(self): provider = __new__(firebase.auth.GoogleAuthProvider()) firebase.auth().currentUser.linkWithPopup(provider).then( self.linkgoogleok, lambda err: window.alert("Link Google failed: {}".format(err))) def linkmailcallback(self): credential = firebase.auth.EmailAuthProvider.credential( self.emailinput.getText(), self.passwordinput.getText()) firebase.auth().currentUser.linkAndRetrieveDataWithCredential( credential).then( self.linkmailok, lambda err: window.alert("Link Email failed: {}".format(err))) def helpcallback(self): self.sioreq({"kind": "getdoc", "data": "profilehelp", "owner": "doc"}) def buildsignupdiv(self): self.signupdiv = Div() self.signupmaildiv = Div("signupmaildiv") self.emaillabel = Span().html("Email:") self.emailinput = TextInput().ac("profiletextinput").w(250) self.passwordlabel = Span().html("Password:"******"profiletextinput").w(100) self.helpbutton = Button("Help", self.helpcallback).ac("helpbutton") self.signinbutton = Button("Sign in", self.signincallback) self.signoutbutton = Button("Sign out", self.signoutcallback) self.signupbutton = Button("Sign up", self.signupcallback) self.sendverificationbutton = Button("Send verification", self.sendverificationcallback) self.resetpasswordbutton = Button("Reset password", self.resetpasswordcallback) self.linkgooglebutton = Button("Link Google", self.linkgooglecallback) self.linkmailbutton = Button("Link Email", self.linkmailcallback) self.userinfodiv = Div("userinfodiv") self.signupmaildiv.a([ self.helpbutton, self.emaillabel, self.emailinput, self.passwordlabel, self.passwordinput, self.signinbutton, self.signoutbutton, self.signupbutton, self.sendverificationbutton, self.resetpasswordbutton, self.linkgooglebutton, self.linkmailbutton ]) self.userdetailsdiv = Div("userdetailsdiv") self.displaynamelabel = Span().html("Display name:") self.displaynameinput = TextInput().ac("profiletextinput").w(250) self.photourllabel = Span().html("Photo url:") self.photourlinput = TextInput().ac("profiletextinput").w(250) self.updatedisplaynamebutton = Button("Update display name", self.updatedisplaynamecallback) self.updatephotourlbutton = Button("Update photo url", self.updatephotourlcallback) self.userdetailsdiv.a([ self.displaynamelabel, self.displaynameinput, self.updatedisplaynamebutton, self.photourllabel, self.photourlinput, self.updatephotourlbutton ]) self.photodiv = Div("photodiv") self.signupdiv.a([ self.signupmaildiv, self.userdetailsdiv, self.userinfodiv, self.photodiv ]) self.firebaseuidiv = Div().sa("id", "firebaseuidiv") self.signupdiv.a(self.firebaseuidiv) def logobj(self, logkind, obj, prompt): objstr = JSON.stringify(obj) if self.log: li = LogItem({"text": objstr, "kind": logkind, "prompt": prompt}) li.container.ac("socketlog") self.log.log(li) def emit(self, kind, obj): self.logobj("info", obj, "-> ") if self.rawsocket: self.rawsocket.emit(kind, obj) def sioreq(self, obj): obj["uid"] = self.getuid() #print("sioreq", obj) self.emit("sioreq", obj) def onconnect(self): if self.log: self.logobj("success", "socket connected ok", "socket message: ") if not self.configloaded: self.sioreq({"kind": "sendfirebaseconfig"}) if self.connectcallback: self.connectcallback() def siores(self, obj): if self.log: self.logobj("normal", obj, "<- ") if self.configloaded: if self.siorescallback: self.siorescallback(obj) else: kind = obj["kind"] if kind == "firebaseconfig": self.configloaded = True self.startfirebase(obj["firebaseconfig"]) def getuserdisplayname(self): if self.user: if self.displayName: return self.displayName return self.email return None def setprofiletab(self): self.profiletab.rc(["profilelogged", "profileanon"]) dn = self.getuserdisplayname() if dn: self.profiletab.container.html(dn) self.profiletab.ac("profilelogged") else: if self.user: self.profiletab.container.html("Anonymous") self.profiletab.ac("profileanon") else: self.profiletab.container.html("Profile") def signinanonymously(self): firebase.auth().signInAnonymously().then(lambda: print("ok"), lambda error: print(error)) def userstatusverbal(self): if not self.user: return "[logged out]" if self.user.isAnonymous: return "anonymous" return cpick(self.emailVerified, "verified", "not verified") def userverified(self): if not self.user: return False if self.user.isAnonymous: return False return self.user.emailVerified def authstatechanged(self, user): self.user = user self.passwordinput.setText("") if user: self.displayName = user.displayName self.email = user.email self.emailVerified = user.emailVerified self.photoURL = user.photoURL self.isAnonymous = user.isAnonymous self.uid = user.uid self.providerData = user.providerData print("user:"******"name : <span class='{}'>{}</span>".format( cpick(self.displayName, "uiinfo", "uiinfored"), getelse(self.displayName, "<NA>"))).pt(5) self.emailinfodiv = Div().html( "email : <span class='{}'>{}</span>".format( cpick(self.email, "uiinfo", "uiinfored"), getelse(self.email, "<NA>"))) self.verifiedinfodiv = Div().html( "status : <span class='{}'>{}</span>".format( cpick(self.userverified(), "uiinfo", "uiinfored"), self.userstatusverbal())) self.photourldiv = Div().html( "photo url : <span class='{}'>{}</span>".format( cpick(self.photoURL, "uiinfo", "uiinfored"), getelse(self.photoURL, "<NA>"))) self.uidinfodiv = Div().html( "uid : <span class='uiinfo'>{}</span>".format(self.uid)).pb(8) self.userinfodiv.x().a([ self.nameinfodiv, self.emailinfodiv, self.verifiedinfodiv, self.photourldiv, self.uidinfodiv ]) self.emailinput.setText(self.email) self.displaynameinput.setText(self.displayName) self.photourlinput.setText(self.photoURL) self.photodiv.x() if self.photoURL: self.photodiv.html( "<img src='{}' class='userphotoimg'></img>".format( self.photoURL)) else: print("no user") self.userinfodiv.x().a([ Div().html("Please sign up or sign in !"), Button("Sign in anonymously", self.signinanonymously()) ]) self.setprofiletab() self.userinfodiv.fs(cpick(self.user, 10, 14)) if user: if self.authcallback: self.authcallback() def initializefirebase(self): print("initializing firebase from", self.firebaseconfig) firebase.initializeApp(self.firebaseconfig) firebase.auth().onAuthStateChanged(self.authstatechanged) def initializefirebaseui(self): self.uiConfig = { "signInSuccessUrl": '/', "signInOptions": [ firebase.auth.GoogleAuthProvider.PROVIDER_ID, #firebase.auth.FacebookAuthProvider.PROVIDER_ID, #firebase.auth.TwitterAuthProvider.PROVIDER_ID, #firebase.auth.GithubAuthProvider.PROVIDER_ID, firebase.auth.EmailAuthProvider.PROVIDER_ID, #firebase.auth.PhoneAuthProvider.PROVIDER_ID ], "tosUrl": '/tos' } print("initializing firebase ui from", self.uiConfig) self.ui = __new__(firebaseui.auth.AuthUI(firebase.auth())) self.ui.start(self.firebaseuidiv.e, self.uiConfig) def startfirebase(self, firebaseconfig): self.firebaseconfig = firebaseconfig self.initializefirebase() self.initializefirebaseui() def getuid(self): if self.user: return self.uid return "mockuser" def __init__(self, args={}): self.configloaded = False self.user = None if window.location.protocol == "https:": self.ws_scheme = "wss://" else: self.ws_scheme = "ws://" self.SUBMIT_URL = self.ws_scheme + window.location.host print("creating socket {}".format(self.SUBMIT_URL)) self.rawsocket = io.connect(self.SUBMIT_URL) print("socket created ok") self.log = Log() self.connectcallback = args.get("connectcallback", None) self.authcallback = args.get("authcallback", None) self.siorescallback = args.get("siorescallback", None) self.buildsignupdiv() self.profiletab = Tab("profile", "Profile", self.signupdiv) if self.rawsocket: self.rawsocket.on("connect", self.onconnect) self.rawsocket.on("siores", self.siores)
def build(self): self.root.innerHTML = "" self.owners["config"] = self.config if self.dodirbrowser: self.maindirbrowser = DirBrowser({"id": "maindirbrowser"}) self.owners["maindirbrowser"] = self.maindirbrowser else: self.maindirbrowser = Div() if self.dodrive: self.drive = DirBrowser({ "id": "drive", "drive": True, "editclickedcallback": self.driveeditclickedcallback }) self.owners["drive"] = self.drive else: self.drive = Div() self.createbotdiv() if self.doboard: self.mainboard = Board({ "dobook": self.dobook, "dostoredanalysis": self.dostoredanalysis, "dostoredauto": self.dostoredauto, "dogames": self.dogames, "setposinfo": self.setposinfo, "dogamepreview": self.dogamepreview, "background": self.boardbackground, "autoanalysisdelay": self.autoanalysisdelay, "maxgames": self.maxgames, "gamesfilter": self.gamesfilter, "analysispvlength": self.analysispvlength }) self.mainboard.setusername(self.username, self.usertoken) self.mainboard.tabpane.controlpanel.ac("subcontrolpanel") self.owners["mainboard"] = self.mainboard else: self.mainboard = Div() if self.dodocs: self.doc = Doc() self.srcdiv = self.doc.srcdiv self.owners["doc"] = self.doc else: self.doc = Div() self.srcdiv = Div() if self.doabout: self.about = Doc({ "id": "about", "startpage": "about", "showcontentslink": False }) self.owners["about"] = self.about else: self.about = Div() if self.isadmin: self.processpane = ProcessPane( {"configsch": self.config.getpath("processes")}) self.processpane.processtabpane.controlpanel.ac("subcontrolpanel") else: self.processpane = Div("featureplaceholder").html( "Admin only feature.") self.forumgametab = Tab( "forumgame", "Forum game", Div("featureplaceholder").html("Forum game disabled.")) if self.doforumgame: self.forumgame = Forumgame() self.forumgame.mainboard = self.mainboard self.owners["forumgame"] = self.forumgame self.forumgametab = Tab("forumgame", "Forum game", self.forumgame) self.tabs = TabPane({ "id": "maintabpane", "fillwindow": True, "tabs": [ Tab("config", "Config", self.config), Tab("upload", "Upload", FileUploader({"url": "/upload"})), Tab("board", "Board", self.mainboard), self.forumgametab, Tab("process", "Process", self.processpane), Tab("dirbrowser", "Dirbrowser", self.maindirbrowser), Tab("drive", "Drive", self.drive), Tab("bots", "Bots", self.botdiv), Tab("doc", "Doc", self.doc), Tab("src", "Src", self.srcdiv), Tab("log", "Log", getconn().log), getconn().profiletab, Tab("about", "About", self.about) ], "selected": "drive" }) self.root.appendChild(self.tabs.e) qseltab = queryparams.get("tab", None) if qseltab: self.tabs.selectbykey(qseltab)
def createbotdiv(self): self.botdiv = Div() self.botresultdiv = Div() self.botdiv.a(Button("Request bots", self.requestbots).mar(10)) self.botdiv.a(Hlink("/bots", "Bots page")) self.botdiv.a(self.botresultdiv)
class Client: def __init__(self): self.isadmin = False self.root = ge("clientroot") self.owners = {} self.config = Config() self.authdone = False self.connectdone = False def driveeditclickedcallback(self, dir): ext = getext(dir) if ext == "bin": self.mainboard.setbookpath(dir, True) self.mainboard.tabpane.selectbykey("book") self.tabs.selectbykey("board") self.mainboard.getbookpage() return True def requestbots(self): getconn().sioreq({"kind": "getmybots"}) def createbotdiv(self): self.botdiv = Div() self.botresultdiv = Div() self.botdiv.a(Button("Request bots", self.requestbots).mar(10)) self.botdiv.a(Hlink("/bots", "Bots page")) self.botdiv.a(self.botresultdiv) def build(self): self.root.innerHTML = "" self.owners["config"] = self.config if self.dodirbrowser: self.maindirbrowser = DirBrowser({"id": "maindirbrowser"}) self.owners["maindirbrowser"] = self.maindirbrowser else: self.maindirbrowser = Div() if self.dodrive: self.drive = DirBrowser({ "id": "drive", "drive": True, "editclickedcallback": self.driveeditclickedcallback }) self.owners["drive"] = self.drive else: self.drive = Div() self.createbotdiv() if self.doboard: self.mainboard = Board({ "dobook": self.dobook, "dostoredanalysis": self.dostoredanalysis, "dostoredauto": self.dostoredauto, "dogames": self.dogames, "setposinfo": self.setposinfo, "dogamepreview": self.dogamepreview, "background": self.boardbackground, "autoanalysisdelay": self.autoanalysisdelay, "maxgames": self.maxgames, "gamesfilter": self.gamesfilter, "analysispvlength": self.analysispvlength }) self.mainboard.setusername(self.username, self.usertoken) self.mainboard.tabpane.controlpanel.ac("subcontrolpanel") self.owners["mainboard"] = self.mainboard else: self.mainboard = Div() if self.dodocs: self.doc = Doc() self.srcdiv = self.doc.srcdiv self.owners["doc"] = self.doc else: self.doc = Div() self.srcdiv = Div() if self.doabout: self.about = Doc({ "id": "about", "startpage": "about", "showcontentslink": False }) self.owners["about"] = self.about else: self.about = Div() if self.isadmin: self.processpane = ProcessPane( {"configsch": self.config.getpath("processes")}) self.processpane.processtabpane.controlpanel.ac("subcontrolpanel") else: self.processpane = Div("featureplaceholder").html( "Admin only feature.") self.forumgametab = Tab( "forumgame", "Forum game", Div("featureplaceholder").html("Forum game disabled.")) if self.doforumgame: self.forumgame = Forumgame() self.forumgame.mainboard = self.mainboard self.owners["forumgame"] = self.forumgame self.forumgametab = Tab("forumgame", "Forum game", self.forumgame) self.tabs = TabPane({ "id": "maintabpane", "fillwindow": True, "tabs": [ Tab("config", "Config", self.config), Tab("upload", "Upload", FileUploader({"url": "/upload"})), Tab("board", "Board", self.mainboard), self.forumgametab, Tab("process", "Process", self.processpane), Tab("dirbrowser", "Dirbrowser", self.maindirbrowser), Tab("drive", "Drive", self.drive), Tab("bots", "Bots", self.botdiv), Tab("doc", "Doc", self.doc), Tab("src", "Src", self.srcdiv), Tab("log", "Log", getconn().log), getconn().profiletab, Tab("about", "About", self.about) ], "selected": "drive" }) self.root.appendChild(self.tabs.e) qseltab = queryparams.get("tab", None) if qseltab: self.tabs.selectbykey(qseltab) def onready(self): getconn().sioreq({"kind": "connected", "queryparams": queryparams}) def setloadinfo(self, content): ge("connectmsg").innerHTML = content def onconnect(self): self.connectdone = True if self.authdone: self.onready() else: self.setloadinfo("Authenticating, please wait ...") def onauth(self): self.authdone = True if self.connectdone: self.onready() else: self.setloadinfo( "Authenticated, connecting to server, please wait ...") def getschemaconfigfromobj(self, obj): self.config.setschemaconfig(obj["schemaconfig"]) self.dodocs = self.config.get("global/dodocs", True) self.dobook = self.config.get("global/dobook", True) self.username = self.config.get("global/username") self.usertoken = self.config.get("global/usertoken") self.dostoredanalysis = self.config.get("global/dostoredanalysis", True) self.dodirbrowser = self.config.get("global/dodirbrowser", True) self.dodrive = self.config.get("global/dodrive", True) self.dogames = self.config.get("global/dogames", True) self.doboard = self.config.get("global/doboard", True) self.doabout = self.config.get("global/doabout", True) self.dogamepreview = self.config.get("global/dogamepreview", True) self.doforumgame = self.config.get("global/doforumgame", True) self.dostoredauto = self.config.get("global/dostoredauto", True) self.boardbackground = self.config.get("layout/boardbackground", "wood.jpg") self.autoanalysisdelay = self.config.get("global/autoanalysisdelay", True) self.maxgames = self.config.get("global/maxgames", 25) self.gamesfilter = self.config.get("global/gamesfilter", "") self.analysispvlength = self.config.get("global/analysispvlength", 4) self.setposinfo = obj["setposinfo"] def buildfromconfiginobj(self, obj): self.getschemaconfigfromobj(obj) self.build() def setmybots(self, obj): botprofiles = obj["mybots"] self.botresultdiv.x() __pragma__("jsiter") for id in botprofiles: botprofile = botprofiles[id] self.botresultdiv.a(Div().html("{} {}".format( botprofile["username"], cpick(botprofile["online"], "online", "offline"))).fs(25).pad(5)) self.botresultdiv.a(Div().html( "follow {} games {} last move {}".format( botprofile["nbFollowers"], botprofile["count"]["all"], botprofile["lastmoveago"])).fs(20).pad(3)) self.botresultdiv.a(Div().html("last players {}".format( botprofile["lastplayers"])).fs(20).pad(3)) __pragma__("nojsiter") def siores(self, obj): self.isadmin = obj["isadmin"] if queryparams.get("noadmin", "false") == "true": self.isadmin = False if "kind" in obj: kind = obj["kind"] if kind == "buffered": for item in obj["items"]: self.siores(item) elif kind == "connectedack": self.buildfromconfiginobj(obj) elif kind == "configsaved": window.alert("Config saved, {} characters".format(obj["size"])) location.reload() elif kind == "alert": window.alert(obj["data"]) if obj["reload"]: location.reload() elif kind == "proc": self.processpane.siores(obj) elif kind == "storedb": pass elif kind == "storedbfailed": pass elif kind == "retrievedbfailed": pass elif kind == "mybots": self.setmybots(obj) else: if IS_DEV(): self.owners[obj["owner"]].siores(obj) else: try: self.owners[obj["owner"]].siores(obj) except: print("could not handle", obj) if kind == "showdoc": if obj["switchtodoctab"]: self.tabs.selectbykey("doc") def authtimeout(self): if not self.authdone: print("authtimeout") self.onauth() def startup(self): createconn({ "connectcallback": self.onconnect, "authcallback": self.onauth, "siorescallback": self.siores }) if IS_DEV(): setTimeout(self.authtimeout, 3000)