http_server.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. # GPL3 or later
  2. from http.server import BaseHTTPRequestHandler, HTTPServer
  3. from subprocess import *
  4. import urllib.parse
  5. import json
  6. import os
  7. import time
  8. import commands
  9. import local_markdown as markdown
  10. import datetime
  11. from ui import *
  12. ADDRESS = "/"
  13. PORT = 8080
  14. CSS = "http://192.168.0.101:8080/css"
  15. class handler(BaseHTTPRequestHandler):
  16. def start_page(self):
  17. self.send_response(200)
  18. if "/json/" in self.path:
  19. self.send_header('Content-type', 'application/json')
  20. elif self.path == "/css":
  21. self.send_header('Content-type', 'text/css')
  22. elif self.path == "/ttf":
  23. self.send_header('Content-type', 'font/ttf')
  24. elif self.path in ["/favicon.png", "/logo"]:
  25. self.send_header('Content-type', 'image/png')
  26. else:
  27. self.send_header('Content-type', 'text/html')
  28. self.end_headers()
  29. def send(self, textin):
  30. software = self.path.replace("/", "").replace("+", " ")
  31. if software:
  32. software = ": "+software[0].upper()+software[1:].lower()
  33. textin = str(textin)
  34. cssfile = open("default.css")
  35. cssfile = cssfile.read()
  36. csstext = "<style>"+cssfile+"</style>"
  37. text = """<meta charset="Utf-8">
  38. <!-- Welcome to Free Competitors Page Source!!!-->
  39. """
  40. text = text + "<!-- Let's add some CSS, you can edit 'config.json' to change it. -->\n"
  41. text = text + '<head>'+csstext+'\n\n'
  42. text = text + "<!-- Now we want the favicon to be PNG instead of ICO -->\n\n"
  43. text = text + '<link rel="icon" href="https://em-content.zobj.net/thumbs/120/mozilla/36/guitar_1f3b8.png">\n\n'
  44. text = text + "<!-- Now the title -->\n\n"
  45. text = text + '<title>Music Remote Control</title></head>\n\n'
  46. text = text + "<!-- Now the body. The main part of the page, so to speak. -->\n"
  47. text = text + '<body>\n\n'+textin+'\n\n</body>'
  48. self.start_page()
  49. self.wfile.write(text.encode("utf-8"))
  50. def do_GET(self):
  51. if self.path == "/css":
  52. # The css file
  53. cssfile = open("default.css", "rb")
  54. cssfile = cssfile.read()
  55. self.wfile.write(cssfile)
  56. elif self.path == "/favicon.png":
  57. # The css file
  58. self.wfile.write(b"")
  59. elif self.path.startswith("/now_playing"):
  60. page = """
  61. <meta http-equiv="refresh" content="3">
  62. <meta name="viewport" content="width=device-width, initial-scale=1.0,
  63. user-scalable=no">
  64. """
  65. with open('stuff.json') as json_file:
  66. stuff = json.load(json_file)
  67. parsed = urllib.parse.urlparse(self.path)
  68. parsed = urllib.parse.parse_qs(parsed.query)
  69. username = parsed.get("user_name", [""])[0]
  70. password = parsed.get("password", [""])[0]
  71. if stuff.get("users", {}).get(username, {}).get("password", "") != password:
  72. password = ""
  73. videoId = stuff.get("now_playing")
  74. data = stuff.get("songs", {}).get(videoId, {})
  75. # Percent of the song ( Progress bar in the bottom
  76. duration = stuff.get("songs", {}).get(videoId, {}).get("duration", 1)
  77. started = stuff.get("last_played", 0)
  78. percent = str(max(0, min(1, (time.time()-started) / duration)) * 100)
  79. page = page + "<ul><li>"
  80. page = page +user_emoji(stuff.get("now_username", ""), stuff)
  81. page = page + " | "+data.get("title", "")+"<br>"
  82. page = page + "<i>"+timestring(duration)+" / "+timestring(int(time.time()-started))+"</i> "
  83. if password and username != stuff.get("now_username", ""):
  84. page = page +' </li><li><a class="button" href="/?user_name='+username+'&password='+password+'&item='+"https://yewtu.be/"+videoId+'">+</a>'
  85. elif password:
  86. page = page +' </li><li><a class="button" href="/?user_name='+username+'&password='+password+'&item=skip">⏭</a>'
  87. page = page + """
  88. </li></ul><br><br><br><br>
  89. <div class="back_progress">
  90. <div class="front_progress" style="width:"""+str(percent)+"""%">
  91. </div>
  92. </div>"""
  93. self.send(page)
  94. else:
  95. parsed = urllib.parse.urlparse(self.path)
  96. parsed = urllib.parse.parse_qs(parsed.query)
  97. username = parsed.get("user_name", [""])[0]
  98. password = parsed.get("password", [""])[0]
  99. command = parsed.get("item", [""])[0]
  100. volume = parsed.get("volume", [""])[0]
  101. page = "<div class=\"side_found\"><code>"+username+"</code><br><br>"
  102. page = page + """<meta name="viewport" content="width=device-width, initial-scale=1.0,
  103. user-scalable=no">"""
  104. page = page + "<code>"+command+"</code><br><br>"
  105. with open('stuff.json') as json_file:
  106. stuff = json.load(json_file)
  107. new_date_format = "%Y/%m/%d"
  108. today = datetime.datetime.strftime(datetime.datetime.today(), new_date_format)
  109. for d in range(400):
  110. yesterday = datetime.datetime.strftime(datetime.datetime.today()-datetime.timedelta(days=d+1), new_date_format)
  111. if yesterday in stuff.get("volume", {}):
  112. break
  113. if volume:
  114. page = """<meta http-equiv="refresh" content="0; url=/?user_name="""+username+"""&password="""+password+"""&item="""+volume+"""%" />"""
  115. if not stuff.get("users", {}).get(username, {}).get("password", "") and password:
  116. try:
  117. stuff["users"][username]["password"] = password
  118. with open('stuff.json', 'w') as fp:
  119. json.dump(stuff, fp, indent=4)
  120. except Exception as e:
  121. print( "ERROR", e)
  122. if username not in stuff.get("users", {}):
  123. page = page + "<i>To create an account use either the Matrix group, or ask the administrator to create an acount for you manually.<br><br>"
  124. elif stuff.get("users", {}).get(username, {}).get("password", "") == password:
  125. answer = commands.execute(username, command, password=password)
  126. afterpage = ""
  127. if not answer and command:
  128. page = page + '<details class="button"><summary>🎸 From Your History בהיסטוריה שלך</summary><br>'
  129. answer = commands.execute(username, "history "+command, password=password)
  130. page = page + markdown.convert(answer, isfile=False) + "<br><br>"
  131. page = page + '</details><br><details class="button"><summary>🎶 In All Songs בכל השירים</summary><br>'
  132. answer = commands.execute(username, "songs "+command, password=password)
  133. page = page + markdown.convert(answer, isfile=False) + "<br><br>"
  134. page = page + '</details><br><details class="button"><summary>🌐 From YouTube ביוטיוב</summary><br>'
  135. answer = commands.execute(username, "search "+command, password=password)
  136. afterpage = "</details>"
  137. elif not answer:
  138. answer = commands.execute(username, "help", password=password)
  139. page = page + markdown.convert(answer, isfile=False) + "<br><br>"+afterpage
  140. else:
  141. page = page + "Invalid Password<br><br>"
  142. if not username or not password:
  143. page = page + """
  144. </div>
  145. <div class="searchbar">
  146. <center>
  147. <br><br>
  148. <form action="/" method="GET">
  149. <input id="user_name" name="user_name" autofocus required placeholder="Matrix Username" size="8"><br>
  150. <input id="password" name="password" type="password" placeholder="Password" size="8" /><br>
  151. <input name="item" type="hidden" value='help'>
  152. <button type="submit">Login</button>
  153. </form>
  154. </center></div>
  155. """
  156. else:
  157. volume_was = stuff.get("volume", {}).get(today, {}).get("users", {}).get(username, stuff.get("volume", {}).get(yesterday, {}).get("average", 20))
  158. if command.endswith("%"):
  159. volume_was = command.replace("%", "")
  160. page = page + """
  161. <br><br><br><br><br><br><br><br><br><br><br><br>
  162. </div>
  163. <div class="searchbar">
  164. <center>
  165. <form action="/" method="GET">
  166. <a class="button" href="/?user_name="""+username+"""&password="""+password+"""">🏠️</a>
  167. <input id="user_name" name="user_name" type="hidden" value='"""+username+"""'>
  168. <input id="password" name="password" type="hidden" value='"""+password+"""'>
  169. <input type="text" name="item" class="search" placeholder="Command" >
  170. <button type="submit">▶</button>
  171. </form>
  172. <br>
  173. <a class="button" href="/?user_name="""+username+"""&password="""+password+"""&item=list">⬆</a>
  174. <a class="button" href="/?user_name="""+username+"""&password="""+password+"""&item=history">🎸</a>
  175. <a class="button" href="/?user_name="""+username+"""&password="""+password+"""&item=set_volume">🔈</a>
  176. <a class="button" href="/?user_name="""+username+"""&password="""+password+"""&item=songs">🎶</a>
  177. </center></div>
  178. <div class="nowplayingbar"><iframe src="/now_playing?user_name="""+username+"""&password="""+password+"""" title="now playing" width="100%" height="200" style="border:none;" ></iframe></div>
  179. """
  180. self.send(page)
  181. serve = HTTPServer(("", PORT), handler)
  182. print("Now serving on port "+ str(PORT) +" at "+ ADDRESS +".")
  183. serve.serve_forever()