zeronet.py 4.0 KB

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