zeronet.py 5.1 KB

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