server.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  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. from modules import search
  14. from modules import render
  15. # Author: https://www.delftstack.com/howto/python/python-print-colored-text/
  16. class bcolors:
  17. OK = '\033[92m' #GREEN
  18. WARNING = '\033[93m' #YELLOW
  19. FAIL = '\033[91m' #RED
  20. RESET = '\033[0m' #RESET COLOR
  21. print("""╔═╗┬─┐┌─┐┌─┐╔═╗┌─┐┌┬┐┌─┐┌─┐┌┬┐┬┌┬┐┌─┐┬─┐┌─┐
  22. ╠╣ ├┬┘├┤ ├┤ ║ │ ││││├─┘├┤ │ │ │ │ │├┬┘└─┐
  23. ╚ ┴└─└─┘└─┘╚═╝└─┘┴ ┴┴ └─┘ ┴ ┴ ┴ └─┘┴└─└─┘
  24. Copyright (C) 2022 Jeison Yehuda Amihud and contributors.
  25. This program is free software: you can redistribute it and/or modify
  26. it under the terms of the GNU Affero General Public License as published by
  27. the Free Software Foundation, either version 3 of the License, or
  28. (at your option) any later version.
  29. This program is distributed in the hope that it will be useful,
  30. but WITHOUT ANY WARRANTY; without even the implied warranty of
  31. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  32. GNU Affero General Public License for more details.
  33. You should have received a copy of the GNU Affero General Public License
  34. along with this program. If not, see <http://www.gnu.org/licenses/>.
  35. """)
  36. print("Loading config...")
  37. if os.path.exists("config.json"):
  38. with open("config.json","r") as f:
  39. srvConfig = json.load(f)
  40. ADDRESS = srvConfig["address"]
  41. PORT = srvConfig["port"]
  42. CSS = srvConfig["css"]
  43. print(bcolors.OK + "Loaded Configuration: " + bcolors.RESET)
  44. print("Address: "+ ADDRESS)
  45. print("Port: "+ str(PORT)) # Do not think people are smart at syntax
  46. print("CSS: "+ CSS)
  47. try:
  48. PORT = int(PORT)
  49. except:
  50. print(bcolors.FAIL + "ERR: Port should be a number" + bcolors.RESET)
  51. exit()
  52. else:
  53. newConfig = open("config.json", "w")
  54. newConfig.write("""{
  55. "INFO" : "You would be better off setting address to the full URL of the FreeCompetitors instance.",
  56. "address" : "/",
  57. "port" : 8080,
  58. "css" : "/css"
  59. }""")
  60. newConfig.close
  61. print(bcolors.WARNING + "Please edit the configuration file \"config.json\"." + bcolors.RESET)
  62. exit()
  63. # Who fucking made this http.server so I need to use classes?
  64. # I fucking hate who ever thought that it was a good idea...
  65. class handler(BaseHTTPRequestHandler):
  66. def start_page(self):
  67. self.send_response(200)
  68. if "/json/" in self.path:
  69. self.send_header('Content-type', 'application/json')
  70. elif self.path == "/css":
  71. self.send_header('Content-type', 'text/css')
  72. elif self.path == "/ttf":
  73. self.send_header('Content-type', 'font/ttf')
  74. else:
  75. self.send_header('Content-type', 'text/html')
  76. self.end_headers()
  77. def send(self, text):
  78. text = str(text)
  79. csstext = '<link media="all" href="'+CSS+'" type="text/css" rel="stylesheet" />'
  80. text = '<head>'+csstext+'</head><body>'+text+'</body>'
  81. self.start_page()
  82. self.wfile.write(text.encode("utf-8"))
  83. def do_GET(self):
  84. if self.path.startswith("/json/"):
  85. # API CALL
  86. term = self.path[6:]
  87. software_data, match = search.search_app(term)
  88. data = {"found":{"data":software_data,"match":match}}
  89. data["suggestions"] = search.suggest(software_data)
  90. text = json.dumps(data, indent = 2)
  91. self.start_page()
  92. self.wfile.write(text.encode("utf-8"))
  93. elif self.path == "/":
  94. # If the user is at the front page, let him get only the search bar
  95. page = "<center><br><br><br><h1>Free Competitors</h1>"
  96. page = render.search_widget(page, ADDRESS)
  97. page = page + "<p>Please search for any software to which you would like to find a Free Software replacement.</p></center>"
  98. page = render.source_code_link(page)
  99. self.send(page)
  100. elif self.path == "/css":
  101. # The css file
  102. cssfile = open("default.css")
  103. cssfile = cssfile.read()
  104. self.send(cssfile)
  105. elif self.path == "/font":
  106. # The font file
  107. fontfile = open("OpenSans-ExtraBold.ttf", "rb")
  108. fontfile = fontfile.read()
  109. self.send(fontfile)
  110. elif self.path in ["/faq", "/faq?"]:
  111. # The font file
  112. faqfile = open("faq.html")
  113. faqfile = faqfile.read()
  114. faqfile = render.search_widget(faqfile, ADDRESS)
  115. faqfile = render.source_code_link(faqfile)
  116. self.send(faqfile)
  117. elif "/search?item=" in self.path:
  118. # Clearing the url
  119. # instead of it being /search?item=softwarename
  120. # it will be just /softwarename
  121. item = self.path[self.path.find("item=")+5:].lower()
  122. self.send('<meta http-equiv="Refresh" content="0; url=\'/'+item+'\'" />')
  123. else:
  124. # This is when the fun is
  125. software = self.path.replace("/", "").replace("+", " ")
  126. software_data, match = search.search_app(software)
  127. page = render.search_widget("", ADDRESS)
  128. page = page +"Search match: "+ str(int(match*100))+"%"
  129. # Let's add the found software to the page
  130. page = render.html(page, software_data)
  131. page = render.suggestions(page, software_data)
  132. page = render.source_code_link(page)
  133. self.send(page)
  134. serve = HTTPServer(("", PORT), handler)
  135. print(bcolors.OK + "⚡Now serving on port "+ str(PORT) +" at "+ ADDRESS +"." + bcolors.RESET)
  136. serve.serve_forever()