Player_Web.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. #!/usr/bin/env python3
  2. # -*- encoding: utf-8 -*-
  3. # Author: MoeClub.org
  4. import tornado.web
  5. import tornado.ioloop
  6. import tornado.options
  7. import tornado.httpserver
  8. import json
  9. import os
  10. import time
  11. import base64
  12. MasterKey = ["MoeClub"]
  13. SubPath = "Player"
  14. RootPath = os.path.dirname(os.path.abspath(__file__))
  15. DataPath = os.path.join(RootPath, "data")
  16. class Utils:
  17. treelist = []
  18. treetime = 0
  19. @staticmethod
  20. def load(file, mode="r"):
  21. if "b" in mode:
  22. fd = open(file, mode)
  23. else:
  24. fd = open(file, mode, encoding="utf-8")
  25. data = fd.read()
  26. fd.close()
  27. return data
  28. @classmethod
  29. def b64(cls, file):
  30. data = cls.load(file=file)
  31. b64data = base64.b64encode(data.encode("utf-8"))
  32. return b64data.decode("utf-8")
  33. @classmethod
  34. def list(cls, dirname, second=15):
  35. if not os.path.exists(dirname):
  36. return ""
  37. if int(time.time()) - second >= cls.treetime:
  38. cls.treelist = []
  39. cls.tree(dirname=dirname)
  40. cls.treetime = int(time.time())
  41. return "\n".join(cls.treelist)
  42. @classmethod
  43. def tree(cls, dirname, padding=" ", Print=False):
  44. PRINTITEM1 = padding[:-1] + '+-' + os.path.basename(os.path.abspath(dirname)) + '/'
  45. cls.treelist.append(PRINTITEM1)
  46. if Print:
  47. print(PRINTITEM1)
  48. padding = padding + ' '
  49. files = os.listdir(dirname)
  50. count = 0
  51. for file in files:
  52. count += 1
  53. PRINTITEM2 = padding + '|'
  54. cls.treelist.append(PRINTITEM2)
  55. if Print:
  56. print(PRINTITEM2)
  57. path = dirname + os.sep + file
  58. if os.path.isdir(path):
  59. if count == len(files):
  60. cls.tree(path, padding + ' ', Print)
  61. else:
  62. cls.tree(path, padding + '|', Print)
  63. else:
  64. PRINTITEM3 = padding + '+-' + file
  65. cls.treelist.append(PRINTITEM3)
  66. if Print:
  67. print(PRINTITEM3)
  68. class MainHandler(tornado.web.RequestHandler):
  69. StringList = [chr(item) for item in range(65, 90 + 1)] + [chr(item) for item in range(48, 57 + 1)] + [chr(item) for item in range(97, 122 + 1)] + ["-", "_", ".", "@"]
  70. StaticFile = {}
  71. def check_argument(self, key):
  72. value = None
  73. if key in self.request.arguments:
  74. value = self.get_argument(key)
  75. return value
  76. def real_address(self):
  77. if 'X-Real-IP' in self.request.headers:
  78. self.request.remote_ip = self.request.headers['X-Real-IP']
  79. return self.request.remote_ip
  80. def WriteString(self, obj):
  81. if isinstance(obj, (str, int)):
  82. return obj
  83. elif isinstance(obj, (dict, list)):
  84. return json.dumps(obj, ensure_ascii=False)
  85. else:
  86. return obj
  87. def get(self, Item=None):
  88. try:
  89. self.real_address()
  90. assert Item and str(Item).strip()
  91. if Item == "list":
  92. data = Utils.list(DataPath)
  93. self.set_header("Content-Type", "text/plain; charset=utf-8")
  94. self.write(self.WriteString(data))
  95. self.finish()
  96. return
  97. print(Item)
  98. if str(Item).strip().lstrip("/").startswith("static/"):
  99. StaticPath = os.path.join(RootPath, Item)
  100. if os.path.exists(StaticPath):
  101. if str(StaticPath).endswith(".js"):
  102. self.set_header("Content-Type", "application/javascript; charset=utf-8")
  103. elif str(StaticPath).endswith(".css"):
  104. self.set_header("Content-Type", "text/css")
  105. if StaticPath not in self.StaticFile:
  106. self.StaticFile[StaticPath] = Utils.load(StaticPath, "rb")
  107. self.finish(self.StaticFile[StaticPath])
  108. self.flush()
  109. else:
  110. self.set_status(404)
  111. self.finish()
  112. return
  113. if not str(Item).strip().endswith(".m3u8"):
  114. Item = str(Item).strip() + ".m3u8"
  115. ItemPath = os.path.join(DataPath, Item)
  116. if os.path.exists(ItemPath):
  117. self.render("Player.html", PageTitle=str(Item).rstrip(".m3u8"), SubPath=str("/%s" % SubPath), PageData=Utils.b64(ItemPath))
  118. else:
  119. self.set_status(404)
  120. self.write("Not Found")
  121. except:
  122. self.set_status(400)
  123. self.write("Null")
  124. def post(self, Item=None):
  125. try:
  126. assert Item and str(Item).strip()
  127. assert str(Item) in MasterKey
  128. filesDict = self.request.files["file"]
  129. for FileItem in filesDict:
  130. if "filename" in FileItem and FileItem["filename"]:
  131. ItemName = FileItem["filename"]
  132. else:
  133. ItemName = "UN" + str(int(time.time())) + ".m3u8"
  134. FileSave = os.path.join(DataPath, ItemName)
  135. fd = open(FileSave, "wb")
  136. fd.write(FileItem["body"])
  137. fd.close()
  138. self.set_status(200)
  139. self.write("ok")
  140. except:
  141. self.set_status(400)
  142. self.write("fail")
  143. class Web:
  144. @staticmethod
  145. def main():
  146. tornado.options.define("host", default='127.0.0.1', help="Host", type=str)
  147. tornado.options.define("port", default=5866, help="Port", type=int)
  148. tornado.options.parse_command_line()
  149. application = tornado.web.Application([(r"/%s/(?P<Item>.+)" % SubPath, MainHandler)], static_path=os.path.join(RootPath, "static"))
  150. http_server = tornado.httpserver.HTTPServer(application)
  151. http_server.listen(tornado.options.options.port)
  152. tornado.ioloop.IOLoop.instance().start()
  153. if __name__ == "__main__":
  154. Web.main()