Ejemplo n.º 1
0
def download_file(url, file):
    if url not in download_progress:
        download_progress[url] = {}
        download_progress[url]["status"] = "downloading"
    else:
        if download_progress[url]["status"] == "downloading":
            launcher_log.warn("url in downloading, %s", url)
            return False

    try:
        launcher_log.info("download %s to %s", url, file)
        opener = get_opener()
        req = opener.open(url)
        download_progress[url]["size"] = int(
            req.headers.get('content-length') or 0)

        CHUNK = 16 * 1024
        downloaded = 0
        with open(file, 'wb') as fp:
            while True:
                chunk = req.read(CHUNK)
                if not chunk: break
                fp.write(chunk)
                downloaded += len(chunk)
                download_progress[url]["downloaded"] = downloaded

        download_progress[url]["status"] = "finished"
        return True
    except urllib2.URLError as e:
        launcher_log.warn("download %s to %s fail:%r", url, file, e)
        return False
    except Exception as e:
        download_progress[url]["status"] = "fail"
        launcher_log.exception("download %s to %s fail:%r", url, file, e)
        return False
Ejemplo n.º 2
0
def check_update():
    try:
        update_rule = config.get(["update", "check_update"], "stable")
        if update_rule == "dont-check":
            return

        check_push_update()

        if update_rule != "stable" and update_rule != "test":
            return

        versions = update_from_github.get_github_versions()
        current_version = update_from_github.current_version()
        if update_rule == "test":
            if LooseVersion(current_version) < LooseVersion(versions[0][1]):
                launcher_log.info("update to test version %s", versions[0][1])
                update_from_github.update_version(versions[0][1])
        elif update_rule == "stable":
            if LooseVersion(current_version) < LooseVersion(versions[1][1]):
                launcher_log.info("update to stable version %s",
                                  versions[1][1])
                update_from_github.update_version(versions[1][1])
    except IOError as e:
        launcher_log.warn("check update fail:%r", e)
    except Exception as e:
        launcher_log.exception("check_update fail:%r", e)
Ejemplo n.º 3
0
    def do_POST(self):
        refer = self.headers.getheader('Referer')
        if refer:
            refer_loc = urlparse.urlparse(refer).netloc
            host = self.headers.getheader('host')
            if refer_loc != host:
                launcher_log.warn("web control ref:%s host:%s", refer_loc,
                                  host)
                return

        #url_path = urlparse.urlparse(self.path).path
        url_path_list = self.path.split('/')
        if len(url_path_list) >= 3 and url_path_list[1] == "module":
            module = url_path_list[2]
            if len(url_path_list) >= 4 and url_path_list[3] == "control":
                if module not in module_init.proc_handler:
                    launcher_log.warn("request %s no module in path",
                                      self.path)
                    self.send_not_found()
                    return

                path = '/' + '/'.join(url_path_list[4:])
                controler = module_init.proc_handler[module][
                    "imp"].local.web_control.ControlHandler(
                        self.client_address, self.headers, self.command, path,
                        self.rfile, self.wfile)
                controler.do_POST()
                return
Ejemplo n.º 4
0
def download_file(url, file):
    if url not in download_progress:
        download_progress[url] = {}
        download_progress[url]["status"] = "downloading"
    else:
        if download_progress[url]["status"] == "downloading":
            launcher_log.warn("url in downloading, %s", url)
            return False

    try:
        launcher_log.info("download %s to %s", url, file)
        opener = get_opener()
        req = opener.open(url)
        download_progress[url]["size"] = int(req.headers.get('content-length') or 0)

        CHUNK = 16 * 1024
        downloaded = 0
        with open(file, 'wb') as fp:
            while True:
                chunk = req.read(CHUNK)
                if not chunk: break
                fp.write(chunk)
                downloaded += len(chunk)
                download_progress[url]["downloaded"] = downloaded

        download_progress[url]["status"] = "finished"
        return True
    except urllib2.URLError as e:
        launcher_log.warn("download %s to %s fail:%r", url, file, e)
        return False
    except Exception as e:
        download_progress[url]["status"] = "fail"
        launcher_log.exception("download %s to %s fail:%r", url, file, e)
        return False
Ejemplo n.º 5
0
def check_update():
    try:
        update_rule = config.get(["update", "check_update"], "stable")
        if update_rule == "dont-check":
            return

        check_push_update()

        if update_rule != "stable" and update_rule != "test":
            return

        versions = update_from_github.get_github_versions()
        current_version = update_from_github.current_version()
        if update_rule == "test":
            if LooseVersion(current_version) < LooseVersion(versions[0][1]):
                launcher_log.info("update to test version %s", versions[0][1])
                update_from_github.update_version(versions[0][1])
        elif update_rule == "stable":
            if LooseVersion(current_version) < LooseVersion(versions[1][1]):
                launcher_log.info("update to stable version %s", versions[1][1])
                update_from_github.update_version(versions[1][1])
    except IOError as e:
        launcher_log.warn("check update fail:%r", e)
    except Exception as e:
        launcher_log.exception("check_update fail:%r", e)
Ejemplo n.º 6
0
    def do_POST(self):
        refer = self.headers.getheader("Referer")
        if refer:
            refer_loc = urlparse.urlparse(refer).netloc
            host = self.headers.getheader("host")
            if refer_loc != host:
                launcher_log.warn("web control ref:%s host:%s", refer_loc, host)
                return

        # url_path = urlparse.urlparse(self.path).path
        url_path_list = self.path.split("/")
        if len(url_path_list) >= 3 and url_path_list[1] == "module":
            module = url_path_list[2]
            if len(url_path_list) >= 4 and url_path_list[3] == "control":
                if module not in module_init.proc_handler:
                    launcher_log.warn("request %s no module in path", self.path)
                    self.send_not_found()
                    return

                path = "/" + "/".join(url_path_list[4:])
                controler = module_init.proc_handler[module]["imp"].local.web_control.ControlHandler(
                    self.client_address, self.headers, self.command, path, self.rfile, self.wfile
                )
                controler.do_POST()
                return
Ejemplo n.º 7
0
def save():
    global config, config_path
    try:
        json.dump(config,
                  file(config_path, "w"),
                  sort_keys=True,
                  separators=(',', ':'),
                  indent=2)
    except Exception as e:
        launcher_log.warn("save config %s fail %s", config_path, e)
Ejemplo n.º 8
0
    def do_POST(self):
        #url_path = urlparse.urlparse(self.path).path
        url_path_list = self.path.split('/')
        if len(url_path_list) >= 3 and url_path_list[1] == "module":
            module = url_path_list[2]
            if len(url_path_list) >= 4 and url_path_list[3] == "control":
                if module not in module_init.proc_handler:
                    launcher_log.warn("request %s no module in path", self.path)
                    self.send_not_found()
                    return

                path = '/' + '/'.join(url_path_list[4:])
                controler = module_init.proc_handler[module]["imp"].local.web_control.ControlHandler(self.client_address, self.headers, self.command, path, self.rfile, self.wfile)
                controler.do_POST()
                return
Ejemplo n.º 9
0
    def add(name, application):
        if not os.path.isdir(os.path.expanduser(_xdg_config_home)):
            launcher_log.warn("autorun linux config path not found:%s",
                              os.path.expanduser(_xdg_config_home))
            return

        if not os.path.isdir(_xdg_user_autostart):
            os.mkdir(_xdg_user_autostart)
        """add a new autostart entry"""
        desktop_entry = "[Desktop Entry]\n"\
            "Name=%s\n"\
            "Exec=%s\n"\
            "Type=Application\n"\
            "Terminal=false\n" % (name, application)
        with open(getfilename(name), "w") as f:
            f.write(desktop_entry)
Ejemplo n.º 10
0
    def _handle_request_noblock(self):
        try:
            request, client_address = self.get_request()
        except IOError as e:
            launcher_log.warn("socket(%s:%s) accept fail(errno: %s).", self.server_address[0], self.server_address[1], e.args[0])
            if e.args[0] == 10022:
                launcher_log.info("server %s:%d restarted.", self.server_address[0], self.server_address[1])
                self.init_socket()
            return

        if self.verify_request(request, client_address):
            try:
                self.process_request(request, client_address)
            except:
                self.handle_error(request, client_address)
                self.shutdown_request(request)
Ejemplo n.º 11
0
    def _handle_request_noblock(self):
        try:
            request, client_address = self.get_request()
        except IOError as e:
            launcher_log.warn("socket(%s:%s) accept fail(errno: %s).", self.server_address[0], self.server_address[1], e.args[0])
            if e.args[0] == 10022:
                launcher_log.info("server %s:%d restarted.", self.server_address[0], self.server_address[1])
                self.init_socket()
            return

        if self.verify_request(request, client_address):
            try:
                self.process_request(request, client_address)
            except:
                self.handle_error(request, client_address)
                self.shutdown_request(request)
Ejemplo n.º 12
0
    def add(name, application):
        if not os.path.isdir(os.path.expanduser(_xdg_config_home)):
            launcher_log.warn("autorun linux config path not found:%s", os.path.expanduser(_xdg_config_home))
            return

        if not os.path.isdir(_xdg_user_autostart):
            os.mkdir(_xdg_user_autostart)

        """add a new autostart entry"""
        desktop_entry = "[Desktop Entry]\n"\
            "Name=%s\n"\
            "Exec=%s\n"\
            "Type=Application\n"\
            "Terminal=false\n" % (name, application)
        with open(getfilename(name), "w") as f:
            f.write(desktop_entry)
Ejemplo n.º 13
0
def install_module(module, new_version):
    import module_init
    import os, subprocess, sys

    current_path = os.path.dirname(os.path.abspath(__file__))
    new_module_version_path = os.path.abspath(
        os.path.join(current_path, os.pardir, os.pardir, module, new_version))

    #check path exist
    if not os.path.isdir(new_module_version_path):
        launcher_log.error("install module %s dir %s not exist", module,
                           new_module_version_path)
        return

    #call setup.py
    setup_script = os.path.join(new_module_version_path, "setup.py")
    if not os.path.isfile(setup_script):
        launcher_log.warn("update %s fail. setup script %s not exist", module,
                          setup_script)
        return

    config.set(["modules", module, "current_version"], str(new_version))
    config.save()

    if module == "launcher":
        module_init.stop_all()
        import web_control
        web_control.stop()

        subprocess.Popen([sys.executable, setup_script], shell=False)

        os._exit(0)

    else:
        launcher_log.info("Setup %s version %s ...", module, new_version)
        try:
            module_init.stop(module)

            subprocess.call([sys.executable, setup_script], shell=False)
            launcher_log.info("Finished new version setup.")

            launcher_log.info("Restarting new version ...")
            module_init.start(module)
        except Exception as e:
            launcher_log.error("install module %s %s fail:%s", module,
                               new_version, e)
Ejemplo n.º 14
0
def start(module):
    if not os.path.isdir(os.path.join(root_path, module)):
        return

    try:
        if module not in config.config["modules"]:
            launcher_log.error("module not exist %s", module)
            raise

        if module in proc_handler:
            launcher_log.error("module %s is running", module)
            return "module is running"

        if module not in proc_handler:
            proc_handler[module] = {}

        if os.path.isfile(os.path.join(root_path, module, "__init__.py")):
            if "imp" not in proc_handler[module]:
                proc_handler[module]["imp"] = __import__(
                    module, globals(), locals(), ['local', 'start'], -1)

            _start = proc_handler[module]["imp"].start
            p = threading.Thread(target=_start.main)
            p.daemon = True
            p.start()
            proc_handler[module]["proc"] = p

            while not _start.client.ready:
                time.sleep(0.1)
        else:
            script_path = os.path.join(root_path, module, 'start.py')
            if not os.path.isfile(script_path):
                launcher_log.warn("start module script not exist:%s",
                                  script_path)
                return "fail"

            proc_handler[module]["proc"] = subprocess.Popen(
                [sys.executable, script_path], shell=False)

        launcher_log.info("%s started", module)

    except Exception as e:
        launcher_log.exception("start module %s fail:%s", module, e)
        return "Except:%s" % e
    return "start success."
Ejemplo n.º 15
0
def install_module(module, new_version):
    import module_init
    import os, subprocess, sys

    current_path = os.path.dirname(os.path.abspath(__file__))
    new_module_version_path = os.path.abspath( os.path.join(current_path, os.pardir, os.pardir, module, new_version))

    #check path exist
    if not os.path.isdir(new_module_version_path):
        launcher_log.error("install module %s dir %s not exist", module, new_module_version_path)
        return

    #call setup.py
    setup_script = os.path.join(new_module_version_path, "setup.py")
    if not os.path.isfile(setup_script):
        launcher_log.warn("update %s fail. setup script %s not exist", module, setup_script)
        return


    config.set(["modules", module, "current_version"], str(new_version))
    config.save()

    if module == "launcher":
        module_init.stop_all()
        import web_control
        web_control.stop()


        subprocess.Popen([sys.executable, setup_script], shell=False)

        os._exit(0)

    else:
        launcher_log.info("Setup %s version %s ...", module, new_version)
        try:
            module_init.stop(module)

            subprocess.call([sys.executable, setup_script], shell=False)
            launcher_log.info("Finished new version setup.")

            launcher_log.info("Restarting new version ...")
            module_init.start(module)
        except Exception as e:
            launcher_log.error("install module %s %s fail:%s", module, new_version, e)
Ejemplo n.º 16
0
def start(module):
    if not os.path.isdir(os.path.join(root_path, module)):
        return

    try:
        if not module in config.config["modules"]:
            launcher_log.error("module not exist %s", module)
            raise

        if module in proc_handler:
            launcher_log.error("module %s is running", module)
            return "module is running"

        if module not in proc_handler:
            proc_handler[module] = {}

        if os.path.isfile(os.path.join(root_path, module, "__init__.py")):
            if "imp" not in proc_handler[module]:
                proc_handler[module]["imp"] = __import__(module, globals(), locals(), ['local', 'start'], -1)

            _start = proc_handler[module]["imp"].start
            p = threading.Thread(target = _start.main)
            p.daemon = True
            p.start()
            proc_handler[module]["proc"] = p

            while not _start.client.ready:
                time.sleep(0.1)
        else:
            script_path = os.path.join(root_path, module, 'start.py')
            if not os.path.isfile(script_path):
                launcher_log.warn("start module script not exist:%s", script_path)
                return "fail"

            proc_handler[module]["proc"] = subprocess.Popen([sys.executable, script_path], shell=False)


        launcher_log.info("%s started", module)

    except Exception as e:
        launcher_log.exception("start module %s fail:%s", module, e)
        return "Except:%s" % e
    return "start success."
Ejemplo n.º 17
0
    current_path = os.path.dirname(os.path.abspath(__file__))
    python_path = os.path.abspath(
        os.path.join(current_path, os.pardir, 'python27', '1.0'))
    noarch_lib = os.path.abspath(os.path.join(python_path, 'lib', 'noarch'))
    sys.path.append(noarch_lib)

pygtk.require('2.0')
import gtk

gtk.gdk.threads_init()

try:
    import pynotify
    pynotify.init('XX-Net Notify')
except:
    launcher_log.warn(
        "import pynotify fail, please install python-notify if possiable.")
    pynotify = None

import module_init


class Gtk_tray():
    notify_list = []

    def __init__(self):
        logo_filename = os.path.join(
            os.path.abspath(os.path.dirname(__file__)), 'web_ui',
            'favicon.ico')

        self.trayicon = gtk.StatusIcon()
        self.trayicon.set_from_file(logo_filename)
Ejemplo n.º 18
0
    def do_GET(self):
        try:
            refer = self.headers.getheader('Referer')
            netloc = urlparse.urlparse(refer).netloc
            if not netloc.startswith("127.0.0.1") and not netloc.startswitch("localhost"):
                launcher_log.warn("web control ref:%s refuse", netloc)
                return
        except:
            pass

        # check for '..', which will leak file
        if re.search(r'(\.{2})', self.path) is not None:
            self.wfile.write(b'HTTP/1.1 404\r\n\r\n')
            launcher_log.warn('%s %s %s haking', self.address_string(), self.command, self.path )
            return

        url_path = urlparse.urlparse(self.path).path
        if url_path == '/':
            return self.req_index_handler()

        url_path_list = self.path.split('/')
        if len(url_path_list) >= 3 and url_path_list[1] == "module":
            module = url_path_list[2]
            if len(url_path_list) >= 4 and url_path_list[3] == "control":
                if module not in module_init.proc_handler:
                    launcher_log.warn("request %s no module in path", url_path)
                    self.send_not_found()
                    return

                path = '/' + '/'.join(url_path_list[4:])
                controler = module_init.proc_handler[module]["imp"].local.web_control.ControlHandler(self.client_address, self.headers, self.command, path, self.rfile, self.wfile)
                controler.do_GET()
                return
            else:
                file_path = os.path.join(root_path, module, url_path_list[3:].join('/'))
        else:
            file_path = os.path.join(current_path, 'web_ui' + url_path)


        launcher_log.debug ('launcher web_control %s %s %s ', self.address_string(), self.command, self.path)
        if os.path.isfile(file_path):
            if file_path.endswith('.js'):
                mimetype = 'application/javascript'
            elif file_path.endswith('.css'):
                mimetype = 'text/css'
            elif file_path.endswith('.html'):
                mimetype = 'text/html'
            elif file_path.endswith('.jpg'):
                mimetype = 'image/jpeg'
            elif file_path.endswith('.png'):
                mimetype = 'image/png'
            else:
                mimetype = 'text/plain'


            self.send_file(file_path, mimetype)
        elif url_path == '/config':
            self.req_config_handler()
        elif url_path == '/download':
            self.req_download_handler()
        elif url_path == '/init_module':
            self.req_init_module_handler()
        elif url_path == '/quit':
            self.send_response('text/html', '{"status":"success"}')
            module_init.stop_all()
            os._exit(0)
        elif url_path == '/restart':
            self.send_response('text/html', '{"status":"success"}')
            update_from_github.restart_xxnet()
        else:
            self.wfile.write(b'HTTP/1.1 404\r\nContent-Type: text/plain\r\nConnection: close\r\n\r\n404 Not Found')
            launcher_log.info('%s "%s %s HTTP/1.1" 404 -', self.address_string(), self.command, self.path)
Ejemplo n.º 19
0
if __name__ == "__main__":
    import os, sys
    current_path = os.path.dirname(os.path.abspath(__file__))
    python_path = os.path.abspath( os.path.join(current_path, os.pardir, 'python27', '1.0'))
    noarch_lib = os.path.abspath( os.path.join(python_path, 'lib', 'noarch'))
    sys.path.append(noarch_lib)

pygtk.require('2.0')
import gtk
gtk.gdk.threads_init()

try:
    import pynotify
    pynotify.init('XX-Net Notify')
except:
    launcher_log.warn("import pynotify fail, please install python-notify if possiable.")
    pynotify = None

import module_init

class Gtk_tray():
    notify_list = []
    def __init__(self):
        logo_filename = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'web_ui', 'favicon.ico')

        self.trayicon = gtk.StatusIcon()
        self.trayicon.set_from_file(logo_filename)

        self.trayicon.connect('popup-menu', lambda i, b, t: self.make_menu().popup(None, None, gtk.status_icon_position_menu, b, t, self.trayicon))
        self.trayicon.connect('activate', self.show_control_web)
        self.trayicon.set_tooltip('XX-Net')
Ejemplo n.º 20
0
    def do_GET(self):
        refer = self.headers.getheader('Referer')
        if refer:
            refer_loc = urlparse.urlparse(refer).netloc
            host = self.headers.getheader('host')
            if refer_loc != host:
                launcher_log.warn("web control ref:%s host:%s", refer_loc,
                                  host)
                return

        # check for '..', which will leak file
        if re.search(r'(\.{2})', self.path) is not None:
            self.wfile.write(b'HTTP/1.1 404\r\n\r\n')
            launcher_log.warn('%s %s %s haking', self.address_string(),
                              self.command, self.path)
            return

        url_path = urlparse.urlparse(self.path).path
        if url_path == '/':
            return self.req_index_handler()

        url_path_list = self.path.split('/')
        if len(url_path_list) >= 3 and url_path_list[1] == "module":
            module = url_path_list[2]
            if len(url_path_list) >= 4 and url_path_list[3] == "control":
                if module not in module_init.proc_handler:
                    launcher_log.warn("request %s no module in path", url_path)
                    self.send_not_found()
                    return

                if "imp" not in module_init.proc_handler[module]:
                    launcher_log.warn("request module:%s start fail", module)
                    self.send_not_found()
                    return

                path = '/' + '/'.join(url_path_list[4:])
                controler = module_init.proc_handler[module][
                    "imp"].local.web_control.ControlHandler(
                        self.client_address, self.headers, self.command, path,
                        self.rfile, self.wfile)
                controler.do_GET()
                return
            else:
                file_path = os.path.join(root_path, module,
                                         url_path_list[3:].join('/'))
        else:
            file_path = os.path.join(current_path, 'web_ui' + url_path)

        launcher_log.debug('launcher web_control %s %s %s ',
                           self.address_string(), self.command, self.path)
        if os.path.isfile(file_path):
            if file_path.endswith('.js'):
                mimetype = 'application/javascript'
            elif file_path.endswith('.css'):
                mimetype = 'text/css'
            elif file_path.endswith('.html'):
                mimetype = 'text/html'
            elif file_path.endswith('.jpg'):
                mimetype = 'image/jpeg'
            elif file_path.endswith('.png'):
                mimetype = 'image/png'
            else:
                mimetype = 'text/plain'

            self.send_file(file_path, mimetype)
        elif url_path == '/config':
            self.req_config_handler()
        elif url_path == '/download':
            self.req_download_handler()
        elif url_path == '/init_module':
            self.req_init_module_handler()
        elif url_path == '/quit':
            self.send_response('text/html', '{"status":"success"}')
            module_init.stop_all()
            os._exit(0)
        elif url_path == '/restart':
            self.send_response('text/html', '{"status":"success"}')
            update_from_github.restart_xxnet()
        else:
            self.wfile.write(
                b'HTTP/1.1 404\r\nContent-Type: text/plain\r\nConnection: close\r\n\r\n404 Not Found'
            )
            launcher_log.info('%s "%s %s HTTP/1.1" 404 -',
                              self.address_string(), self.command, self.path)
Ejemplo n.º 21
0
def save():
    global config, config_path
    try:
        yaml.dump(config, file(config_path, "w"))
    except Exception as e:
        launcher_log.warn("save config %s fail %s", config_path, e)
Ejemplo n.º 22
0
def save():
    global config, config_path
    try:
        yaml.dump(config, file(config_path, "w"))
    except Exception as e:
        launcher_log.warn("save config %s fail %s", config_path, e)
Ejemplo n.º 23
0
    def do_GET(self):
        refer = self.headers.getheader("Referer")
        if refer:
            refer_loc = urlparse.urlparse(refer).netloc
            host = self.headers.getheader("host")
            if refer_loc != host:
                launcher_log.warn("web control ref:%s host:%s", refer_loc, host)
                return

        # check for '..', which will leak file
        if re.search(r"(\.{2})", self.path) is not None:
            self.wfile.write(b"HTTP/1.1 404\r\n\r\n")
            launcher_log.warn("%s %s %s haking", self.address_string(), self.command, self.path)
            return

        url_path = urlparse.urlparse(self.path).path
        if url_path == "/":
            return self.req_index_handler()

        url_path_list = self.path.split("/")
        if len(url_path_list) >= 3 and url_path_list[1] == "module":
            module = url_path_list[2]
            if len(url_path_list) >= 4 and url_path_list[3] == "control":
                if module not in module_init.proc_handler:
                    launcher_log.warn("request %s no module in path", url_path)
                    self.send_not_found()
                    return

                if "imp" not in module_init.proc_handler[module]:
                    launcher_log.warn("request module:%s start fail", module)
                    self.send_not_found()
                    return

                path = "/" + "/".join(url_path_list[4:])
                controler = module_init.proc_handler[module]["imp"].local.web_control.ControlHandler(
                    self.client_address, self.headers, self.command, path, self.rfile, self.wfile
                )
                controler.do_GET()
                return
            else:
                file_path = os.path.join(root_path, module, url_path_list[3:].join("/"))
        else:
            file_path = os.path.join(current_path, "web_ui" + url_path)

        launcher_log.debug("launcher web_control %s %s %s ", self.address_string(), self.command, self.path)
        if os.path.isfile(file_path):
            if file_path.endswith(".js"):
                mimetype = "application/javascript"
            elif file_path.endswith(".css"):
                mimetype = "text/css"
            elif file_path.endswith(".html"):
                mimetype = "text/html"
            elif file_path.endswith(".jpg"):
                mimetype = "image/jpeg"
            elif file_path.endswith(".png"):
                mimetype = "image/png"
            else:
                mimetype = "text/plain"

            self.send_file(file_path, mimetype)
        elif url_path == "/config":
            self.req_config_handler()
        elif url_path == "/download":
            self.req_download_handler()
        elif url_path == "/init_module":
            self.req_init_module_handler()
        elif url_path == "/quit":
            self.send_response("text/html", '{"status":"success"}')
            module_init.stop_all()
            os._exit(0)
        elif url_path == "/restart":
            self.send_response("text/html", '{"status":"success"}')
            update_from_github.restart_xxnet()
        else:
            self.wfile.write(b"HTTP/1.1 404\r\nContent-Type: text/plain\r\nConnection: close\r\n\r\n404 Not Found")
            launcher_log.info('%s "%s %s HTTP/1.1" 404 -', self.address_string(), self.command, self.path)
Ejemplo n.º 24
0
def download_module(module, new_version):
    import os
    global update_content, update_dict

    current_path = os.path.dirname(os.path.abspath(__file__))
    download_path = os.path.abspath(
        os.path.join(current_path, os.pardir, os.pardir, 'data', 'downloads'))
    if not os.path.isdir(download_path):
        os.mkdir(download_path)

    try:
        for source in update_dict["modules"][module]["versions"][new_version][
                "sources"]:
            url = source["url"]
            filename = module + "-" + new_version + ".zip"

            file_path = os.path.join(download_path, filename)

            if os.path.isfile(file_path) and sha1_file(
                    file_path) == update_dict["modules"][module]["versions"][
                        new_version]["sha1"]:
                pass
            elif not download_file(url, file_path):
                launcher_log.warn("download %s fail", url)
                continue

            sha1 = sha1_file(file_path)
            if update_dict["modules"][module]["versions"][new_version][
                    "sha1"] != sha1:
                launcher_log.warn("download %s sha1 wrong", url)
                continue

            module_path = os.path.abspath(
                os.path.join(current_path, os.pardir, os.pardir, module))
            if not os.path.isdir(module_path):
                os.path.mkdir(module_path, "755")

            version_path = os.path.join(module_path, new_version)
            if os.path.isdir(version_path):
                launcher_log.error("module dir exist:%s, download exist.",
                                   version_path)
                return

            with zipfile.ZipFile(file_path, "r") as dz:
                dz.extractall(module_path)
                dz.close()

            import shutil
            unzip_path = os.path.abspath(
                os.path.join(module_path, module + "-" + new_version))
            tag_path = os.path.abspath(os.path.join(module_path, new_version))
            shutil.move(unzip_path, tag_path)

            msg = "Module %s new version %s downloaded, Install?" % (
                module, new_version)
            if sys.platform == "linux" or sys.platform == "linux2":
                from gtk_tray import sys_tray
                data_install = "%s|%s|install" % (module, new_version)
                data_ignore = "%s|%s|ignore" % (module, new_version)
                buttons = {
                    1: {
                        "data": data_install,
                        "label": "Install",
                        'callback': general_gtk_callback
                    },
                    2: {
                        "data": data_ignore,
                        "label": "Ignore",
                        'callback': general_gtk_callback
                    }
                }
                sys_tray.notify_general(msg=msg,
                                        title="Install",
                                        buttons=buttons)
            elif sys.platform == "win32":
                from win_tray import sys_tray
                if sys_tray.dialog_yes_no(msg, u"Install", None, None) == 1:
                    install_module(module, new_version)
                else:
                    ignore_module(module, new_version)
            elif sys.platform == "darwin":
                from mac_tray import sys_tray
                if sys_tray.dialog_yes_no(msg, u"Install", None, None) == 1:
                    install_module(module, new_version)
                else:
                    ignore_module(module, new_version)

            else:
                install_module(module, new_version)

            break

    except Exception as e:
        launcher_log.warn("get gae_proxy source fail, content:%s err:%s",
                          update_content, e)
Ejemplo n.º 25
0
def check_push_update():
    global update_content, update_dict
    try:
        opener = get_opener()

        req_url = update_url + "?uuid=" + get_uuid() + "&version=" + update_from_github.current_version()
        try:
            update_content = opener.open(req_url).read()
        except Exception as e:
            launcher_log.warn("check_update fail:%r", e)
            return False

        update_dict = json.loads(update_content)
        return True

        for module in update_dict["modules"]:
            new_version = str(update_dict["modules"][module]["last_version"])
            describe = update_dict["modules"][module]["versions"][new_version]["describe"]

            if update_dict["modules"][module]["versions"][new_version]["notify"] != "true":
                continue

            if not module in config.config["modules"]:
                ignore_version = 0
                current_version = 0
                config.config["modules"][module] = {}
                config.config["modules"][module]["current_version"] = '0.0.0'
            else:
                current_version = config.get(["modules", module, "current_version"])
                if "ignore_version" in config.config["modules"][module]:
                    ignore_version = config.config["modules"][module]["ignore_version"]
                else:
                    ignore_version = current_version

            if version_to_bin(new_version) <= version_to_bin(ignore_version):
                continue

            if version_to_bin(new_version) > version_to_bin(current_version):
                launcher_log.info("new %s version:%s", module, new_version)


                if sys.platform == "linux" or sys.platform == "linux2":
                    from gtk_tray import sys_tray
                    msg = "Module %s new version: %s, Download?\nNew:%s" % (module,  new_version, describe)
                    data_download = "%s|%s|download" % (module, new_version)
                    data_ignore = "%s|%s|ignore" % (module, new_version)
                    buttons = {1: {"data":data_download, "label":"Download", 'callback':general_gtk_callback},
                               2: {"data":data_ignore, "label":"Ignore", 'callback':general_gtk_callback}}
                    sys_tray.notify_general(msg=msg, title="New Version", buttons=buttons)
                elif sys.platform == "win32":
                    from win_tray import sys_tray
                    msg = "Module %s new version: %s, Download?" % (module,  new_version)
                    if sys_tray.dialog_yes_no(msg, u"Download", None, None) == 1:
                        download_module(module, new_version)
                    else:
                        ignore_module(module, new_version)
                elif sys.platform == "darwin":
                    from mac_tray import sys_tray
                    msg = "Module %s new version: %s, Download?" % (module,  new_version)
                    if sys_tray.dialog_yes_no(msg, u"Download", None, None) == 1:
                        download_module(module, new_version)
                    else:
                        ignore_module(module, new_version)

                else:
                    download_module(module, new_version)

    except Exception as e:
        launcher_log.exception("check_update except:%s", e)
        return
Ejemplo n.º 26
0
def check_push_update():
    global update_content, update_dict
    try:
        opener = get_opener()

        req_url = update_url + "?uuid=" + get_uuid(
        ) + "&version=" + update_from_github.current_version()
        try:
            update_content = opener.open(req_url).read()
        except Exception as e:
            launcher_log.warn("check_update fail:%r", e)
            return False

        update_dict = json.loads(update_content)
        return True

        for module in update_dict["modules"]:
            new_version = str(update_dict["modules"][module]["last_version"])
            describe = update_dict["modules"][module]["versions"][new_version][
                "describe"]

            if update_dict["modules"][module]["versions"][new_version][
                    "notify"] != "true":
                continue

            if not module in config.config["modules"]:
                ignore_version = 0
                current_version = 0
                config.config["modules"][module] = {}
                config.config["modules"][module]["current_version"] = '0.0.0'
            else:
                current_version = config.get(
                    ["modules", module, "current_version"])
                if "ignore_version" in config.config["modules"][module]:
                    ignore_version = config.config["modules"][module][
                        "ignore_version"]
                else:
                    ignore_version = current_version

            if version_to_bin(new_version) <= version_to_bin(ignore_version):
                continue

            if version_to_bin(new_version) > version_to_bin(current_version):
                launcher_log.info("new %s version:%s", module, new_version)

                if sys.platform == "linux" or sys.platform == "linux2":
                    from gtk_tray import sys_tray
                    msg = "Module %s new version: %s, Download?\nNew:%s" % (
                        module, new_version, describe)
                    data_download = "%s|%s|download" % (module, new_version)
                    data_ignore = "%s|%s|ignore" % (module, new_version)
                    buttons = {
                        1: {
                            "data": data_download,
                            "label": "Download",
                            'callback': general_gtk_callback
                        },
                        2: {
                            "data": data_ignore,
                            "label": "Ignore",
                            'callback': general_gtk_callback
                        }
                    }
                    sys_tray.notify_general(msg=msg,
                                            title="New Version",
                                            buttons=buttons)
                elif sys.platform == "win32":
                    from win_tray import sys_tray
                    msg = "Module %s new version: %s, Download?" % (
                        module, new_version)
                    if sys_tray.dialog_yes_no(msg, u"Download", None,
                                              None) == 1:
                        download_module(module, new_version)
                    else:
                        ignore_module(module, new_version)
                elif sys.platform == "darwin":
                    from mac_tray import sys_tray
                    msg = "Module %s new version: %s, Download?" % (
                        module, new_version)
                    if sys_tray.dialog_yes_no(msg, u"Download", None,
                                              None) == 1:
                        download_module(module, new_version)
                    else:
                        ignore_module(module, new_version)

                else:
                    download_module(module, new_version)

    except Exception as e:
        launcher_log.exception("check_update except:%s", e)
        return
Ejemplo n.º 27
0
def download_module(module, new_version):
    import os
    global update_content, update_dict

    current_path = os.path.dirname(os.path.abspath(__file__))
    download_path = os.path.abspath( os.path.join(current_path, os.pardir, os.pardir, 'data', 'downloads'))
    if not os.path.isdir(download_path):
        os.mkdir(download_path)

    try:
        for source in update_dict["modules"][module]["versions"][new_version]["sources"]:
            url = source["url"]
            filename = module + "-" + new_version + ".zip"



            file_path = os.path.join(download_path, filename)

            if os.path.isfile(file_path) and sha1_file(file_path) == update_dict["modules"][module]["versions"][new_version]["sha1"]:
                pass
            elif not download_file(url, file_path):
                launcher_log.warn("download %s fail", url)
                continue

            sha1 = sha1_file(file_path)
            if update_dict["modules"][module]["versions"][new_version]["sha1"] != sha1:
                launcher_log.warn("download %s sha1 wrong", url)
                continue

            module_path = os.path.abspath( os.path.join(current_path, os.pardir, os.pardir, module))
            if not os.path.isdir(module_path):
                os.path.mkdir(module_path, "755")

            version_path = os.path.join(module_path, new_version)
            if os.path.isdir(version_path):
                launcher_log.error("module dir exist:%s, download exist.", version_path)
                return

            with zipfile.ZipFile(file_path, "r") as dz:
                dz.extractall(module_path)
                dz.close()

            import shutil
            unzip_path = os.path.abspath(os.path.join(module_path, module + "-" + new_version))
            tag_path = os.path.abspath(os.path.join(module_path, new_version))
            shutil.move(unzip_path, tag_path)

            msg = "Module %s new version %s downloaded, Install?" % (module,  new_version)
            if sys.platform == "linux" or sys.platform == "linux2":
                from gtk_tray import sys_tray
                data_install = "%s|%s|install" % (module, new_version)
                data_ignore = "%s|%s|ignore" % (module, new_version)
                buttons = {1: {"data":data_install, "label":"Install", 'callback':general_gtk_callback},
                           2: {"data":data_ignore, "label":"Ignore", 'callback':general_gtk_callback}}
                sys_tray.notify_general(msg=msg, title="Install", buttons=buttons)
            elif sys.platform == "win32":
                from win_tray import sys_tray
                if sys_tray.dialog_yes_no(msg, u"Install", None, None) == 1:
                    install_module(module, new_version)
                else:
                    ignore_module(module, new_version)
            elif sys.platform == "darwin":
                from  mac_tray import sys_tray
                if sys_tray.dialog_yes_no(msg, u"Install", None, None) == 1:
                    install_module(module, new_version)
                else:
                    ignore_module(module, new_version)

            else:
                install_module(module, new_version)

            break

    except Exception as e:
        launcher_log.warn("get gae_proxy source fail, content:%s err:%s", update_content, e)