server.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  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
  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: "+ PORT)
  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" : "https://zortazert.codeberg.page/style/styles.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/" not in self.path:
  69. self.send_header('Content-type', 'text/html')
  70. else:
  71. self.send_header('Content-type', 'application/json')
  72. self.end_headers()
  73. def send(self, text):
  74. text = str(text)
  75. csstext = '<link media="all" href="'+CSS+'" type="text/css" rel="stylesheet" />'
  76. text = '<head>'+csstext+'</head><body>'+text+'</body>'
  77. self.start_page()
  78. self.wfile.write(text.encode("utf-8"))
  79. def do_GET(self):
  80. if self.path.startswith("/json/"):
  81. # API CALL
  82. term = self.path[6:]
  83. software_data, match = search.search_app(term)
  84. data = {"found":{"data":software_data,"match":match}}
  85. data["suggestions"] = search.suggest(software_data)
  86. text = json.dumps(data, indent = 2)
  87. self.start_page()
  88. self.wfile.write(text.encode("utf-8"))
  89. elif self.path == "/":
  90. # If the user is at the front page, let him get only the search bar
  91. page = "<center><br><br><br><h1>Free Competitors</h1>"
  92. page = render.search_widget(page, ADDRESS)
  93. page = page + "<p>Please search for any software to which you would like to find a Free Software replacement.</p></center>"
  94. page = render.source_code_link(page)
  95. self.send(page)
  96. elif "/search?item=" in self.path:
  97. # Clearing the url
  98. # instead of it being /search?item=softwarename
  99. # it will be just /softwarename
  100. item = self.path[self.path.find("item=")+5:].lower()
  101. self.send('<meta http-equiv="Refresh" content="0; url=\'/'+item+'\'" />')
  102. else:
  103. # This is when the fun is
  104. software = self.path.replace("/", "").replace("+", " ")
  105. software_data, match = search.search_app(software)
  106. page = render.search_widget("", ADDRESS)
  107. page = page +"Search match: "+ str(int(match*100))+"%"
  108. # Let's add the found software to the page
  109. page = render.html(page, software_data)
  110. page = render.suggestions(page, software_data)
  111. page = render.source_code_link(page)
  112. self.send(page)
  113. serve = HTTPServer(("", PORT), handler)
  114. print(bcolors.OK + "⚡Now serving on port "+ str(PORT) +" at "+ ADDRESS +"." + bcolors.RESET)
  115. serve.serve_forever()