server.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. #!/usr/bin/python3
  2. # THIS SOFTWARE IS A PART OF FREE COMPETITOR PROJECT
  3. # THE FOLLOWING SOURCE CODE I UNDER THE GNU
  4. # AGPL LICENSE V3 OR ANY LATER VERSION.
  5. # This project is not for simple users, but for
  6. # web-masters and a like, so we are counting on
  7. # your ability to set it up and running.
  8. # Server side
  9. from http.server import BaseHTTPRequestHandler, HTTPServer
  10. from subprocess import *
  11. import json
  12. import os
  13. import sys
  14. import time
  15. import threading
  16. from modules import search
  17. from modules import render
  18. # Author: https://www.delftstack.com/howto/python/python-print-colored-text/
  19. class bcolors:
  20. OK = '\033[92m' #GREEN
  21. WARNING = '\033[93m' #YELLOW
  22. FAIL = '\033[91m' #RED
  23. RESET = '\033[0m' #RESET COLOR
  24. print("""╔═╗┬─┐┌─┐┌─┐╔═╗┌─┐┌┬┐┌─┐┌─┐┌┬┐┬┌┬┐┌─┐┬─┐┌─┐
  25. ╠╣ ├┬┘├┤ ├┤ ║ │ ││││├─┘├┤ │ │ │ │ │├┬┘└─┐
  26. ╚ ┴└─└─┘└─┘╚═╝└─┘┴ ┴┴ └─┘ ┴ ┴ ┴ └─┘┴└─└─┘
  27. Copyright (C) 2022 Jeison Yehuda Amihud and contributors.
  28. This program is free software: you can redistribute it and/or modify
  29. it under the terms of the GNU Affero General Public License as published by
  30. the Free Software Foundation, either version 3 of the License, or
  31. (at your option) any later version.
  32. This program is distributed in the hope that it will be useful,
  33. but WITHOUT ANY WARRANTY; without even the implied warranty of
  34. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  35. GNU Affero General Public License for more details.
  36. You should have received a copy of the GNU Affero General Public License
  37. along with this program. If not, see <http://www.gnu.org/licenses/>.
  38. """)
  39. print("Loading config...")
  40. if os.path.exists("config.json"):
  41. with open("config.json","r") as f:
  42. srvConfig = json.load(f)
  43. ADDRESS = srvConfig["address"]
  44. PORT = srvConfig["port"]
  45. CSS = srvConfig["css"]
  46. print(bcolors.OK + "Loaded Configuration: " + bcolors.RESET)
  47. print("Address: "+ ADDRESS)
  48. print("Port: "+ str(PORT)) # Do not think people are smart at syntax
  49. print("CSS: "+ CSS)
  50. try:
  51. PORT = int(PORT)
  52. except:
  53. print(bcolors.FAIL + "ERR: Port should be a number" + bcolors.RESET)
  54. exit()
  55. else:
  56. newConfig = open("config.json", "w")
  57. newConfig.write("""{
  58. "INFO" : "You would be better off setting address to the full URL of the FreeCompetitors instance.",
  59. "address" : "/",
  60. "port" : 8080,
  61. "css" : "/css"
  62. }""")
  63. newConfig.close
  64. print(bcolors.WARNING + "Please edit the configuration file \"config.json\"." + bcolors.RESET)
  65. exit()
  66. # Who fucking made this http.server so I need to use classes?
  67. # I fucking hate who ever thought that it was a good idea...
  68. class handler(BaseHTTPRequestHandler):
  69. def start_page(self):
  70. self.send_response(200)
  71. if "/json/" in self.path:
  72. self.send_header('Content-type', 'application/json')
  73. elif self.path == "/css":
  74. self.send_header('Content-type', 'text/css')
  75. elif self.path == "/ttf":
  76. self.send_header('Content-type', 'font/ttf')
  77. elif self.path in ["/favicon.png", "/logo"]:
  78. self.send_header('Content-type', 'image/png')
  79. else:
  80. self.send_header('Content-type', 'text/html')
  81. self.end_headers()
  82. def send(self, textin):
  83. software = self.path.replace("/", "").replace("+", " ")
  84. if software:
  85. software = ": "+software[0].upper()+software[1:].lower()
  86. textin = str(textin)
  87. csstext = '<link media="all" href="'+CSS+'" type="text/css" rel="stylesheet" />'
  88. text = "<!-- Welcome to Free Competitors Page Source!!!--> \n\n"
  89. text = text + "<!-- Let's add some CSS, you can edit 'config.json' to change it. -->\n"
  90. text = text + '<head>'+csstext+'\n\n'
  91. text = text + "<!-- Now we want the favicon to be PNG instead of ICO -->\n\n"
  92. text = text + '<link rel="icon" href="favicon.png">\n\n'
  93. text = text + "<!-- Now the title -->\n\n"
  94. text = text + '<title>Free Competitors'+software+'</title></head>\n\n'
  95. text = text + "<!-- Now the body. The main part of the page, so to speak. -->\n"
  96. text = text + '<body>\n\n'+textin+'\n\n</body>'
  97. self.start_page()
  98. self.wfile.write(text.encode("utf-8"))
  99. def do_GET(self):
  100. if self.path.startswith("/json/"):
  101. # API CALL
  102. term = self.path[6:]
  103. software_data, match = search.search_app(term)
  104. data = {"found":{"data":software_data,"match":match}}
  105. data["suggestions"] = search.suggest(software_data)
  106. text = json.dumps(data, indent = 2)
  107. self.start_page()
  108. self.wfile.write(text.encode("utf-8"))
  109. elif self.path == "/":
  110. # If the user is at the front page, let him get only the search bar
  111. page = """<center>
  112. <br><br><br>
  113. <img src="/logo" alt="[LOGO]" style="height:150px;">
  114. <h1>Free Competitors</h1>"""
  115. page = render.search_widget(page, ADDRESS)
  116. page = page + "<p>Please search for any software to which you would like to find a Free Software replacement.</p></center>"
  117. page = render.source_code_link(page)
  118. self.send(page)
  119. elif self.path == "/test":
  120. self.send_response(200)
  121. self.wfile.write("Success!".encode("utf-8"))
  122. elif self.path == "/css":
  123. # The css file
  124. self.send_response(200)
  125. self.send_header('Content-type', 'text/css')
  126. self.end_headers()
  127. cssfile = open("default.css", "rb")
  128. cssfile = cssfile.read()
  129. self.wfile.write(cssfile)
  130. elif self.path == "/font":
  131. # The font file
  132. fontfile = open("OpenSans-ExtraBold.ttf", "rb")
  133. fontfile = fontfile.read()
  134. self.wfile.write(fontfile)
  135. elif self.path in ["/faq", "/faq?"]:
  136. # The font file
  137. faqfile = open("faq.html")
  138. faqfile = faqfile.read()
  139. faqfile = render.search_widget(faqfile, ADDRESS)
  140. faqfile = render.source_code_link(faqfile)
  141. self.send(faqfile)
  142. elif "/favicon.png" == self.path:
  143. # I'm recording all the favicons request times to get
  144. # a rough estimate of how many people visit when.
  145. # It seems like the browser is visiting the site for
  146. # the first time ( at least in a given session ) it
  147. # asks for a 'favicon.ico'. So I store each of those
  148. # requests time. As a timestamp.
  149. try:
  150. with open("data/favicon_requests.json") as json_file:
  151. favicons = json.load(json_file)
  152. except:
  153. favicons = []
  154. favicons.append(time.time())
  155. with open("data/favicon_requests.json", 'w') as f:
  156. json.dump(favicons, f, indent=4, sort_keys=True)
  157. icon = open("favicon.png", "rb")
  158. icon = icon.read()
  159. self.wfile.write(icon)
  160. elif "/logo" == self.path:
  161. self.send_response(200)
  162. self.send_header('Content-type', 'image/png')
  163. self.end_headers()
  164. icon = open("favicon.png", "rb")
  165. icon = icon.read()
  166. self.wfile.write(icon)
  167. elif self.path in ["/stats", "/stats?"]:
  168. # Analytics / statistics availble for all users of
  169. # the website.
  170. try:
  171. with open("data/favicon_requests.json") as json_file:
  172. favicons = json.load(json_file)
  173. except:
  174. favicons = []
  175. page = render.stats("", True, favicons)
  176. self.send(page)
  177. elif "/search?item=" in self.path:
  178. # Clearing the url
  179. # instead of it being /search?item=softwarename
  180. # it will be just /softwarename
  181. item = self.path[self.path.find("item=")+5:].lower()
  182. self.send('<meta http-equiv="Refresh" content="0; url=\'/'+item+'\'" />')
  183. else:
  184. # This is when the fun is
  185. software = self.path.replace("/", "").replace("+", " ")
  186. software_data, match = search.search_app(software)
  187. page = ""
  188. page = page + '<div class="searchbar">'
  189. page = page + render.search_widget("", ADDRESS)
  190. page = page + "</div>"
  191. page = page + '<div class="side_found">'
  192. page = render.progress(page, match, "Search match: "+ str(int(match*100))+"%")
  193. # Let's add the found software to the page
  194. page = render.html(page, software_data)
  195. page = page + "</div>"
  196. page = page + '<div class="recomendations">'
  197. page = render.suggestions(page, software_data)
  198. page = render.source_code_link(page)
  199. page = page + "</div>"
  200. self.send(page)
  201. serve = HTTPServer(("", PORT), handler)
  202. print(bcolors.OK + "⚡Now serving on port "+ str(PORT) +" at "+ ADDRESS +"." + bcolors.RESET)
  203. def Test():
  204. while True:
  205. time.sleep(100)
  206. # Check if the server is running.
  207. try:
  208. req = urllib.request.Request("http://localhost:"+str(PORT)+"/test")
  209. f = urllib.request.urlopen(req, timeout=2)
  210. except Exception as e:
  211. if "Success!" != str(e):
  212. print( "Test:", e, "restarting server!" )
  213. os.execl(sys.executable, *sys.orig_argv)
  214. t2 = threading.Thread(target=Test, daemon=True)
  215. t2.start()
  216. serve.serve_forever()