def check_version():
    try:
        if os.path.isfile(globals.INSTALL_DIRECTORY +
                          globals.CLIENT_VERSION_FILE):
            debug.info("Found client version file in " +
                       globals.INSTALL_DIRECTORY)
            with open(globals.INSTALL_DIRECTORY +
                      globals.CLIENT_VERSION_FILE) as current_version_file:
                globals.CLIENT_VERSION = current_version_file.read().replace(
                    "\n", "")
            current_version_file.close()
            debug.info("Contents of client version file: " +
                       globals.CLIENT_VERSION)

        filehandler.download(
            globals.CLIENT_DOWNLOAD_URL + globals.CLIENT_VERSION_FILE,
            globals.CLIENT_VERSION_FILE)
        debug.info("Saved client version file to ./" +
                   globals.CLIENT_VERSION_FILE)
        with open(globals.CLIENT_VERSION_FILE, "r") as online_version_file:
            globals.ONLINE_CLIENT_VERSION = online_version_file.read().replace(
                "\n", "")

        debug.info("Current client version: " + globals.CLIENT_VERSION)
        debug.info("Latest client version: " + globals.ONLINE_CLIENT_VERSION)
        if globals.CLIENT_VERSION == globals.ONLINE_CLIENT_VERSION:
            debug.success("Your client is up to date!")
            os.remove(globals.CLIENT_VERSION_FILE)
            debug.terminate()

        if os.path.isfile(globals.INSTALL_DIRECTORY +
                          globals.CLIENT_VERSION_FILE):
            debug.info("Deleting old version data..")
            os.remove(globals.INSTALL_DIRECTORY + globals.CLIENT_VERSION_FILE)

        debug.success("Deleted old version data!")
        debug.info("Installing new version data..")
        shutil.move(globals.CLIENT_VERSION_FILE,
                    globals.INSTALL_DIRECTORY + globals.CLIENT_VERSION_FILE)
        return os.path.isfile(globals.INSTALL_DIRECTORY +
                              globals.CLIENT_VERSION_FILE)
    except (OSError, URLError) as e:
        debug.error(
            "There was an error while checking the version of your client:")
        print(e)
        return False
Esempio n. 2
0
 def update_sections():
     if (
             not keeper["updated"]
     ):  # this to prevent redundant multiple download. TODO disable the button instead
         link = GITHUB_PATTERN_DEFAULT.format(DEFAULT_REPO, pkg_path)
         filehandler.download(cached_pkg_path,
                              link,
                              stream=False,
                              outstream=outstream)
         keeper["updated"] = True
     else:
         return
     sections = read_sections_from_pkg(cached_pkg_path)
     keeper["adtframe"].destroy()
     keeper["adtframe"] = adtframe = treeview_frame(window,
                                                    sections,
                                                    additional_set,
                                                    cache_obj=cache_obj,
                                                    outstream=outstream)
     adtframe.grid(column=0, row=2, columnspan=2)
def check_console_updates():
    try:
        filehandler.download(
            globals.CONSOLE_DOWNLOAD_URL + globals.CONSOLE_VERSION_FILE,
            globals.APPLICATION_PATH + globals.CONSOLE_VERSION_FILE)
        with open(globals.APPLICATION_PATH +
                  globals.CONSOLE_VERSION_FILE) as console_file:
            online_console_version = console_file.read().replace("\n", "")
        if online_console_version == "":
            online_console_version = "0.0.0"

        os.remove(globals.APPLICATION_PATH + globals.CONSOLE_VERSION_FILE)
        if online_console_version == globals.CONSOLE_VERSION:
            return False
        else:
            debug.info("New updater version available!")
            debug.info("Version available: V" + online_console_version)
            return True
    except (IOError, URLError) as e:
        debug.error("There was an error while trying to receive version data.")
        print(e)
        debug.error("Terminating updater launch.")
        return False
def update_console():
    debug.info("Saving current updater files..")
    try:
        os.rename(
            globals.APPLICATION_PATH +
            globals.MAIN_EXECUTABLE[globals.OPERATING_SYSTEM],
            globals.APPLICATION_PATH +
            globals.BACKUP_EXECUTABLE[globals.OPERATING_SYSTEM])
        debug.success("Successfully saved updater files!")
        debug.info("Downloading new updater files.")

        debug.info("This may take a minute.")
        if filehandler.download(
                globals.CONSOLE_DOWNLOAD_URL + globals.OPERATING_SYSTEM + "/" +
                globals.MAIN_EXECUTABLE[globals.OPERATING_SYSTEM],
                globals.APPLICATION_PATH +
                globals.MAIN_EXECUTABLE[globals.OPERATING_SYSTEM]):
            debug.success("Downloaded updater files.")
        else:
            debug.error("Failed to download new updater files.")
            debug.error("Ending the update process.")
            debug.terminate()

        if globals.OPERATING_SYSTEM == "Linux" or globals.OPERATING_SYSTEM == "Darwin":
            debug.info("Applying file permissions..")
            os.system("sudo chmod +x " + globals.APPLICATION_PATH + "main")

        debug.success("Update completed!")
        debug.terminate()
    except URLError as e:
        debug.error("Failed to download new updater files.")
        print(e)
        debug.info("Loading saved files.")
        os.rename(globals.APPLICATION_PATH + globals.BACKUP_EXECUTABLE,
                  globals.APPLICATION_PATH + globals.MAIN_EXECUTABLE)
        debug.success("Loaded saved files!")
        debug.success("Ending update process.")
        debug.terminate()
    except OSError as e:
        debug.error("The updater encountered an error:")
        print(e)
        debug.error("Terminating update.")
        debug.terminate()
Esempio n. 5
0
import os, filehandler, analyze, plotting
import pandas as pd
from random import choice, randint

# Define filename and url for the dataset
fname = "movies.csv"
url = "https://raw.githubusercontent.com/MikkelHansen95/dataset/master/movies_metadata.csv"

# Download required files/datasets
if not os.path.isfile(fname):
    filehandler.download(url, fname)

# Read the dataset and remove untitled entries
dataframe = pd.read_csv(fname, dtype='unicode', low_memory=False)
dataframe = dataframe[dataframe['title'].notnull()]

# Using 'analyze' retrieve portions of the needed data
adult = analyze.rated_adult(dataframe)
animation = analyze.genre(dataframe, 'Animation')['title']
budget = analyze.budget(dataframe)['title']

#ploting the numbers of movies from a releasedate
plot1 = plotting.releasedate_number(dataframe)
plot1 = plot1.get_figure()

#ploting the runtime as x and date as y
plot2 = plotting.runtime_releasedate(dataframe)
plot2 = plot2.get_figure()

#plotting Revenue, Budget and Buzzword Count as X, Y, X in 3D plot
plot3 = plotting.three_d_plot(dataframe)
Esempio n. 6
0
def install(directoryvar,
            download_set,
            cache_obj,
            cache_obj_path=cache.DEFAULT_CACHE,
            cache_loc=cache.DEFAULT_CACHE_LOC,
            progressbar=None,
            progress_labelvar=None,
            finish_trigger_fn=None,
            credit_path=None,
            wait=1.0,
            outstream=sys.stdout):
    # check the directory again for good measure
    directory = directoryvar.get()
    if (not check_location(directoryvar, outstream=outstream)):
        messagebox.showerror(
            title="Wrong directory",
            message=
            "Directory {:s} is not a valid WOT instance. Try again. The directory to be used is one where you can see WorldOfTank.exe in the files."
            .format(directory))
        if (progressbar or progress_labelvar
            ):  # if wrong directory, immediately enable exit
            progress_labelvar.set(
                "Error found. Exit, and try again or check your version.")
            finish_trigger_fn(False)
        return
    # make certain cache_loc
    if (isinstance(cache_loc, tk.StringVar)):
        cache_loc = cache_loc.get()
    # progressbar, progress label and finish trigger is checked
    start = time.time()
    #if(progressbar):
    #progressbar.start(100) # 100ms interval
    # step_size = 400 / (len(download_set) + 1)

    session = requests.Session()
    # Download and extract the UML base to correct location (res_mod/vernumber/)
    resmod_folder = os.path.join(directory, "res_mods")
    subfolders = [
        os.path.basename(os.path.normpath(f.path))
        for f in os.scandir(resmod_folder) if f.is_dir()
    ]
    valid = sorted(
        [pth for pth in subfolders if all(c in "1234567890." for c in pth)],
        key=lambda x: version.parse(x),
        reverse=True)  # hack to search for game version
    if (len(valid) > 1):
        outstream.write(
            "Multiple game versions found, using the highest({:s} in {})\n".
            format(valid[0], valid))
    elif (len(valid) == 0):
        messagebox.showerror(
            title="No version available",
            message=
            "There is no version detected in the resmod folder (list of folder found: {}). Try to play a battle or something, I dunno."
            .format(subfolders))
        return
    # correct location to install, correct cache zip file
    UML_loc = os.path.join(resmod_folder, valid[0])
    uml_filepath = os.path.join(cache_loc, "src.zip")
    if (progress_labelvar):
        progress_labelvar.set("Downloading and extracting main UML file...")
    if (cache_obj.get("use_drive_UML", 0) == 1):  # Use inbuilt drive file
        filehandler.download(uml_filepath,
                             DRIVE_FILE_LOCATION,
                             progressbar=progressbar,
                             session=session)
    else:  # use the github file
        filehandler.download(uml_filepath,
                             GITHUB_PATTERN_DEFAULT.format(
                                 DEFAULT_REPO, "src.zip"),
                             progressbar=progressbar)
    filehandler.extractZip(uml_filepath, UML_loc)  # extract the file to resmod
    # delete the file after extraction. This prevent updates from being blocked by previous cached UML package
    # not needed this time as we check filesize
    # os.remove(uml_filepath)
    outstream.write("Base UML installed to {:s}\n".format(UML_loc))

    # if selected, attempt to find and copy old ownModel.xml from other valid directoryvar
    copy_ownModel, symlink_ownModel = cache_obj.get(
        "copy_ownModel", 0) == 1, cache_obj.get("symlink_ownModel", 0) == 1
    if (copy_ownModel or symlink_ownModel):
        if (symlink_ownModel):
            # filepath is the cached location (symlink)
            cached_ownmodel_filepath = os.path.join(cache_loc, "ownModel.xml")
            symlink_destination = os.path.join(UML_loc, "scripts", "client",
                                               "mods", "ownModel.xml")
            if (os.path.islink(symlink_destination)):
                # already symlinked, nothing to do
                outstream.write("Symlink already created, continuing.\n")
            else:
                if (not os.path.isfile(cached_ownmodel_filepath)):
                    # make sure cached_ownmodel_filepath have a file
                    with io.open(cached_ownmodel_filepath, "w") as temp:
                        pass
                if (os.path.isfile(symlink_destination)):
                    # existing ownModel.xml; this should already been copied by the oldversion section above
                    os.remove(symlink_destination)
                # attenmting symlink
                try:
                    os.symlink(cached_ownmodel_filepath, symlink_destination)
                except OSError as e:
                    # insufficient privilege, copy directly
                    outstream.write("OSError caught: " + str(e) + "\n")
                    messagebox.showerror(
                        title="Insufficient privilege",
                        message=
                        "The process do not have enough privilege to create a symlink. Falling back to common copying.\n"
                    )
                    shutil.copyfile(cached_ownmodel_filepath,
                                    symlink_destination)
        else:
            # filepath is the new location of ownModel (copy)
            new_ownmodel_filepath = os.path.join(UML_loc, "scripts", "client",
                                                 "mods", "ownModel.xml")
            copied = False
            for oldversion in (
                    valid[1:] if copy_ownModel else valid
            ):  # go back from the latest version; copy to correct location
                ownmodel_filepath = os.path.join(resmod_folder, oldversion,
                                                 "scripts", "client", "mods",
                                                 "ownModel.xml")
                if (os.path.isfile(ownmodel_filepath)
                        and (not os.path.islink(ownmodel_filepath)
                             or not os.path.islink(new_ownmodel_filepath))):
                    # if there is links already set up (in old or new ownModel), the copying is ignored
                    # last condition is because if there is 3 versions 1-2-3, (1) is symlinked, (2) is copied, and (3) is symlinked again, subsequent copy will override the symlinked (3) with old config (2)
                    shutil.copyfile(ownmodel_filepath, new_ownmodel_filepath)
                    outstream.write(
                        "Found ownModel.xml at {:s}, copied to {:s}".format(
                            oldversion, ownmodel_filepath))
                    copied = True
                    break
            if (not copied):
                outstream.write(
                    "Did not find any ownModel.xml on older directories. Continuing.\n"
                )

    # download all the supplementary mods recorded in download_set into the mods folder
    for i, (filename, link) in enumerate(download_set):
        fileloc = os.path.join(directory, "mods", valid[0], "UML", filename)
        if (progress_labelvar):
            progress_labelvar.set(
                "Downloading {:s} from {} to location {:s}...".format(
                    filename, link, fileloc))
        filehandler.download(
            fileloc,
            link,
            stream=True,
            cache_loc=cache_loc,
            wait=wait,
            progressbar=progressbar,
            session=session)  # check for file in specific locations as well
        outstream.write("Installed mod {:s} to {:s}.\n".format(
            filename, fileloc))
    # check the cache if the credit is already shown for this version (subsequent runs on the same version will no longer show the credit)
    show_credit = cache_obj.get("installed_version",
                                "") != valid[0] and credit_path is not None
    if (show_credit):
        cache_obj["installed_version"] = valid[0]
    # after finished installing, update the cache_obj and write it to disk
    cache_obj["WOT_location"] = directory
    cache_obj["mods"] = [name for name, link in download_set]
    cache.write_cache(cache_obj, cache_obj_path)
    # done
    session.close()
    if (progressbar or progress_labelvar
        ):  # if there are a progressbar in another thread, run its complete
        if (callable(finish_trigger_fn)):
            progress_labelvar.set("Everything finished.")
            if (show_credit):
                credit_dialog(download_set,
                              credit_path,
                              callback_fn=lambda: finish_trigger_fn(True))
            else:
                finish_trigger_fn(True)
    else:  # create a simple infobox
        messagebox.showinfo(
            title="Done",
            message="Installation complete in {:s}".format(directory))

    outstream.write("Finish installation.\n")