server.py 9.2 KB

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