Esempio n. 1
0
def main():
    quotes = [
        'The unexamined life is not worth living – Socrates',
        'Entities should not be multiplied unnecessarily – William of Ockham',
        'He who thinks great thoughts, often makes great errors – Martin Heidegger',
        'We live in the best of all possible worlds – Gottfried Wilhelm Leibniz',
        'What is rational is actual and what is actual is rational – G.W.Fy. Hegel',
        'God is dead! He remains dead! And we have killed him. – Friedrich Nietzsche',
        'There is but one truly serious philosophical problem, and that is suicide – Albert Camus',
        'Happiness is not an ideal of reason but of imagination – Immanuel Kant',
        'There is only one good, knowledge, and one evil, ignorance – Socrates',
        'He who is unable to live in society, or who has no need because he is sufficient for himself, must be either a beast or a god – Aristotle',
        'We are too weak to discover the truth by reason alone – St. Augustine'
    ]
    # Selects random quote
    randomQuote = random.choice(quotes)

    print(Back.BLACK + Fore.CYAN +
          'This program generates a random quote from a philosoher.')

    choice = input(Back.BLACK + Fore.MAGENTA +
                   'Would you like to get a quote? y/n: ')

    if choice == 'y':
        clrc.success('Quote: ', randomQuote)
    elif choice == 'n':
        clrc.warn('Maybe another time!')
    else:
        clrc.error('Input Error: Please try again.')
Esempio n. 2
0
def start_flask_server(daemonize=True, debug=True):
    if Path(PID_PATH).exists():
        pid = int(Path(PID_PATH).read_text())

        if pid in psutil.pids():
            clrc.info(
                "It seems daemon is already running. Use restart command to restart it"
            )
            return
        else:
            clrc.warn(
                "It seems daemon was not stopped correctly the last time. PID file exists, and PID inside it do not match any running process. Please remove PID file manually: {0}"
                .format(PID_PATH))
            clrc.info("After removing PID file daemon should start as usual")
            return

    if daemonize:
        if debug:
            clrc.info("Information:")
            clrc.info("Database is at: {0}".format(DATABASE_PATH))
            clrc.info("Daemon process PID file is at: {0}".format(PID_PATH))
            if LOG_PATH:
                clrc.info(
                    "You specified LOG_PATH. It's at: {0}".format(LOG_PATH))
        if (_can_create_pid_file() and _can_create_logs()):
            clrc.info("Starting daemon...")
            clrc.info(
                "Daemon started successfully. You can access your server at http://{0}:{1}"
                .format(HOST, PORT))
            clrc.info(
                "If you are not able to access the web server and sure this is not a problem with firewall/closed port etc, please check logs here: {0}"
                .format(LOG_PATH))
            logger = logging.getLogger()
            logger.setLevel(logging.DEBUG)
            fh = logging.FileHandler(LOG_PATH)
            logger.addHandler(fh)

            # Fix to work with pyinstaller onefile
            fds_to_myself = []
            if getattr(sys, 'frozen', False):
                fds_to_myself = [
                    of.fd for of in psutil.Process(os.getpid()).open_files()
                    if of.path == sys.executable
                ]

            with daemon.DaemonContext(
                    pidfile=pidlockfile.PIDLockFile(PID_PATH),
                    stdout=fh.stream,
                    stderr=fh.stream,
                    files_preserve=[fh.stream] + fds_to_myself):
                _run_flask_app()

            clrc.success(
                "Daemon started! You can access server at {0}:{1}".format(
                    HOST, PORT))
    else:
        _run_flask_app(debug=True)
Esempio n. 3
0
def _can_create_pid_file() -> bool:
    try:
        with open(PID_PATH, "w") as file:
            pass

        Path(PID_PATH).unlink()

        return True
    except:
        clrc.warn(
            "Error creating pidfile for daemon. This error can give you some thoughts, why the problem appeared:"
        )
        clrc.error(traceback.format_exc())
Esempio n. 4
0
def get_env(name: str, default: str, cast_to=None):
    try:
        if not config_exists:
            return default

        value = os.getenv(name, default)

        if cast_to:
            value = cast_to(value)

        return value
    except:
        clrc.warn(
            "Error getting {0} value from config file. Using default value: {1}"
            .format(name, default))
        return default
Esempio n. 5
0
def _can_create_logs() -> bool:
    if not LOG_PATH:
        return True

    try:
        if Path(LOG_PATH).exists():
            with open(LOG_PATH, "r") as file:
                pass
        else:
            with open(LOG_PATH, "w") as file:
                pass

            Path(LOG_PATH).unlink()
        return True
    except:
        clrc.warn(
            "You provided LOGS_PATH in config file, but it seems it cannot be accessed. Here is more info on the error:"
        )
        clrc.error(traceback.format_exc())
        return False
Esempio n. 6
0
def add_log(user: str):
  if user:
    user = find_user(user)
    if not user:
      clrc.info("User with provided username not found. Aborting")
      return

  filepath: str = click.prompt("Please enter absolute path for log file")

  if not filepath.strip():
    clrc.info("No path provided")
    return

  if LOG_PATH == filepath:
    clrc.info("Sorry, you cannot add log file of showme daemon to the logs. It creates eternal recursion, will eat up your space and speed up your fans :D")
    return

  try:
    with open(filepath, "r") as file:
      file.read(1)

    name: str = click.prompt("Please enter name for your log")

    if not name.strip():
      clrc.info("No name provided")
      return

    if not user:
      click.confirm("You are going to add log file for all users, without specifying --user=USERNAME option. It will be accessible by all users. Proceed?", abort=True)
      add_log_file(name, filepath)
      clrc.success("Log file added for everyone")
    else:
      add_log_file(name, filepath, user)
      clrc.success("Log file added for user {0}".format(user.username))


  except:
    clrc.warn("There seems to be the problem with opening file with the provided path. Here is more debug info for you to possibly discover source of the problem:")
    clrc.error(traceback.format_exc())
Esempio n. 7
0
    if not user:
      click.confirm("You are going to add log file for all users, without specifying --user=USERNAME option. It will be accessible by all users. Proceed?", abort=True)
      add_log_file(name, filepath)
      clrc.success("Log file added for everyone")
    else:
      add_log_file(name, filepath, user)
      clrc.success("Log file added for user {0}".format(user.username))


  except:
    clrc.warn("There seems to be the problem with opening file with the provided path. Here is more debug info for you to possibly discover source of the problem:")
    clrc.error(traceback.format_exc())


log.add_command(add_log)


cli.add_command(help)
cli.add_command(init)


if __name__ == "__main__":
  try:
    cli()
  except SystemExit:
    # NOTE: for not logging plain SystemExit, which means well, that cli has ended it's lifecycle. That's all
    pass
  except:
    clrc.warn("Unfortunately, major error occurred while executing command. Here is more info:")
    clrc.error(traceback.format_exc())
Esempio n. 8
0
        return value
    except:
        clrc.warn(
            "Error getting {0} value from config file. Using default value: {1}"
            .format(name, default))
        return default


try:
    PID_PATH = get_env("PID_PATH", os.path.join(HOME_DIR, ".showme.pid"))
    PORT = get_env("PORT", "4020")
    HOST = get_env("HOST", "0.0.0.0")
    DEBUG = get_env("DEBUG", "0", int) == 1
    _SECRET_KEY_DEFAULT = "NOT_SO_SECRET_RIGHT? RIGHT? GUYS?..."
    SECRET_KEY = get_env("SECRET_KEY", _SECRET_KEY_DEFAULT)
    if SECRET_KEY == _SECRET_KEY_DEFAULT:
        clrc.warn(
            "You have default SECRET_KEY value. Please edit this in the config file at {0} to flavour your protection of csrf token"
            .format(CONFIG_PATH))

    DATABASE_PATH = get_env("DATABASE_PATH",
                            os.path.join(HOME_DIR, ".showme.db"))
    LOG_PATH = get_env("LOG_PATH", os.path.join(HOME_DIR, ".showme.log"))
except:
    clrc.error(
        "There was major error reading config file. Cannot continue execution. Maybe this error will give you more information"
    )
    clrc.error(traceback.format_exc())
    sys.exit(1)