Beispiel #1
0
    def updateNetworkData(self, rq):
        data = {}
        self.dns_name = rq['data']['dns_name']
        self.auto_to_ap = rq['data']['auto_to_ap']

        config = weioConfig.getConfiguration()
        config['dns_name'] = self.dns_name + ".local"
        config['auto_to_ap'] = self.auto_to_ap
      
        if (platform.machine() == 'mips'):
            # Change avahi name
            command = "sh scripts/change_boardname.sh " + self.dns_name
            try:
                subprocess.call(command, shell=True)
                firstTimeSwitch = "NO"
                config['first_time_run']=firstTimeSwitch
                data['data'] = "msg_success"
            except:
                output = "ERR_CMD BRDNAME"
                data['data'] = "msg_fail"
                print output
        else:
            # On PC
            firstTimeSwitch = "NO"
            config['first_time_run']=firstTimeSwitch
            data['data'] = "msg_success"
       
        # Save new user data in config file 
        weioConfig.saveConfiguration(config);
        data['requested'] = "updataNetwork"
        self.send(json.dumps(data))
Beispiel #2
0
    def decompressNewProject(self, rq):
        print "decompress"
        f = rq['data']
        name = f['name']
        contents = f['data']
        storageUnit = rq['storageUnit'] +"/"
        #print contents

        # get configuration from file
        confFile = weioConfig.getConfiguration()
        pathCurrentProject = "www/" + storageUnit

        projectName = name.split(".tar")[0]
        data = {}

        if (weioFiles.checkIfDirectoryExists(pathCurrentProject+projectName) is False) :
            #decode from base64, file is binary
            bb = contents
            bb = bb.split(",")[1] # split header, for example: "data:image/jpeg;base64,"
            weioFiles.saveRawContentToFile(pathCurrentProject+name, bb.decode("base64"))
            #print "save to ", pathCurrentProject+name
            weioFiles.createDirectory(pathCurrentProject+projectName)
            #print "mkdir ", pathCurrentProject+"userProjects/"+projectName
            weioFiles.unTarFile(pathCurrentProject+name, pathCurrentProject+projectName)
            #print "untar ", pathCurrentProject+"userProjects/"+projectName

            data['request'] = "changeProject"
            data['data'] = storageUnit+projectName

            self.changeProject(data)
        else :
            data['requested'] = 'status'
            data['status'] = "Error this projet already exists"
            self.broadcast(clients, json.dumps(data))
Beispiel #3
0
    def createTarForProject(self, rq):
        # TEST IF NAME IS OK FIRST
        # get configuration from file
        config = weioConfig.getConfiguration()
        data = {}
        data['requested'] = "status"
        data['status'] = "Making archive..."
        self.broadcast(clients, json.dumps(data))

        data['requested'] = rq['request']

        splitted = config["last_opened_project"].split("/")
        print "CHOOSE NAME", splitted
        lp = splitted[-1]


        if (weioFiles.checkIfDirectoryExists(config["last_opened_project"])):
            weioFiles.createTarfile(config["last_opened_project"] + "/" + lp + ".tar",
                    config["last_opened_project"]+"/")

            data['status'] = "Project archived"
            print "project archived"
        else :
            data['status'] = "Error archiving project"

        self.broadcast(clients, json.dumps(data))
Beispiel #4
0
    def loadUserProjectMain(self):
        confFile = weioConfig.getConfiguration()

        # Get the last name of project and run it

        projectModule = confFile["last_opened_project"].replace('/', '.') + ".main"
        #print "CALL", projectModule

        result = None

        if (self.lastCalledProjectPath == projectModule):
            #print "RELOADING"
            result = reload(self.userMain)
        else :
            #print "NEW IMPORT"
            # Import userMain from local module
            try :
                userMain = __import__(projectModule, fromlist=[''])
                result = userMain
            except :
                #print "MODULE CAN'T BE LOADED"
                result = None

        self.lastCalledProjectPath = projectModule
        return result
Beispiel #5
0
    def createNewFile(self, rq):
        data = {}
        # this function is similar to saveFile

        # echo given request
        data['requested'] = rq['request']

        # don't echo given data to spare unnecessary communication, just return name
        f = rq['data']
        name = f['name']
        contents = f['data']

        # get configuration from file
        confFile = weioConfig.getConfiguration()
        print "WILL BE SAVED IN ", name

        if ((".html" in name) or (".py" in name) or (".json" in name) or
            (".css" in name) or (".txt" in name) or (".js" in name) or
            (".md" in name) or (".svg" in name) or (".xml" in name) or
            (".less" in name) or (".coffee" in name)):

            weioFiles.saveRawContentToFile(confFile["last_opened_project"] + "/" + name, contents)
        else :

            #decode from base64, file is binary
            bin = contents
            bin = bin.split(",")[1] # split header, for example: "data:image/jpeg;base64,"
            weioFiles.saveRawContentToFile(confFile["last_opened_project"] + "/" + name, bin.decode("base64"))

        #print (pathCurrentProject+pathname)

        data['status'] = name + " has been created"
        self.broadcast(clients, json.dumps(data))
Beispiel #6
0
    def createTarForProject(self, rq):
        # TEST IF NAME IS OK FIRST
        # get configuration from file
        config = weioConfig.getConfiguration()
        data = {}
        data['requested'] = "status"
        data['status'] = "Making archive..."
        self.broadcast(clients, json.dumps(data))

        data['requested'] = rq['request']

        splitted = config["last_opened_project"].split("/")
        print "CHOOSE NAME", splitted
        lp = splitted[-1]

        if (weioFiles.checkIfDirectoryExists(config["last_opened_project"])):
            weioFiles.createTarfile(
                config["last_opened_project"] + "/" + lp + ".tar",
                config["last_opened_project"] + "/")

            data['status'] = "Project archived"
            print "project archived"
        else:
            data['status'] = "Error archiving project"

        self.broadcast(clients, json.dumps(data))
Beispiel #7
0
    def changeProject(self,rq):
        #print "CHANGE PROJECT", rq
        # get configuration from file
        print "TO CHANGE ", rq
        config = weioConfig.getConfiguration()

        virtPath = rq['data']
        storage = os.path.dirname(virtPath)
        print 'STORAGE', storage
        path = "www/"+virtPath
        print 'STORAGE', path

        config["last_opened_project"] = path
        weioConfig.saveConfiguration(config);

        # In this way we avoid migrations between pc and weio and other archs
        try :
            os.remove(path+"/www")
        except:
            print "Symlink don't exist. Will create new one for www in this project"
        os.symlink(config["absolut_root_path"] + "/www/", path + "/www")

        data = {}
        data['requested'] = rq['request']
        self.broadcast(clients, json.dumps(data))

        rqlist = ["stop", "getLastProjectName", "getUserProjetsFolderList"]

        for i in range(0,len(rqlist)):
            rq['request'] = rqlist[i]
            callbacks[ rq['request'] ](self, rq)
Beispiel #8
0
    def decompressNewProject(self, rq):
        print "decompress"
        f = rq['data']
        name = f['name']
        contents = f['data']
        storageUnit = rq['storageUnit'] +"/"
        #print contents

        # get configuration from file
        confFile = weioConfig.getConfiguration()
        pathCurrentProject = "www/" + storageUnit

        projectName = name.split(".tar")[0]
        data = {}

        if (weioFiles.checkIfDirectoryExists(pathCurrentProject+projectName) is False) :
            #decode from base64, file is binary
            bb = contents
            bb = bb.split(",")[1] # split header, for example: "data:image/jpeg;base64,"
            weioFiles.saveRawContentToFile(pathCurrentProject+name, bb.decode("base64"))
            #print "save to ", pathCurrentProject+name
            weioFiles.createDirectory(pathCurrentProject+projectName)
            #print "mkdir ", pathCurrentProject+"userProjects/"+projectName
            weioFiles.unTarFile(pathCurrentProject+name, pathCurrentProject+projectName)
            #print "untar ", pathCurrentProject+"userProjects/"+projectName

            data['request'] = "changeProject"
            data['data'] = storageUnit+projectName

            self.changeProject(data)
        else :
            data['requested'] = 'status'
            data['status'] = "Error this projet already exists"
            self.broadcast(clients, json.dumps(data))
Beispiel #9
0
    def newProject(self, rq):
        config = weioConfig.getConfiguration()
        print "NEW PROJECT", rq
        data = {}
        data['requested'] = rq['request']
        path = ""
        storage = rq['storageUnit']

        path = "www/" + rq['storageUnit'] + "/" + rq['path']

        print "CREATE PROJECT", path
        if (len(path)>0):
            if (weioFiles.checkIfDirectoryExists(path)):
                print "ALREADY EXISTS"
                data['status'] = "Can't create project"
                data['error'] = "already exists"
                data['path'] = path
                self.broadcast(clients, json.dumps(data))
            else :
                weioFiles.createDirectory(path)
                # ADD HERE SOME DEFAULT FILES
                # adding __init__.py
                weioFiles.saveRawContentToFile(path + "/__init__.py", "")

                # make symlink to www/
                if (storage == "sd" or storage == "usbFlash"):
                    if (storage == "sd"):
                        if os.path.isdir(path):
                            if not (os.path.exists(path + "/www")):
                                print "COPYING TO ", path + "/www"
                                copytree(config["absolut_root_path"] + "/www/", path + "/www", ignore=ignore_patterns('sd', 'flash', 'examples', 'usbFlash'))
                                print "OK"
                    else:
                        if not (os.path.exists(path + "/www")):
                            print "COPYING TO ", path + "/www"
                            copytree(config["absolut_root_path"] + "/www/", path + "/www", ignore=ignore_patterns('sd', 'flash', 'examples', 'usbFlash'))
                            print "OK"
                else:
                    try:
                        os.remove(path + "/www")
                    except:
                        print "Symlink don't exist. Will create new one for this project"
                    os.symlink(config["absolut_root_path"] + "/www/", path + "/www")

                # copy all files from directory boilerplate to destination
                mypath = "www/libs/weio/boilerPlate/"
                onlyfiles = [ f for f in os.listdir(mypath) if isfile(join(mypath,f)) ]
                for f in onlyfiles:
                    copyfile(mypath+f, path +"/"+f)

                print "LASTOPENED new project", path
                config["last_opened_project"] = path
                weioConfig.saveConfiguration(config);

                data['status'] = "New project created"
                data['path'] = path
                self.broadcast(clients, json.dumps(data))
        else:
            print "BAD PATHNAME"
Beispiel #10
0
 def checkPermission(self, password, username):
     confFile = weioConfig.getConfiguration()
     validPass = confFile['password']
     #if username == "admin" and password == "admin":
     #    return True
     if password == validPass:
         return True
     return False
Beispiel #11
0
    def sendUserData(self, rq):
        data = {}
        # get configuration from file
        config = weioConfig.getConfiguration()
        data['requested'] = rq['request']

        data['name'] = config["user"]
        self.broadcast(clients, json.dumps(data))
Beispiel #12
0
 def checkPermission(self, password, username):
     confFile = weioConfig.getConfiguration()
     validPass = confFile['password']
     #if username == "admin" and password == "admin":
     #    return True
     if password == validPass:
         return True
     return False
Beispiel #13
0
    def sendUserData(self,rq):
        data = {}
        # get configuration from file
        config = weioConfig.getConfiguration()
        data['requested'] = rq['request']

        data['name'] = config["user"]
        self.broadcast(clients, json.dumps(data))
Beispiel #14
0
    def post(self):
        confFile = weioConfig.getConfiguration()
        fullName = self.get_argument("fullName", "")
        passwd = self.get_argument("password", "")
        boardname = self.get_argument("boardname", "")

        # This is two letters country code to be used to setup wifi region
        countryCode = self.get_argument("countryCode", "")

        print "************ ", fullName, passwd, boardname, countryCode

        data = {}
        # OK now is time to setup username and password
        confFile['user'] = fullName
        weioConfig.saveConfiguration(confFile)

        output = "OK PASSWD"
        #echo -e "weio\nweio" | passwd

        # ATTENTION, DON'T MESS WITH THIS STUFF ON YOUR LOCAL COMPUTER
        # First protection is mips detection, second is your own OS
        # who hopefully needs sudo to change passwd on the local machine
        if (platform.machine() == 'mips'):

            # Change root password
            command = "sh scripts/change_root_pswd.sh " + passwd
            print "EXEC : " + command

            try:
                subprocess.call(command, shell=True)
                firstTimeSwitch = "NO"
                confFile['first_time_run']=firstTimeSwitch
            except:
                output = "ERR_CMD PASSWD"
                print output

            # Change avahi name
            command = "sh scripts/change_boardname.sh " + boardname
            print "EXEC : " + command

            try:
                subprocess.call(command, shell=True)
            except:
                output = "ERR_CMD BRDNAME"

        else:
            # On PC
            firstTimeSwitch = "NO"
            confFile['first_time_run']=firstTimeSwitch
        
        # Save new password in the config file
        confFile['password'] = passwd

        # Write in config file
        weioConfig.saveConfiguration(confFile)

        self.set_secure_cookie("user", tornado.escape.json_encode("weio"))
        self.redirect(self.get_argument("next", u"/"))
Beispiel #15
0
    def downloadUpdate(self, data):
        config = weioConfig.getConfiguration()

        # ok now save binary in /tmp (folder in RAM)
        print "downloaded"

        fileToStoreUpdate = ""
        if (platform.machine()=="mips") :
            fileToStoreUpdate = "/tmp/weioUpdate.tar.gz"
            pathToDecompressUpdate = "/tmp"
        else :
            fileToStoreUpdate = "./weioUpdate.tar.gz"
            pathToDecompressUpdate = "./"

        if not(self.downloadUpdateLink is None):

            sw = functools.partial(self.sizeWatcher, fileToStoreUpdate, self.updateDownloadSize)
            sizeCheckerCallback = ioloop.PeriodicCallback(sw, 500)
            sizeCheckerCallback.start()
            self.startDownload(self.downloadUpdateLink, fileToStoreUpdate)
            sizeCheckerCallback.stop()

        # Check is file size is the same as on the server
        sizeOnDisk = os.path.getsize(fileToStoreUpdate)
        print "comparing sizes", sizeOnDisk, self.updateDownloadSize
        if (sizeOnDisk == self.updateDownloadSize):
            # OK
            print "File size is OK"
            self.progressInfo("50%", "File size OK")
            print "Bundle decompressing"
            tar = tarfile.open(fileToStoreUpdate)
            tar.extractall(pathToDecompressUpdate)
            tar.close()
            print "Bundle decompressed"
            #self.progressInfo("80%", "WeIO Bundle decompressed")

            # kill arhive that we don't need anymore to free RAM
            os.remove(fileToStoreUpdate)
            global currentWeioConfigurator
            print "Setting kill flag to YES in current config.weio"
            print "Now I'm ready to exit Tornado and install new version"
            config["kill_flag"] = "YES"
            weioConfig.saveConfiguration(config)
            #self.progressInfo("81%", "WeIO installing")
            # Now quit Tornado and leave script to do his job
            ioloop.IOLoop.instance().stop()
            exit()

        else :
            print "MD5 checksum is not OK, retrying..."
            if (self.downloadTries<2):
                self.progressInfo("5%", "Downloading Bundle again, MD5 checkum was not correct")
                self.downloadUpdate(None)
            else:
                print "Something went wrong. Check Internet connection and try again later"
                self.progressInfo("0%", "Something went wrong. Check Internet connection and try again later")

            self.downloadTries+=1
Beispiel #16
0
    def duplicateProject(self, rq):
        config = weioConfig.getConfiguration()

        print "DUPLICATE",rq

        storage = rq['storageUnit']

        path = "www/" + rq['storageUnit'] + "/" + rq['path']

        print "DUPLICATE PROJECT", path
        data = {}
        if (len(path)>0):
            if (storage != "sd" and storage != "usbFlash"):
                # Destroy symlink
                if os.path.islink(config["last_opened_project"]+"/www"):
                    os.remove(config["last_opened_project"]+"/www")
                else:
                    shutil.rmtree(config["last_opened_project"]+"/www")
                # copy all files
                try:
                    copytree(config["last_opened_project"], path)
                except:
                    print sys.exc_info()[0]
            else:
                if os.path.isdir("www/"+rq['storageUnit']):
                    try: 
                        copytree(config["last_opened_project"], path, ignore=ignore_patterns('www'))
                    except:
                        print sys.exc_info()[0]

            if (storage != "sd" and storage != "usbFlash"):
                # Recreate symlink
                os.symlink(config["absolut_root_path"] + "/www/", path + "/www")
            else:
                if not (os.path.exists(path + "/www")):
                    copytree(config["absolut_root_path"] + "/www/", path + "/www", ignore=ignore_patterns('sd', 'flash', 'examples', 'usbFlash'))

            config["last_opened_project"] = path
            weioConfig.saveConfiguration(config)

            data['status'] = "Project duplicated"

            data['requested'] = "status"
            self.broadcast(clients, json.dumps(data))

            # now go to newely duplicated project

            data['request'] = "changeProject"
            data['data'] = rq['storageUnit'] + "/" + rq['path']

            self.changeProject(data)
        else:
            print "BAD PATHNAME"
            data['status'] = "Error duplicating project"

            data['requested'] = "status"
            self.broadcast(clients, json.dumps(data))
Beispiel #17
0
    def sendUserPortNumber(self, rq):

        # get configuration from file
        config = weioConfig.getConfiguration()

        data = {}
        data['requested'] = rq['request']
        data['data'] = config["userAppPort"]
        # Send connection information to the client
        self.broadcast(clients, json.dumps(data))
Beispiel #18
0
    def sendUserPortNumber(self, rq):

        # get configuration from file
        config = weioConfig.getConfiguration()

        data = {}
        data['requested'] = rq['request']
        data['data'] = config["userAppPort"]
        # Send connection information to the client
        self.broadcast(clients, json.dumps(data))
Beispiel #19
0
    def checkConnection(self) :
        command = "iwconfig " + self.interface
        status = weioSubprocess.shellBlocking(command)

        #print(str(status))
        # We are in STA mode, so check if we are connected
        if (status == "ERR_CMD") or "No such device" in status :
            # WiFi is DOWN
            print "Wifi is DOWN"
            self.mode = None
        # Check if wlan0 is in Master mode
        elif "Mode:Master" in status :
            print "AP Mode"
            self.mode = "ap"
            #self.essid = status.strip().startswith("ESSID:").split(':')[1]
        elif "Mode:Managed" in status :
            if "Access Point: Not-Associated" in status :
                self.mode = None
            else :
                self.mode = "sta"

        # We can not serve anything if we are not in sta or ap mode
        #print "CHECKING WIFI!"
        #if (self.mode != None):
        #   print "self.mode = " + self.mode
        #print "weioIpAddress.getLocalIpAddress() = " + weioIpAddress.getLocalIpAddress()

        if (self.mode == None):
            self.disconnectedCounter = self.disconnectedCounter + 1
        else:
            self.disconnectedCounter = 0

        config = weioConfig.getConfiguration()

        if ((self.disconnectedCounter >= 2 or (self.mode == "sta" and weioIpAddress.getLocalIpAddress() == ''))
             and config['auto_to_ap'] == "YES"):
            # Move to Master mode
            print "Trying to move to AP RESCUE mode..."
            subprocess.call("scripts/wifi_set_mode.sh rescue", shell=True)

            self.disconnectedCounter = 0

            # Restart Tornado (shell script bring it up whenever it exits)
            #cmd = "/etc/init.d/weio_run restart"
            #weioSubprocess.shellBlocking(cmd)
            print "************* EXITING ****************"
            os._exit(os.EX_OK)

        # At this point connection has been maid, and all we have to do is check ESSID
        #print "WIFI ESSID : ", status
        pat = r"(?<=ESSID:\")(.*\n?)(?=\")"
        #print "RESULT", re.findall(pat, status)[0]
        essidName = re.findall(pat, status)
        if (len(essidName)>0):
            self.essid = essidName[0]
Beispiel #20
0
    def get(self):
        global confFile
        global firstTimeSwitch
        confFile = weioConfig.getConfiguration()
        firstTimeSwitch = confFile['first_time_run']

        if (firstTimeSwitch == "YES"):
            path = "www/firstTime.html"
        else:
            path = confFile['editor_html_path']

        self.render(path, error="")
Beispiel #21
0
    def sendIp(self, rq):

        # get configuration from file
        config = weioConfig.getConfiguration()

        data = {}
        ip = weioIpAddress.getLocalIpAddress()
        #publicIp = weioIpAddress.getPublicIpAddress()
        data['requested'] = rq['request']
        data['status'] = config["dns_name"] + " on " + ip
        # Send connection information to the client
        self.broadcast(clients, json.dumps(data))
Beispiel #22
0
    def get(self):
        global confFile
        global firstTimeSwitch
        confFile = weioConfig.getConfiguration()
        firstTimeSwitch = confFile['first_time_run']

        if (firstTimeSwitch=="YES") :
            path = "www/firstTime.html"
        else :
            path = confFile['editor_html_path']

        self.render(path, error="")
Beispiel #23
0
    def sendIp(self,rq):

        # get configuration from file
        config = weioConfig.getConfiguration()

        data = {}
        ip = weioIpAddress.getLocalIpAddress()
        #publicIp = weioIpAddress.getPublicIpAddress()
        data['requested'] = rq['request']
        data['status'] = config["dns_name"] + " on " + ip
        # Send connection information to the client
        self.broadcast(clients, json.dumps(data))
Beispiel #24
0
    def play(self, rq={'request':'play'}):
        """ This is where all the magic happens.

            "Play" button will spawn a new subprocess
            which will execute users program written in the editor.
            This subprocess will communicate with Tornado wia non-blocking pipes,
            so that Tornado can simply transfer subprocess's `stdout` and `stderr`
            to the client via WebSockets. """

        # get configuration from file
        config = weioConfig.getConfiguration()

        # stop if process is already running
        self.stop()

        data = {}
        lp = config["last_opened_project"]

        # check if user project exists before launching
        #if (weioFiles.checkIfFileExists(up+lp+"main.py")):
        if (weioFiles.checkIfFileExists(lp+"/main.py")):
            #print("weioMain indipendent process launching...")

            # Inform client the we run subprocess
            data['requested'] = rq['request']
            data['status'] = "Warming up the engines..."
            self.send(json.dumps(data))

            consoleWelcome = {}
            consoleWelcome['data'] = "WeIO user program started"
            consoleWelcome['serverPush'] = "sysConsole"

            self.lastLaunched = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")

            consoleWelcome['data'] = 'WeIO user server launched ' + self.lastLaunched
            if (weioIdeGlobals.CONSOLE != None):
                #weioIdeGlobals.CONSOLE.send(json.dumps(data))
                weioIdeGlobals.CONSOLE.send(json.dumps(consoleWelcome))
            self.playing = True

            # send *start* command to user tornado
            self.weioPipe.stdin.write("*START*")
            

        else : # FILE DON'T EXIST
            warning = {}
            warning['requested'] = rq['request']
            warning['status'] = "main.py don't exist!"
            warning['state'] = "error"
            self.send(json.dumps(warning))
Beispiel #25
0
    def play(self, rq={'request':'play'}):
        """ This is where all the magic happens.

            "Play" button will spawn a new subprocess
            which will execute users program written in the editor.
            This subprocess will communicate with Tornado wia non-blocking pipes,
            so that Tornado can simply transfer subprocess's `stdout` and `stderr`
            to the client via WebSockets. """

        # get configuration from file
        config = weioConfig.getConfiguration()

        # stop if process is already running
        self.stop()

        data = {}
        lp = config["last_opened_project"]

        # check if user project exists before launching
        #if (weioFiles.checkIfFileExists(up+lp+"main.py")):
        if (weioFiles.checkIfFileExists(lp+"/main.py")):
            print("weioMain indipendent process launching...")

            # Inform client the we run subprocess
            data['requested'] = rq['request']
            data['status'] = "Warming up the engines..."
            self.send(json.dumps(data))

            consoleWelcome = {}
            consoleWelcome['serverPush'] = "sysConsole"

            self.lastLaunched = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")

            consoleWelcome['data'] = 'WeIO user server launched ' + self.lastLaunched
            if (weioIdeGlobals.CONSOLE != None):
                weioIdeGlobals.CONSOLE.send(json.dumps(data))
            self.playing = True

            # send *start* command to user tornado
            self.weioPipe.stdin.write("*START*")
            

        #weioIdeGlobals.CONSOLE.send(json.dumps(consoleWelcome))
        else : # FILE DON'T EXIST
            warning = {}
            warning['requested'] = rq['request']
            warning['status'] = "main.py don't exist!"
            warning['state'] = "error"
            self.send(json.dumps(warning))
Beispiel #26
0
    def sendPlatformDetails(self, rq):
        # get configuration from file
        config = weioConfig.getConfiguration()

        data = {}

        platformS = ""

        platformS += "WeIO version " + config["weio_version"] + " with Python " + \
                            platform.python_version() + " on " + platform.system() + "<br>"
        platformS += "BSD, Nodesign.net 2015 Uros Petrevski & Drasko Draskovic <br>"

        data['serverPush'] = 'sysConsole'
        data['data'] = platformS
        self.broadcast(clients, json.dumps(data))
Beispiel #27
0
    def sendPlatformDetails(self, rq):
        # get configuration from file
        config = weioConfig.getConfiguration()

        data = {}

        platformS = ""

        platformS += "WeIO version " + config["weio_version"] + " with Python " + \
                            platform.python_version() + " on " + platform.system() + "<br>"
        platformS += "GPL 3, Nodesign.net 2013 Uros Petrevski & Drasko Draskovic <br>"

        data['serverPush'] = 'sysConsole'
        data['data'] = platformS
        self.broadcast(clients, json.dumps(data))
Beispiel #28
0
    def sendPlatformDetails(self, rq):
        # get configuration from file
        config = weioConfig.getConfiguration()

        data = {}

        platformS = ""

        platformS += "WeIO version " + config["weio_version"] + " with Python " + \
                            platform.python_version() + " on " + platform.system() + "<br>"
        platformS += "GPL 3, Nodesign.net 2013-2015 Uros Petrevski & Drasko Draskovic <br>"

        data['serverPush'] = 'sysConsole'
        data['data'] = platformS
        weioIdeGlobals.CONSOLE.send(json.dumps(data))
Beispiel #29
0
    def get(self):
        confFile = weioConfig.getConfiguration()
        firstTimeSwitch = confFile['first_time_run']

        if (firstTimeSwitch=="YES") :
            self.redirect("/signin")
            return

        if (confFile["login_required"] == "YES"):
            if not self.current_user:
                self.redirect("/login")
                return

        path = confFile['editor_html_path']
        self.render(path, error="")
Beispiel #30
0
    def post(self):
        confFile = weioConfig.getConfiguration()
        fullName = self.get_argument("fullName", "")
        passwd = self.get_argument("password", "")
        hostname = self.get_argument("hostname", "")

        # This is two letters country code to be used to setup wifi region
        countryCode = self.get_argument("countryCode", "")

        print "************ ", fullName, passwd, hostname, countryCode

        data = {}
        # OK now is time to setup username and password
        confFile['user'] = fullName
        weioConfig.saveConfiguration(confFile)

        output = "OK PASSWD"
        #echo -e "weio\nweio" | passwd

        if (platform.machine() == 'mips'):
            command = "sh scripts/change_root_pswd.sh " + passwd
            print "EXEC : " + command

        try:
            # ATTENTION, DON'T MESS WITH THIS STUFF ON YOUR LOCAL COMPUTER
            # First protection is mips detection, second is your own OS
            # who hopefully needs sudo to change passwd on the local machine
            if (platform.machine() == 'mips'):
                print Popen(command, stdout=PIPE, shell=True).stdout.read()
                firstTimeSwitch = "NO"
                confFile['first_time_run'] = firstTimeSwitch
            else:
                firstTimeSwitch = "NO"
                confFile['first_time_run'] = firstTimeSwitch
        except:
            output = "ERR_CMD"
        print output

        # Save new password in the config file
        confFile['password'] = passwd

        # Write in config file
        weioConfig.saveConfiguration(confFile)

        self.set_secure_cookie("user", tornado.escape.json_encode("weio"))
        self.redirect(self.get_argument("next", u"/"))
Beispiel #31
0
    def checkVersion(self, response):
        print response.body
        config = weioConfig.getConfiguration()

        data = json.loads(response.body)

        lastUpdate = data["recipe"]

        # Read version form json file
        # XXX it supposes that the distant version number is prefixed with 'v'
        # The updater will break here if this prefix is removed in the future
        distantVersion = float(lastUpdate["version"].split("v")[1])

        # Check the current version
        currentVersion = float(config["weio_version"])

        print "current",currentVersion,"distant", distantVersion
        rsp = {}

        rsp['requested'] = "checkVersion"
        rsp['localVersion'] = str(currentVersion)
        rsp['distantVersion'] = str(distantVersion)
        rsp['needsUpdate'] = "NO"

        # version differs so we need an update
        if (distantVersion > currentVersion):
            print "Update is available"
            # OK we have to update weio version
            rsp['description'] = lastUpdate["title"]
            rsp['whatsnew'] = lastUpdate["body"]
            #rsp['install_duration'] = self.estimatedInstallTime
            self.downloadUpdateLink = ""

            # set all parameters for download, but DON'T download yet
            # this is a just version check
            self.updateFileName = self.fwPath + "updateRecipe"
            rsp['needsUpdate'] = "YES"
            print "setting parameters :"
            self.fwDownloadLink = lastUpdate["download_url"]
            print "download url", self.fwDownloadLink
            self.fwDownloadSize = lastUpdate["size"]
            print "file size", self.fwDownloadSize
            self.fwDownloadMD5 = lastUpdate["md5"]
            print "md5 checksum", self.fwDownloadSize

        self.send(json.dumps(rsp))
Beispiel #32
0
    def checkVersion(self, response):
        print response.body
        config = weioConfig.getConfiguration()

        data = json.loads(response.body)
        #f = open("github.json", "w")
        #f.write(json.dumps(data, indent=4, sort_keys=True))
        #f.close()
        #print json.dumps(data, indent=4, sort_keys=True)
        lastUpdate = data[0]
        distantVersion = float(lastUpdate["tag_name"].split("v")[1])

        currentVersion = float(config["weio_version"])
        print "current",currentVersion,"distant", distantVersion
        rsp = {}

        rsp['requested'] = "checkVersion"
        rsp['localVersion'] = str(currentVersion)
        rsp['distantVersion'] = str(distantVersion)

        if (distantVersion > currentVersion): 
            print "OK update is needed"
            # OK we have to update weio version
            rsp['needsUpdate'] = "YES"
            rsp['description'] = lastUpdate["name"]
            rsp['whatsnew'] = lastUpdate["body"]
            rsp['install_duration'] = self.estimatedInstallTime
            self.downloadUpdateLink = ""

            for file in lastUpdate["assets"]:
                if ("weio.tar.gz" in file["name"]):
                    self.downloadUpdateLink = file["browser_download_url"]
                    self.updateDownloadSize = file["size"]
                    print self.updateDownloadSize, "size", file["size"]
        else :
            rsp['needsUpdate'] = "NO"

        # You can always reflash with last version even if there are no new updates
        for file in lastUpdate["assets"]:
            if ("weio_recovery.bin" in file["name"]):
                print "found weio_recovery"
                self.fwDownloadLink = file["browser_download_url"]
                self.fwDownloadSize = file["size"]

        self.send(json.dumps(rsp))
Beispiel #33
0
    def checkVersion(self, response):
        wifiMode = "ap"
        if (platform.machine() == 'mips') :
            wifiMode = weioIdeGlobals.WIFI.mode
            print "WIFI MODE ", wifiMode
        else :
            wifiMode = "sta"
        
        rsp={}
    
        if (wifiMode=="sta") : # check Internet
            global currentWeioConfigurator
            
            self.distantJsonUpdater = json.loads(str(response.body))
            currentWeioConfigurator = weioConfig.getConfiguration()

            print "My software version " + \
                currentWeioConfigurator["weio_version"] + \
                " Version on WeIO server " + \
                self.distantJsonUpdater["version"] + \
                " Needs " + str(self.distantJsonUpdater['install_duration']) + " seconds to install"
        
            # Send response to the browser
            
            rsp['requested'] = "checkVersion"
            rsp['localVersion'] = currentWeioConfigurator["weio_version"]
            rsp['distantVersion'] = self.distantJsonUpdater["version"]
        
            distantVersion = float(self.distantJsonUpdater["version"])
            localVersion = float(currentWeioConfigurator["weio_version"])
            if (distantVersion > localVersion) :
                rsp['needsUpdate'] = "YES"
                rsp['description'] = self.distantJsonUpdater['description']
                rsp['whatsnew'] = self.distantJsonUpdater['whatsnew']
                rsp['install_duration'] = self.distantJsonUpdater['install_duration']
                self.estimatedInstallTime = self.distantJsonUpdater['install_duration']
            else :
                rsp['needsUpdate'] = "NO"
        
            
        elif (wifiMode=="ap") :
            rsp['needsUpdate'] = "NO"
        
        # Send connection information to the client
        self.send(json.dumps(rsp))
Beispiel #34
0
    def checkVersion(self, response):
        print response.body
        config = weioConfig.getConfiguration()

        data = json.loads(response.body)
        #f = open("github.json", "w")
        #f.write(json.dumps(data, indent=4, sort_keys=True))
        #f.close()
        #print json.dumps(data, indent=4, sort_keys=True)
        lastUpdate = data[0]
        distantVersion = float(lastUpdate["tag_name"].split("v")[1])

        currentVersion = float(config["weio_version"])
        print "current", currentVersion, "distant", distantVersion
        rsp = {}

        rsp['requested'] = "checkVersion"
        rsp['localVersion'] = str(currentVersion)
        rsp['distantVersion'] = str(distantVersion)

        if (distantVersion > currentVersion):
            print "OK update is needed"
            # OK we have to update weio version
            rsp['needsUpdate'] = "YES"
            rsp['description'] = lastUpdate["name"]
            rsp['whatsnew'] = lastUpdate["body"]
            rsp['install_duration'] = self.estimatedInstallTime
            self.downloadUpdateLink = ""

            for file in lastUpdate["assets"]:
                if ("weio.tar.gz" in file["name"]):
                    self.downloadUpdateLink = file["browser_download_url"]
                    self.updateDownloadSize = file["size"]
                    print self.updateDownloadSize, "size", file["size"]
        else:
            rsp['needsUpdate'] = "NO"

        # You can always reflash with last version even if there are no new updates
        for file in lastUpdate["assets"]:
            if ("weio_recovery.bin" in file["name"]):
                print "found weio_recovery"
                self.fwDownloadLink = file["browser_download_url"]
                self.fwDownloadSize = file["size"]

        self.send(json.dumps(rsp))
Beispiel #35
0
    def sendLastProjectName(self,rq):
        # get configuration from file
        config = weioConfig.getConfiguration()

        data = {}
        data['requested'] = rq['request']
        lp = os.path.basename( config["last_opened_project"].strip("/") )

        storage = config["last_opened_project"].split("/")[0]

        print "USER PRJ NAME", lp

        if (weioFiles.checkIfDirectoryExists(config["last_opened_project"])):
            print "PROJ NAME", config["last_opened_project"]
            data['data'] = config["last_opened_project"].split(storage+"/")[1]
        else :
            data['data'] = "Select project here"
        # Send connection information to the client
        self.broadcast(clients, json.dumps(data))
Beispiel #36
0
    def checkForUpdates(self, rq):
        wifiMode = "ap"
        if (platform.machine() == 'mips'):
            wifiMode = weioIdeGlobals.WIFI.mode
            print "WIFI MODE ", wifiMode
        else:
            wifiMode = "sta"  # local setting

        if (wifiMode == "sta"):
            data = {}
            if (self.isConnected("we-io.net")
                    or self.isConnected("www.github.com")):
                config = weioConfig.getConfiguration()
                repository = ""
                print "REPO", config["weio_update_use_official_repository"]
                if (config["weio_update_use_official_repository"] == "YES"):
                    repository = config["weio_update_official_repository"]
                else:
                    repository = config["weio_update_alternate_repository"]

                h = httputil.HTTPHeaders({
                    "Accept": "application/vnd.github.v3+json",
                    "User-Agent": "weio"
                })
                req = None
                if (config["weio_update_use_official_repository"] == "YES"):
                    req = httpclient.HTTPRequest(repository, headers=h)
                else:
                    req = httpclient.HTTPRequest(repository)

                http_client = httpclient.AsyncHTTPClient()
                http_client.fetch(req, callback=self.checkVersion)
            else:
                # not connected to the internet
                print "NO INTERNET CONNECTION"
                data['serverPush'] = "noInternetConnection"
                data['data'] = "Can't reach Internet servers"
                self.send(json.dumps(data))
        else:
            print "NO INTERNET CONNECTION"
            data['serverPush'] = "noInternetConnection"
            data['data'] = "Can't reach Internet servers"
            self.send(json.dumps(data))
Beispiel #37
0
    def updateNetworkData(self, rq):
        data = {}
        self.dns_name = rq['data']['dns_name']
        self.auto_to_ap = rq['data']['auto_to_ap']
        self.timezone = rq['data']['timezone']
       
        config = weioConfig.getConfiguration()
        config['dns_name'] = self.dns_name + ".local"
        config['auto_to_ap'] = self.auto_to_ap

         # Check timezone
        if self.timezone:
            config["timezone"] = self.timezone
         
        if (platform.machine() == 'mips'):
            # Change avahi name
            command = "sh scripts/change_boardname.sh " + self.dns_name
            if self.timezone:
                commandConfig = "uci set system.@system[0].timezone=" + self.timezone  # Set timezone on openwrt config (required for system reboot)
                commandCommitConfig = "uci commit system.@system[0].timezone"
         
            try:
                subprocess.call(command, shell=True)
                subprocess.call(commandConfig, shell=True)
                subprocess.call(commandCommitConfig, shell=True)
            
                firstTimeSwitch = "NO"
                config['first_time_run']=firstTimeSwitch
                data['data'] = "msg_success"
            except:
                output = "ERR_CMD BRDNAME"
                data['data'] = "msg_fail"
                print output
        else:
            # On PC
            firstTimeSwitch = "NO"
            config['first_time_run']=firstTimeSwitch
            data['data'] = "msg_success"
       
        # Save new user data in config file 
        weioConfig.saveConfiguration(config);
        data['requested'] = "updataNetwork"
        self.send(json.dumps(data))
Beispiel #38
0
    def updateNetworkData(self, rq):
        data = {}
        self.dns_name = rq['data']['dns_name']
        self.auto_to_ap = rq['data']['auto_to_ap']
        self.timezone = rq['data']['timezone']

        config = weioConfig.getConfiguration()
        config['dns_name'] = self.dns_name + ".local"
        config['auto_to_ap'] = self.auto_to_ap

        # Check timezone
        if self.timezone:
            config["timezone"] = self.timezone

        if (platform.machine() == 'mips'):
            # Change avahi name
            command = "sh scripts/change_boardname.sh " + self.dns_name
            if self.timezone:
                commandConfig = "uci set system.@system[0].timezone=" + self.timezone  # Set timezone on openwrt config (required for system reboot)
                commandCommitConfig = "uci commit system.@system[0].timezone"

            try:
                subprocess.call(command, shell=True)
                subprocess.call(commandConfig, shell=True)
                subprocess.call(commandCommitConfig, shell=True)

                firstTimeSwitch = "NO"
                config['first_time_run'] = firstTimeSwitch
                data['data'] = "msg_success"
            except:
                output = "ERR_CMD BRDNAME"
                data['data'] = "msg_fail"
                print output
        else:
            # On PC
            firstTimeSwitch = "NO"
            config['first_time_run'] = firstTimeSwitch
            data['data'] = "msg_success"

        # Save new user data in config file
        weioConfig.saveConfiguration(config)
        data['requested'] = "updataNetwork"
        self.send(json.dumps(data))
Beispiel #39
0
    def sendLastProjectName(self,rq):
        # get configuration from file
        config = weioConfig.getConfiguration()

        data = {}
        data['requested'] = rq['request']
        lp = os.path.basename( config["last_opened_project"].strip("/") )

        storage = config["last_opened_project"].split("/")[0]

        print "USER PRJ NAME", lp

        if (weioFiles.checkIfDirectoryExists(config["last_opened_project"])):
            print "PROJ NAME", config["last_opened_project"]
            data['data'] = config["last_opened_project"].split(storage+"/")[1]
        else :
            data['data'] = "Select project here"
        # Send connection information to the client
        self.broadcast(clients, json.dumps(data))
Beispiel #40
0
    def getUserProjectsList(self, rq):
        # get configuration from file
        config = weioConfig.getConfiguration()

        data = {}
        data['requested'] = rq['request']

        allExamples = []
        allUserProjects = []

        # Examples
        examplesDir = "www/examples"

        if (os.path.exists(examplesDir)):
            dirs = get_directory_structure(examplesDir)
            a = {"storageName": "examples", "projects": dirs}
            allExamples.append(a)

        # Flash
        flashDir = "www/flash"
        if (os.path.exists(flashDir)):
            dirs = get_directory_structure(flashDir)
            a = {"storageName": "flash", "projects": dirs}
            allUserProjects.append(a)

        # SD
        flashDir = "www/sd"
        if (os.path.exists(flashDir)):
            dirs = get_directory_structure(flashDir)
            a = {"storageName": "sd", "projects": dirs}
            allUserProjects.append(a)

        # USB flashDir
        flashDir = "www/usbFlash"
        if (os.path.exists(flashDir)):
            dirs = get_directory_structure(flashDir)
            a = {"storageName": "usbFlash", "projects": dirs}
            allUserProjects.append(a)

        data['data'] = allUserProjects
        data['examples'] = allExamples
        self.broadcast(clients, json.dumps(data))
Beispiel #41
0
    def getUserProjectsList(self, rq):
        # get configuration from file
        config = weioConfig.getConfiguration()

        data = {}
        data['requested'] = rq['request']

        allExamples = []
        allUserProjects = []

        # Examples
        examplesDir = "www/examples"

        if (os.path.exists(examplesDir)):
            dirs = get_directory_structure(examplesDir)
            a = {"storageName":"examples", "projects":dirs}
            allExamples.append(a)

        # Flash
        flashDir = "www/flash"
        if (os.path.exists(flashDir)):
            dirs = get_directory_structure(flashDir)
            a = {"storageName":"flash", "projects":dirs}
            allUserProjects.append(a)

        # SD
        flashDir = "www/sd"
        if (os.path.exists(flashDir)):
           dirs = get_directory_structure(flashDir)
           a = {"storageName":"sd", "projects":dirs}
           allUserProjects.append(a)

        # USB flashDir
        flashDir = "www/usbFlash"
        if (os.path.exists(flashDir)):
           dirs = get_directory_structure(flashDir)
           a = {"storageName":"usbFlash", "projects":dirs}
           allUserProjects.append(a)

        data['data'] = allUserProjects
        data['examples'] = allExamples
        self.broadcast(clients, json.dumps(data))
Beispiel #42
0
    def get(self):
        # The configuration must be refreshed to detect 'first_time_run' change.
        # ref nodesign/weio #136
        confFile = weioConfig.getConfiguration()
        firstTimeSwitch = confFile['first_time_run']
        #print firstTimeSwitch

        if (firstTimeSwitch=="YES") :
            path = "www/signin.html"
        else :
            path = "www/userIndex.html"

            #if (weioFiles.checkIfFileExists(confFile['last_opened_project'] + "/index.html")):
            #    path = "www/userIndex.html"

            #else :
            #    path = "www/error404.html"
        #path = confFile['last_opened_project'] + "index.html"

        self.render(path, error="")
Beispiel #43
0
    def updateUserData(self, rq):
        data = {}
        self.user =  rq['data']['user']
        self.password =  rq['data']['password']
        self.login_required = rq['data']['login_required']
        self.play_composition_on_server_boot = rq['data']['play_composition_on_server_boot']
        config = weioConfig.getConfiguration()
        config["user"] = self.user
        config["play_composition_on_server_boot"] = self.play_composition_on_server_boot
        config["login_required"] = self.login_required
        # Check if new password is sent
        if self.password:
            config["password"] = self.password
       
        # ATTENTION, DON'T MESS WITH THIS STUFF ON YOUR LOCAL COMPUTER
        # First protection is mips detection, second is your own OS
        # who hopefully needs sudo to change passwd on the local machine
        if (platform.machine() == 'mips'):
            # Change root password
            command = "sh scripts/change_root_pswd.sh " + self.password

            try:
                subprocess.call(command, shell=True)
                firstTimeSwitch = "NO"
                config['first_time_run']=firstTimeSwitch
                data['data'] = "msg_success"
            
            except:
                output = "ERR_CMD PASSWD"
                data['data'] = "msg_fail"
                print output
        else:
             # On PC
            firstTimeSwitch = "NO"
            config['first_time_run']=firstTimeSwitch
            data['data'] = "msg_success"
        
        # Save new user data in config file 
        weioConfig.saveConfiguration(config);
        data['requested'] = "updateSettings"
        self.send(json.dumps(data))
Beispiel #44
0
    def updateUserData(self, rq):
        data = {}
        self.user = rq['data']['user']
        self.password = rq['data']['password']
        self.play_composition_on_server_boot = rq['data'][
            'play_composition_on_server_boot']
        config = weioConfig.getConfiguration()
        config["user"] = self.user
        config[
            "play_composition_on_server_boot"] = self.play_composition_on_server_boot
        # Check if new password is sent
        if self.password:
            config["password"] = self.password

        # ATTENTION, DON'T MESS WITH THIS STUFF ON YOUR LOCAL COMPUTER
        # First protection is mips detection, second is your own OS
        # who hopefully needs sudo to change passwd on the local machine
        if (platform.machine() == 'mips'):
            # Change root password
            command = "sh scripts/change_root_pswd.sh " + self.password

            try:
                subprocess.call(command, shell=True)
                firstTimeSwitch = "NO"
                config['first_time_run'] = firstTimeSwitch
                data['data'] = "msg_success"

            except:
                output = "ERR_CMD PASSWD"
                data['data'] = "msg_fail"
                print output
        else:
            # On PC
            firstTimeSwitch = "NO"
            config['first_time_run'] = firstTimeSwitch
            data['data'] = "msg_success"

        # Save new user data in config file
        weioConfig.saveConfiguration(config)
        data['requested'] = "updateSettings"
        self.send(json.dumps(data))
Beispiel #45
0
    def newProject(self, rq):
        config = weioConfig.getConfiguration()
        print "NEW PROJECT", rq
        data = {}
        data['requested'] = rq['request']
        path = ""
        storage = rq['storageUnit']

        path = "www/" + rq['storageUnit'] + "/" + rq['path']

        print "CREATE PROJECT", path
        if (len(path)>0):
            weioFiles.createDirectory(path)
            # ADD HERE SOME DEFAULT FILES
            # adding __init__.py
            weioFiles.saveRawContentToFile(path + "/__init__.py", "")
            
            
            # make symlink to www/
            try :
                os.remove(path + "/www")
            except:
                print "Symlink don't exist. Will create new one for this project"
            os.symlink(config["absolut_root_path"] + "/www/", path + "/www")

            # copy all files from directory boilerplate to destination
            mypath = "www/libs/weio/boilerPlate/"
            onlyfiles = [ f for f in os.listdir(mypath) if isfile(join(mypath,f)) ]
            for f in onlyfiles:
                copyfile(mypath+f, path +"/"+f)

            print "LASTOPENED new project", path
            config["last_opened_project"] = path
            weioConfig.saveConfiguration(config);

            data['status'] = "New project created"
            data['path'] = path
            self.broadcast(clients, json.dumps(data))
        else:
            print "BAD PATHNAME"
Beispiel #46
0
    def duplicateProject(self, rq):
        config = weioConfig.getConfiguration()

        print "DUPLICATE",rq

        storage = rq['storageUnit']

        path = "www/" + rq['storageUnit'] + "/" + rq['path']

        print "DUPLICATE PROJECT", path
        data = {}
        if (len(path)>0):

            # Destroy symlink
            os.remove(config["last_opened_project"]+"/www")
            # copy all files
            copytree(config["last_opened_project"], path)
            # Recreate symlink
            os.symlink(config["absolut_root_path"] + "/www/", config["last_opened_project"] + "/www")

            config["last_opened_project"] = path
            weioConfig.saveConfiguration(config)

            data['status'] = "Project duplicated"

            data['requested'] = "status"
            self.broadcast(clients, json.dumps(data))

            # now go to newely duplicated project

            data['request'] = "changeProject"
            data['data'] = rq['storageUnit'] + "/" + rq['path']

            self.changeProject(data)
        else:
            print "BAD PATHNAME"
            data['status'] = "Error duplicating project"

            data['requested'] = "status"
            self.broadcast(clients, json.dumps(data))
Beispiel #47
0
    def changeProject(self, rq):
        #print "CHANGE PROJECT", rq
        # get configuration from file
        print "TO CHANGE ", rq
        config = weioConfig.getConfiguration()

        virtPath = rq['data']
        storage = os.path.dirname(virtPath)
        print 'STORAGE', storage
        path = "www/" + virtPath
        print 'STORAGE', path

        config["last_opened_project"] = path
        weioConfig.saveConfiguration(config)

        # In this way we avoid migrations between pc and weio and other archs
        if (storage != "sd" and storage != "usbFlash"):
            try:
                os.remove(path + "/www")
            except:
                print "Symlink don't exist. Will create new one for www in this project"
            os.symlink(config["absolut_root_path"] + "/www/", path + "/www")
        elif not os.path.exists(path + "/www"):
            print "COPYING TO ", path + "/www"
            copytree(config['absolut_root_path'] + "/www/",
                     path + "/www",
                     ignore=ignore_patterns('sd', 'flash', 'examples',
                                            'usbFlash'))
            print "OK"

        data = {}
        data['requested'] = rq['request']
        self.broadcast(clients, json.dumps(data))

        rqlist = ["stop", "getLastProjectName", "getUserProjetsFolderList"]

        for i in range(0, len(rqlist)):
            rq['request'] = rqlist[i]
            callbacks[rq['request']](self, rq)
Beispiel #48
0
    def createNewFile(self, rq):
        data = {}
        # this function is similar to saveFile

        # echo given request
        data['requested'] = rq['request']

        # don't echo given data to spare unnecessary communication, just return name
        f = rq['data']
        name = f['name']
        contents = f['data']

        # get configuration from file
        confFile = weioConfig.getConfiguration()
        print "WILL BE SAVED IN ", name

        if ((".html" in name) or (".py" in name) or (".json" in name)
                or (".css" in name) or (".txt" in name) or (".js" in name)
                or (".md" in name) or (".svg" in name) or (".xml" in name)
                or (".less" in name) or (".coffee" in name)
                or (".sh" in name)):

            weioFiles.saveRawContentToFile(
                confFile["last_opened_project"] + "/" + name,
                contents.encode('utf-8'))
        else:

            #decode from base64, file is binary
            bin = contents
            bin = bin.split(",")[
                1]  # split header, for example: "data:image/jpeg;base64,"
            weioFiles.saveRawContentToFile(
                confFile["last_opened_project"] + "/" + name,
                bin.decode("base64"))

        #print (pathCurrentProject+pathname)

        data['status'] = name + " has been created"
        self.broadcast(clients, json.dumps(data))
Beispiel #49
0
    def deleteCurrentProject(self, rq):
        data = {}
        data['requested'] = rq['request']

        config = weioConfig.getConfiguration()
        projectToKill = config["last_opened_project"]

        print "PROJECT TO KILL ", projectToKill

        weioFiles.removeDirectory(projectToKill)

        folders = weioFiles.listOnlyFolders("www/examples")

        if len(folders) > 0:
            config["last_opened_project"] = ""
            weioConfig.saveConfiguration(config)

            data['data'] = "reload page"
        else:
            data['data'] = "ask to create new project"

        self.broadcast(clients, json.dumps(data))
Beispiel #50
0
    def deleteCurrentProject(self, rq):
        data = {}
        data['requested'] = rq['request']

        config = weioConfig.getConfiguration()
        projectToKill = config["last_opened_project"]

        print "PROJECT TO KILL ", projectToKill

        weioFiles.removeDirectory(projectToKill)

        folders = weioFiles.listOnlyFolders("www/examples")

        if len(folders) > 0 :
         config["last_opened_project"] = ""
         weioConfig.saveConfiguration(config)

         data['data'] = "reload page"
        else :
         data['data'] = "ask to create new project"

        self.broadcast(clients, json.dumps(data))
Beispiel #51
0
    def getFileTree(self, rq):
        # get configuration from file
        config = weioConfig.getConfiguration()

        data = {}
        data['requested'] = rq['request']
        lp = config["last_opened_project"]
        if (weioFiles.checkIfDirectoryExists(lp)):
            tree = weioFiles.getFileTree(lp)
            data['data'] = tree
            #data['projectRoot'] = lp.split("/")[0]
            print "PROJECT ROOT", lp
            path = lp.split("/")
            finalPath = ""
            for p in range(len(path) - 1):
                finalPath = finalPath + path[p] + "/"
            data['projectRoot'] = finalPath
            print "PROJECT ROOT", finalPath
        else:
            data['data'] = ""
            data['projectRoot'] = ""
        # Send connection information to the client
        self.broadcast(clients, json.dumps(data))
Beispiel #52
0
    def checkForUpdates(self, rq):
        # default mode is offline
        wifiMode = "ap"
        #check hardware platform
        if (platform.machine() == 'mips') :
            # check network state, if is STA then we can check if there is Internet
            wifiMode = weioIdeGlobals.WIFI.mode
            print "WIFI MODE ", wifiMode
        else :
            # for local purposes only, testing on PC
            wifiMode = "sta" # local setting

        if (wifiMode=="sta"):
            data = {}
            # check if our server is reachable
            if (self.isConnected("www.puzzle-lab.com")):
                config = weioConfig.getConfiguration()
                repository = config["weio_update_official_repository"]

                # make request for a json file
                req = httpclient.HTTPRequest(repository)

                http_client = httpclient.AsyncHTTPClient()
                # start fetching file at the end execute checkVersion function
                http_client.fetch(req, callback=self.checkVersion)
            else :
                # not connected to the internet
                print "NO INTERNET CONNECTION"
                data['serverPush'] = "noInternetConnection"
                data['data'] = "Can't reach Internet servers"
                self.send(json.dumps(data))
        else :
            print "NO INTERNET CONNECTION"
            data['serverPush'] = "noInternetConnection"
            data['data'] = "Can't reach Internet servers"
            self.send(json.dumps(data))