LoremPizza commited on
Commit
9423834
·
verified ·
1 Parent(s): 544ebd6

Update wltv_server.py

Browse files
Files changed (1) hide show
  1. wltv_server.py +77 -63
wltv_server.py CHANGED
@@ -1,13 +1,14 @@
1
  import os
2
  import requests
3
- import gzip
4
- import shutil
5
  import logging
6
- from flask import Flask, send_file, jsonify
 
 
7
 
8
  # Set up logging
9
  logging.basicConfig(level=logging.INFO)
10
- logger = logging.getLogger(__name__)
11
 
12
  app = Flask(__name__)
13
 
@@ -16,52 +17,70 @@ extract_to_dir = 'extracted'
16
  if not os.path.exists(extract_to_dir):
17
  os.makedirs(extract_to_dir, exist_ok=True)
18
 
19
- # Function to download the file
20
- def download_file(url, output_path):
21
  logger.info(f"Downloading from {url}...")
22
  try:
23
  response = requests.get(url)
24
- if response.status_code == 200:
25
- with open(output_path, 'wb') as f:
26
- f.write(response.content)
27
- logger.info(f"Downloaded file to {output_path} with size {len(response.content)} bytes")
28
- else:
29
- logger.error(f"Failed to download file. Status code: {response.status_code}")
30
- except PermissionError as e:
31
- logger.error(f"Permission error occurred while downloading the file: {e}")
32
- except Exception as e:
33
  logger.error(f"An error occurred while downloading the file: {e}")
34
 
35
- # Function to extract .gz files
36
- def extract_gz_file(gz_path, extract_to_dir):
37
- logger.info(f"Extracting {gz_path} to {extract_to_dir}...")
38
- if not os.path.exists(gz_path):
39
- logger.error(f"GZ file does not exist: {gz_path}")
40
- return
41
  try:
42
- extracted_file_path = os.path.join(extract_to_dir, 'it_wltv_full')
43
- with gzip.open(gz_path, 'rb') as f_in:
44
- with open(extracted_file_path, 'wb') as f_out:
45
- shutil.copyfileobj(f_in, f_out)
46
- logger.info(f"Extracted GZ file to {extracted_file_path}")
 
 
 
 
 
 
47
  except Exception as e:
48
  logger.error(f"An error occurred while extracting the file: {e}")
49
 
50
- # Flask route to serve the extracted file
51
- @app.route('/wltv', methods=['GET'])
52
- def serve_extracted_file():
 
 
 
 
53
  try:
54
- extracted_files = os.listdir(extract_to_dir)
55
- logger.info(f"Files in 'extracted' directory: {extracted_files}")
56
- for file_name in extracted_files:
57
- logger.info(f"File: {file_name}, Extension: {os.path.splitext(file_name)[1]}")
 
 
 
 
 
 
 
 
 
 
 
 
58
  except Exception as e:
59
- logger.error(f"Error listing files in 'extracted' directory: {e}")
60
- return "Error listing files", 500
61
-
 
 
 
62
  file_name = 'it_wltv_full' # Update this based on actual file name if needed
63
  file_path = os.path.join(extract_to_dir, file_name)
64
-
65
  if os.path.exists(file_path):
66
  logger.info(f"Serving file from {file_path}")
67
  return send_file(file_path, as_attachment=False, mimetype='text/plain')
@@ -69,36 +88,31 @@ def serve_extracted_file():
69
  logger.error("File not found")
70
  return "File not found", 404
71
 
72
- # Route to fetch logs
73
- @app.route('/logs', methods=['GET'])
74
- def get_logs():
75
- try:
76
- with open('app.log', 'r') as log_file:
77
- logs = log_file.read()
78
- return logs, 200
79
- except Exception as e:
80
- logger.error(f"Failed to read logs: {e}")
81
- return jsonify({"error": "Failed to read logs"}), 500
82
 
83
- # Route to update (download and extract again)
84
  @app.route('/update', methods=['POST'])
85
- def update_files():
86
- file_url = 'http://epg-guide.com/wltv.gz'
87
- file_path = '/tmp/it_wltv_full.gz'
88
 
89
- # Download and extract the gz file
90
- download_file(file_url, file_path)
91
- extract_gz_file(file_path, extract_to_dir)
92
 
93
- return "Files updated", 200
94
 
95
- if __name__ == '__main__':
96
- file_url = 'http://epg-guide.com/wltv.gz'
97
- file_path = '/tmp/it_wltv_full.gz'
98
-
99
- # Download and extract the gz file initially
100
- download_file(file_url, file_path)
101
- extract_gz_file(file_path, extract_to_dir)
102
 
103
- # Start the Flask web server
104
  app.run(host='0.0.0.0', port=8080)
 
1
  import os
2
  import requests
3
+ import zipfile
 
4
  import logging
5
+ from flask import Flask, send_file, jsonify, Response
6
+ import xml.etree.ElementTree as ET
7
+ from datetime import datetime
8
 
9
  # Set up logging
10
  logging.basicConfig(level=logging.INFO)
11
+ logger = logging.getLogger('wltv_server')
12
 
13
  app = Flask(__name__)
14
 
 
17
  if not os.path.exists(extract_to_dir):
18
  os.makedirs(extract_to_dir, exist_ok=True)
19
 
20
+ # Step 1: Download the zip file
21
+ def download_zip_file(url, output_path):
22
  logger.info(f"Downloading from {url}...")
23
  try:
24
  response = requests.get(url)
25
+ response.raise_for_status() # Raise an error for bad responses
26
+ with open(output_path, 'wb') as f:
27
+ f.write(response.content)
28
+ logger.info(f"Downloaded zip file to {output_path} with size {len(response.content)} bytes")
29
+ except requests.RequestException as e:
 
 
 
 
30
  logger.error(f"An error occurred while downloading the file: {e}")
31
 
32
+ # Step 2: Extract the file from the zip file
33
+ def extract_file(zip_path, extract_to_dir):
34
+ logger.info(f"Extracting {zip_path} to {extract_to_dir}...")
 
 
 
35
  try:
36
+ if not os.path.exists(zip_path):
37
+ raise FileNotFoundError(f"Zip file does not exist: {zip_path}")
38
+ with zipfile.ZipFile(zip_path, 'r') as zip_ref:
39
+ zip_ref.extractall(extract_to_dir)
40
+ # Log extracted files and their extensions
41
+ extracted_files = zip_ref.namelist()
42
+ logger.info(f"Extracted files: {extracted_files}")
43
+ for file in extracted_files:
44
+ logger.info(f"File: {file}, Extension: {os.path.splitext(file)[1]}")
45
+ except zipfile.BadZipFile:
46
+ logger.error("The downloaded file is not a zip file or is corrupted.")
47
  except Exception as e:
48
  logger.error(f"An error occurred while extracting the file: {e}")
49
 
50
+ # New function to get current program on Sky TG24
51
+ def get_current_program(channel_id="skytg24"):
52
+ xml_file = os.path.join(extract_to_dir, 'it_wltv_full') # Assuming this is the file name
53
+ if not os.path.exists(xml_file):
54
+ logger.error("XML file does not exist for program data")
55
+ return None
56
+
57
  try:
58
+ tree = ET.parse(xml_file)
59
+ root = tree.getroot()
60
+
61
+ # Get the current time
62
+ current_time = datetime.now()
63
+
64
+ for programme in root.findall('programme'):
65
+ if programme.get('channel') == channel_id:
66
+ start_time = datetime.strptime(programme.get('start')[:14], "%Y%m%d%H%M%S")
67
+ stop_time = datetime.strptime(programme.get('stop')[:14], "%Y%m%d%H%M%S")
68
+ if start_time <= current_time < stop_time:
69
+ title = programme.find('title').text
70
+ desc = programme.find('desc').text
71
+ return {"title": title, "description": desc}
72
+ logger.info("No current program found for Sky TG24.")
73
+ return None
74
  except Exception as e:
75
+ logger.error(f"Failed to parse XML file: {e}")
76
+ return None
77
+
78
+ # Step 3: Set up a Flask route to expose the extracted file
79
+ @app.route('/wltv', methods=['GET'])
80
+ def serve_extracted_file():
81
  file_name = 'it_wltv_full' # Update this based on actual file name if needed
82
  file_path = os.path.join(extract_to_dir, file_name)
83
+
84
  if os.path.exists(file_path):
85
  logger.info(f"Serving file from {file_path}")
86
  return send_file(file_path, as_attachment=False, mimetype='text/plain')
 
88
  logger.error("File not found")
89
  return "File not found", 404
90
 
91
+ # New route to serve what's currently on Sky TG24
92
+ @app.route('/skytg24/now', methods=['GET'])
93
+ def current_skytg24_program():
94
+ program_info = get_current_program("skytg24")
95
+ if program_info:
96
+ return jsonify(program_info)
97
+ else:
98
+ return "No current program found for Sky TG24.", 404
 
 
99
 
100
+ # Step 4: Set up a Flask route to trigger the update (download and extract)
101
  @app.route('/update', methods=['POST'])
102
+ def update_wltv():
103
+ zip_url = 'http://epg-guide.com/wltv.gz'
104
+ zip_path = '/tmp/it_wltv_full.zip'
105
 
106
+ # Download and extract the zip file
107
+ download_zip_file(zip_url, zip_path)
108
+ extract_file(zip_path, extract_to_dir)
109
 
110
+ return "Update complete", 200
111
 
112
+ # Set up a Flask route to serve the logs
113
+ @app.route('/logs', methods=['GET'])
114
+ def serve_logs():
115
+ return Response(log_stream.getvalue(), mimetype='text/plain')
 
 
 
116
 
117
+ if __name__ == '__main__':
118
  app.run(host='0.0.0.0', port=8080)