zeronet.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. #!/usr/bin/env python3
  2. import os
  3. import sys
  4. from src.Config import config
  5. # fix further imports from src dir
  6. sys.modules['Config'] = sys.modules['src.Config']
  7. def pyReq():
  8. major = sys.version_info.major
  9. minor = sys.version_info.minor
  10. if major < 3 or (major == 3 and minor < 8):
  11. print("Error: Python 3.8+ is required")
  12. sys.exit(0)
  13. if major == 3 and minor < 11:
  14. print(f"Python 3.11+ is recommended (you're running {sys.version})")
  15. def launch():
  16. '''renamed from main to avoid clashes with main module'''
  17. pyReq()
  18. if '--silent' not in sys.argv:
  19. from greet import fancy_greet
  20. fancy_greet(config.version)
  21. try:
  22. import main
  23. main.start()
  24. except Exception as err: # Prevent closing
  25. import traceback
  26. try:
  27. import logging
  28. logging.exception("Unhandled exception: %s" % err)
  29. except Exception as log_err:
  30. print("Failed to log error:", log_err)
  31. traceback.print_exc()
  32. error_log_path = config.log_dir / "error.log"
  33. traceback.print_exc(file=open(error_log_path, "w"))
  34. print("---")
  35. print("Please report it: https://github.com/zeronet-conservancy/zeronet-conservancy/issues/new?template=bug-report.md")
  36. if sys.platform.startswith("win") and "python.exe" not in sys.executable:
  37. displayErrorMessage(err, error_log_path)
  38. if main and (main.update_after_shutdown or main.restart_after_shutdown): # Updater
  39. if main.update_after_shutdown:
  40. print("Shutting down...")
  41. prepareShutdown()
  42. import update
  43. print("Updating...")
  44. update.update()
  45. if main.restart_after_shutdown:
  46. print("Restarting...")
  47. restart()
  48. else:
  49. print("Shutting down...")
  50. prepareShutdown()
  51. print("Restarting...")
  52. restart()
  53. def displayErrorMessage(err, error_log_path):
  54. import ctypes
  55. import urllib.parse
  56. import subprocess
  57. MB_YESNOCANCEL = 0x3
  58. MB_ICONEXCLAIMATION = 0x30
  59. ID_YES = 0x6
  60. ID_NO = 0x7
  61. ID_CANCEL = 0x2
  62. err_message = "%s: %s" % (type(err).__name__, err)
  63. err_title = "Unhandled exception: %s\nReport error?" % err_message
  64. res = ctypes.windll.user32.MessageBoxW(0, err_title, "ZeroNet error", MB_YESNOCANCEL | MB_ICONEXCLAIMATION)
  65. if res == ID_YES:
  66. import webbrowser
  67. report_url = "https://github.com/zeronet-conservancy/zeronet-conservancy/issues/new"
  68. webbrowser.open(report_url)
  69. if res in [ID_YES, ID_NO]:
  70. subprocess.Popen(['notepad.exe', error_log_path])
  71. def prepareShutdown():
  72. import atexit
  73. atexit._run_exitfuncs()
  74. # Close log files
  75. if "main" in sys.modules:
  76. logger = sys.modules["main"].logging.getLogger()
  77. for handler in logger.handlers[:]:
  78. handler.flush()
  79. handler.close()
  80. logger.removeHandler(handler)
  81. import time
  82. time.sleep(1) # Wait for files to close
  83. def restart():
  84. args = sys.argv[:]
  85. sys.executable = sys.executable.replace(".pkg", "") # Frozen mac fix
  86. if not getattr(sys, 'frozen', False):
  87. args.insert(0, sys.executable)
  88. # Don't open browser after restart
  89. if "--open_browser" in args:
  90. del args[args.index("--open_browser") + 1] # argument value
  91. del args[args.index("--open_browser")] # argument key
  92. if getattr(sys, 'frozen', False):
  93. pos_first_arg = 1 # Only the executable
  94. else:
  95. pos_first_arg = 2 # Interpter, .py file path
  96. args.insert(pos_first_arg, "--open_browser")
  97. args.insert(pos_first_arg + 1, "False")
  98. if sys.platform == 'win32':
  99. args = ['"%s"' % arg for arg in args]
  100. try:
  101. print("Executing %s %s" % (sys.executable, args))
  102. os.execv(sys.executable, args)
  103. except Exception as err:
  104. print("Execv error: %s" % err)
  105. print("Bye.")
  106. def start():
  107. config.working_dir = os.getcwd()
  108. app_dir = os.path.dirname(os.path.abspath(__file__))
  109. os.chdir(app_dir) # Change working dir to zeronet.py dir
  110. sys.path.insert(0, os.path.join(app_dir, "src/lib")) # External liblary directory
  111. sys.path.insert(0, os.path.join(app_dir, "src")) # Imports relative to src
  112. if "--update" in sys.argv:
  113. sys.argv.remove("--update")
  114. print("Updating...")
  115. import update
  116. update.update()
  117. else:
  118. launch()
  119. if __name__ == '__main__':
  120. start()