server.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  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, textin):
  78. textin = str(textin)
  79. csstext = '<link media="all" href="'+CSS+'" type="text/css" rel="stylesheet" />'
  80. text = "<!-- Welcome to Free Competitors Page Source!!!--> \n\n"
  81. text = text + "<!-- Let's add some CSS, you can edit 'config.json' to change it. -->\n"
  82. text = text + '<head>'+csstext+'</head>\n\n'
  83. text = text + "<!-- Now the body. The main part of the page, so to speak. -->\n"
  84. text = text + '<body>\n\n'+textin+'\n\n</body>'
  85. self.start_page()
  86. self.wfile.write(text.encode("utf-8"))
  87. def do_GET(self):
  88. if self.path.startswith("/json/"):
  89. # API CALL
  90. term = self.path[6:]
  91. software_data, match = search.search_app(term)
  92. data = {"found":{"data":software_data,"match":match}}
  93. data["suggestions"] = search.suggest(software_data)
  94. text = json.dumps(data, indent = 2)
  95. self.start_page()
  96. self.wfile.write(text.encode("utf-8"))
  97. elif self.path == "/":
  98. # If the user is at the front page, let him get only the search bar
  99. page = "<center><br><br><br><h1>Free Competitors</h1>"
  100. page = render.search_widget(page, ADDRESS)
  101. page = page + "<p>Please search for any software to which you would like to find a Free Software replacement.</p></center>"
  102. page = render.source_code_link(page)
  103. self.send(page)
  104. elif self.path == "/css":
  105. # The css file
  106. cssfile = open("default.css")
  107. cssfile = cssfile.read()
  108. self.send(cssfile)
  109. elif self.path == "/font":
  110. # The font file
  111. fontfile = open("OpenSans-ExtraBold.ttf", "rb")
  112. fontfile = fontfile.read()
  113. self.send(fontfile)
  114. elif self.path in ["/faq", "/faq?"]:
  115. # The font file
  116. faqfile = open("faq.html")
  117. faqfile = faqfile.read()
  118. faqfile = render.search_widget(faqfile, ADDRESS)
  119. faqfile = render.source_code_link(faqfile)
  120. self.send(faqfile)
  121. elif "/search?item=" in self.path:
  122. # Clearing the url
  123. # instead of it being /search?item=softwarename
  124. # it will be just /softwarename
  125. item = self.path[self.path.find("item=")+5:].lower()
  126. self.send('<meta http-equiv="Refresh" content="0; url=\'/'+item+'\'" />')
  127. else:
  128. # This is when the fun is
  129. software = self.path.replace("/", "").replace("+", " ")
  130. software_data, match = search.search_app(software)
  131. page = render.search_widget("", ADDRESS)
  132. page = page +"Search match: "+ str(int(match*100))+"%"
  133. # Let's add the found software to the page
  134. page = render.html(page, software_data)
  135. page = render.suggestions(page, software_data)
  136. page = render.source_code_link(page)
  137. self.send(page)
  138. serve = HTTPServer(("", PORT), handler)
  139. print(bcolors.OK + "⚡Now serving on port "+ str(PORT) +" at "+ ADDRESS +"." + bcolors.RESET)
  140. serve.serve_forever()