LoremPizza commited on
Commit
1924ff2
·
verified ·
1 Parent(s): 9423834

Update wltv_server.py

Browse files
Files changed (1) hide show
  1. wltv_server.py +71 -46
wltv_server.py CHANGED
@@ -1,14 +1,15 @@
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,39 +18,40 @@ extract_to_dir = 'extracted'
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
@@ -75,12 +77,21 @@ def get_current_program(channel_id="skytg24"):
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,7 +99,30 @@ def serve_extracted_file():
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")
@@ -97,22 +131,13 @@ def current_skytg24_program():
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)
 
1
  import os
2
  import requests
3
+ import gzip
4
+ import shutil
5
  import logging
6
+ from flask import Flask, send_file, jsonify
7
  import xml.etree.ElementTree as ET
8
  from datetime import datetime
9
 
10
  # Set up logging
11
  logging.basicConfig(level=logging.INFO)
12
+ logger = logging.getLogger(__name__)
13
 
14
  app = Flask(__name__)
15
 
 
18
  if not os.path.exists(extract_to_dir):
19
  os.makedirs(extract_to_dir, exist_ok=True)
20
 
21
+ # Function to download the file
22
+ def download_file(url, output_path):
23
  logger.info(f"Downloading from {url}...")
24
  try:
25
  response = requests.get(url)
26
+ if response.status_code == 200:
27
+ with open(output_path, 'wb') as f:
28
+ f.write(response.content)
29
+ logger.info(f"Downloaded file to {output_path} with size {len(response.content)} bytes")
30
+ else:
31
+ logger.error(f"Failed to download file. Status code: {response.status_code}")
32
+ except PermissionError as e:
33
+ logger.error(f"Permission error occurred while downloading the file: {e}")
34
+ except Exception as e:
35
  logger.error(f"An error occurred while downloading the file: {e}")
36
 
37
+ # Function to extract .gz files
38
+ def extract_gz_file(gz_path, extract_to_dir):
39
+ logger.info(f"Extracting {gz_path} to {extract_to_dir}...")
40
+ if not os.path.exists(gz_path):
41
+ logger.error(f"GZ file does not exist: {gz_path}")
42
+ return
43
  try:
44
+ extracted_file_path = os.path.join(extract_to_dir, 'it_wltv_full.xml') # Updated file extension
45
+ with gzip.open(gz_path, 'rb') as f_in:
46
+ with open(extracted_file_path, 'wb') as f_out:
47
+ shutil.copyfileobj(f_in, f_out)
48
+ logger.info(f"Extracted GZ file to {extracted_file_path}")
 
 
 
 
 
 
49
  except Exception as e:
50
  logger.error(f"An error occurred while extracting the file: {e}")
51
 
52
+ # Function to get the current program for Sky TG24
53
  def get_current_program(channel_id="skytg24"):
54
+ xml_file = os.path.join(extract_to_dir, 'it_wltv_full.xml')
55
  if not os.path.exists(xml_file):
56
  logger.error("XML file does not exist for program data")
57
  return None
 
77
  logger.error(f"Failed to parse XML file: {e}")
78
  return None
79
 
80
+ # Flask route to serve the extracted file
81
  @app.route('/wltv', methods=['GET'])
82
  def serve_extracted_file():
83
+ try:
84
+ extracted_files = os.listdir(extract_to_dir)
85
+ logger.info(f"Files in 'extracted' directory: {extracted_files}")
86
+ for file_name in extracted_files:
87
+ logger.info(f"File: {file_name}, Extension: {os.path.splitext(file_name)[1]}")
88
+ except Exception as e:
89
+ logger.error(f"Error listing files in 'extracted' directory: {e}")
90
+ return "Error listing files", 500
91
+
92
+ file_name = 'it_wltv_full.xml' # Updated file name with extension
93
  file_path = os.path.join(extract_to_dir, file_name)
94
+
95
  if os.path.exists(file_path):
96
  logger.info(f"Serving file from {file_path}")
97
  return send_file(file_path, as_attachment=False, mimetype='text/plain')
 
99
  logger.error("File not found")
100
  return "File not found", 404
101
 
102
+ # Route to fetch logs
103
+ @app.route('/logs', methods=['GET'])
104
+ def get_logs():
105
+ try:
106
+ with open('app.log', 'r') as log_file:
107
+ logs = log_file.read()
108
+ return logs, 200
109
+ except Exception as e:
110
+ logger.error(f"Failed to read logs: {e}")
111
+ return jsonify({"error": "Failed to read logs"}), 500
112
+
113
+ # Route to update (download and extract again)
114
+ @app.route('/update', methods=['POST'])
115
+ def update_files():
116
+ file_url = 'http://epg-guide.com/wltv.gz'
117
+ file_path = '/tmp/it_wltv_full.gz'
118
+
119
+ # Download and extract the gz file
120
+ download_file(file_url, file_path)
121
+ extract_gz_file(file_path, extract_to_dir)
122
+
123
+ return "Files updated", 200
124
+
125
+ # Route to serve the current program on Sky TG24
126
  @app.route('/skytg24/now', methods=['GET'])
127
  def current_skytg24_program():
128
  program_info = get_current_program("skytg24")
 
131
  else:
132
  return "No current program found for Sky TG24.", 404
133
 
134
+ if __name__ == '__main__':
135
+ file_url = 'http://epg-guide.com/wltv.gz'
136
+ file_path = '/tmp/it_wltv_full.gz'
 
 
 
 
 
 
 
 
137
 
138
+ # Download and extract the gz file initially
139
+ download_file(file_url, file_path)
140
+ extract_gz_file(file_path, extract_to_dir)
 
141
 
142
+ # Start the Flask web server
143
  app.run(host='0.0.0.0', port=8080)