that_one_nigga_you_k

servidor final

Jun 6th, 2025
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.25 KB | None | 0 0
  1. import http.server
  2. import socketserver
  3. import os
  4. import json
  5.  
  6. # NOTA: O módulo 'cgi' não é mais necessário com esta abordagem.
  7.  
  8. # --- Configurações do Servidor ---
  9. PORT = 5000
  10. UPLOAD_DIR = 'uploads'
  11.  
  12. # --- Variável Global ---
  13. flash_command = 'FLASH_OFF'
  14.  
  15. # Garante que o diretório de uploads existe.
  16. if not os.path.exists(UPLOAD_DIR):
  17.     os.makedirs(UPLOAD_DIR)
  18.  
  19. class MyHttpRequestHandler(http.server.BaseHTTPRequestHandler):
  20.     def write_response(self, data):
  21.         try:
  22.             self.wfile.write(data)
  23.         except BrokenPipeError:
  24.             print("AVISO: BrokenPipeError - Cliente desconectou.")
  25.  
  26.     def do_GET(self):
  27.         # As rotas GET permanecem as mesmas
  28.         if self.path == '/':
  29.             self.send_response(200)
  30.             self.send_header('Content-type', 'text/html')
  31.             self.end_headers()
  32.             with open('index3.html', 'rb') as f:
  33.                 self.write_response(f.read())
  34.         elif self.path.startswith('/latest-photo'):
  35.             photo_path = os.path.join(UPLOAD_DIR, 'latest.jpg')
  36.             if os.path.exists(photo_path):
  37.                 self.send_response(200)
  38.                 self.send_header('Content-type', 'image/jpeg')
  39.                 self.end_headers()
  40.                 with open(photo_path, 'rb') as f:
  41.                     self.write_response(f.read())
  42.             else:
  43.                 self.send_error(404, 'Foto não encontrada.')
  44.         elif self.path == '/command':
  45.             self.send_response(200)
  46.             self.send_header('Content-type', 'text/plain')
  47.             self.end_headers()
  48.             self.write_response(flash_command.encode('utf-8'))
  49.         else:
  50.             self.send_error(404, 'Página não encontrada.')
  51.  
  52.     def do_POST(self):
  53.         global flash_command
  54.         try:
  55.             # --- NOVA ROTA PARA UPLOAD DIRETO (RAW) ---
  56.             if self.path == '/raw_upload':
  57.                 content_length = int(self.headers['Content-Length'])
  58.                
  59.                 # Lê exatamente o número de bytes especificado no cabeçalho
  60.                 image_data = self.rfile.read(content_length)
  61.  
  62.                 # Verifica se a quantidade de dados recebida é a esperada
  63.                 if len(image_data) == content_length:
  64.                     file_path = os.path.join(UPLOAD_DIR, 'latest.jpg')
  65.                     with open(file_path, 'wb') as f:
  66.                         f.write(image_data)
  67.                     print(f"SUCESSO (RAW): Foto recebida ({len(image_data)} bytes) e salva.")
  68.                    
  69.                     self.send_response(200)
  70.                     self.send_header('Content-type', 'application/json')
  71.                     self.end_headers()
  72.                     response = {'status': 'success', 'message': 'Upload raw bem-sucedido!'}
  73.                     self.write_response(json.dumps(response).encode('utf-8'))
  74.                 else:
  75.                     print(f"ERRO: Upload incompleto. Esperado: {content_length}, Recebido: {len(image_data)}")
  76.                     self.send_error(400, 'Upload incompleto.')
  77.            
  78.             # A rota de comando continua a mesma
  79.             elif self.path == '/command':
  80.                 content_length = int(self.headers['Content-Length'])
  81.                 post_data = self.rfile.read(content_length)
  82.                 data = json.loads(post_data.decode('utf-8'))
  83.                 command = data.get('command')
  84.                 if command in ['FLASH_ON', 'FLASH_OFF']:
  85.                     flash_command = command
  86.                     self.send_response(200)
  87.                     self.send_header('Content-type', 'application/json')
  88.                     self.end_headers()
  89.                     response = {'message': 'Comando atualizado!', 'newCommand': flash_command}
  90.                     self.write_response(json.dumps(response).encode('utf-8'))
  91.                 else:
  92.                     self.send_error(400, 'Comando invalido.')
  93.  
  94.         except Exception as e:
  95.             print(f"ERRO INESPERADO no POST: {e}")
  96.             self.send_error(500, 'Erro interno do servidor')
  97.  
  98. if __name__ == "__main__":
  99.     with socketserver.TCPServer(("", PORT), MyHttpRequestHandler) as httpd:
  100.         print(f"Servidor Python (com Upload RAW) rodando na porta {PORT}")
  101.         httpd.serve_forever()
  102.  
Add Comment
Please, Sign In to add comment