Ejemplo n.º 1
0
 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()
Ejemplo n.º 2
0
 def build(self):
     proctabs = []
     firstkey = None
     for proc in self.configsch.childs:
         processkey = proc.getpath("key").value
         command = proc.getpath("command").value
         args = []
         for arg in proc.getpath("command_args").childs:
             args.append(arg.value)
         if not firstkey:
             firstkey = processkey
         processdisplayname = proc.getpath("displayname").value
         shortcuts = []
         shortcutsobj = proc.getpath("shortcuts")
         if shortcutsobj:
             for shortcut in shortcutsobj.childs:
                 shortcuts.append([shortcut.key, shortcut.value])
         processconsole = ProcessConsole({
             "key": processkey,
             "command": command,
             "command_args": args,
             "shortcuts": shortcuts
         })
         self.processconsoles[processkey] = processconsole
         proctabs.append(Tab(processkey, processdisplayname,
                             processconsole))
     self.processtabpane = TabPane({
         "id": self.id,
         "tabs": proctabs,
         "selected": firstkey
     })
     self.x().a(self.processtabpane)
     return self
Ejemplo n.º 3
0
    def addTab(self, *args, **kwargs):
        '''Add a new tab in the tab list.'''

        tab = Tab(self.notebook,
                  self,
                  self.notebook,
                  properties={
                      'bg': 'lavender',
                      'bd': 1,
                      'highlightthickness': 0
                  })
        self.tabs[self.notebook.tabs()[-1]] = tab

        if len(self.tabs) > 1:
            self.notebook.tab(self.notebook.tabs()[-1], state='disabled')
        return
Ejemplo n.º 4
0
 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)
Ejemplo n.º 5
0
 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)
Ejemplo n.º 6
0
    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)
Ejemplo n.º 7
0
class Client:
    def __init__(self):
        self.socket = None
        self.root = ge("clientroot")

    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 updatedetailscallback(self):
        userdetails = {
            "displayname": self.displaynameinput.getText(),
            "photourl": self.photourlinput.getText()
        }
        self.sioreq({
            "kind": "updateuserdetails",
            "uid": self.uid,
            "userdetails": userdetails
        })

    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.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.userinfodiv = Div("userinfodiv")
        self.signupmaildiv.a([self.emaillabel, self.emailinput, self.passwordlabel, self.passwordinput, self.signinbutton, self.signoutbutton, self.signupbutton, self.sendverificationbutton, self.resetpasswordbutton])        
        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.updatedetailsbutton = Button("Update details", self.updatedetailscallback)
        self.userdetailsdiv.a([self.displaynamelabel, self.displaynameinput, self.photourllabel, self.photourlinput, self.updatedetailsbutton])
        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 serializeconfig(self):
        self.sioreq({
            "kind": "serializeconfig",
            "data": self.configschema.toargs()
        })

    def storecloud(self):
        self.sioreq({
            "kind": "storecloudconfig",
            "data": self.configschema.toargs()
        })

    def retrievecloud(self):
        self.sioreq({
            "kind": "retrievecloudconfig"
        })

    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):        
        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 onconnect(self):
        self.sioreq({"kind": "connected"})

    def sioreq(self, obj):
        print("->", obj)
        self.socket.emit("sioreq", obj)    

    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", self.displayName, self.email)
            print(self.providerData)
            self.nameinfodiv = Div().html("name : <span class='{}'>{}</span>".format(cpick(self.displayName, "uiinfo", "uiinfored"), getelse(self.displayName,"&lt;NA&gt;"))).pt(5)
            self.emailinfodiv = Div().html("email : <span class='{}'>{}</span>".format(cpick(self.email, "uiinfo", "uiinfored"), getelse(self.email, "&lt;NA&gt;")))
            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,"&lt;NA&gt;")))
            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 getschemaconfigfromobj(self, obj):
        self.schemaconfig = {
            "kind": "collection",
            "disposition": "dict"
        }
        if "schemaconfig" in obj:
            self.schemaconfig = obj["schemaconfig"]            
        self.authenabled = ( getrec("global/auth/enabled", self.schemaconfig) == "true" )

    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):
        self.initializefirebase()
        self.initializefirebaseui()

    def siores(self, obj):
        print("<-", obj)
        if "kind" in obj:
            kind = obj["kind"]
            if kind == "connectedack":
                self.getschemaconfigfromobj(obj)
                self.build()
                if self.authenabled:                
                    self.firebaseconfig = obj["firebaseconfig"]
                    setTimeout(self.startfirebase, 50)
            elif kind == "configsaved":
                window.alert("Config saved, {} characters".format(obj["size"]))
            elif kind == "setcloudconfig":
                self.getschemaconfigfromobj(obj)
                self.build()
                setTimeout(lambda: window.alert("Config set from cloud."), 10)
            elif kind == "alert":
                window.alert(obj["data"])
                if obj["reload"]:
                    location.reload()

    def startup(self):
        print("creating socket {}".format(SUBMIT_URL))

        self.socket = io.connect(SUBMIT_URL)

        print("socket created ok")        

        self.socket.on('connect', self.onconnect)
        self.socket.on('siores', self.siores)
######################################################
Ejemplo n.º 8
0
    def open_files(self, path_hash_dictionary):
        # file_paths is expected to be a dictionary
        # This allows for threading file opening
        # Which should speed up multiple file opening
        # especially @ application start

        file_paths = [i for i in path_hash_dictionary]

        for filename in path_hash_dictionary.items():

            file_md5 = filename[1]
            if not file_md5:
                try:
                    with open(filename[0], 'rb') as current_book:
                        first_bytes = current_book.read(
                            1024 * 32)  # First 32KB of the file
                        file_md5 = hashlib.md5(first_bytes).hexdigest()
                except FileNotFoundError:
                    return

            # Remove any already open files
            # Set focus to last file in case only one is open
            for i in range(1, self.tabWidget.count()):
                tab_metadata = self.tabWidget.widget(i).metadata
                if tab_metadata['hash'] == file_md5:
                    file_paths.remove(filename[0])
                    if not file_paths:
                        self.tabWidget.setCurrentIndex(i)
                        return

        if not file_paths:
            return

        def finishing_touches():
            self.format_contentView()
            self.start_culling_timer()

        print('Attempting to open: ' + ', '.join(file_paths))

        contents = sorter.BookSorter(file_paths, 'reading',
                                     self.database_path, True,
                                     self.temp_dir.path()).initiate_threads()

        for i in contents:
            # New tabs are created here
            # Initial position adjustment is carried out by the tab itself
            file_data = contents[i]
            Tab(file_data, self.tabWidget)

        if self.settings['last_open_tab'] == 'library':
            self.tabWidget.setCurrentIndex(0)
            self.listView.setFocus()
            self.settings['last_open_tab'] = None
            return

        for i in range(1, self.tabWidget.count()):
            this_path = self.tabWidget.widget(i).metadata['path']
            if self.settings['last_open_tab'] == this_path:
                self.tabWidget.setCurrentIndex(i)
                self.settings['last_open_tab'] = None
                finishing_touches()
                return

        self.tabWidget.setCurrentIndex(self.tabWidget.count() - 1)
        finishing_touches()