65 lines
2.0 KiB
Python
65 lines
2.0 KiB
Python
# -*- coding: utf-8 -*-
|
|
"""
|
|
M3U Playlist Generator - Flask 应用入口
|
|
提供 M3U 播放列表的浏览、下载和订阅服务。
|
|
"""
|
|
|
|
import os
|
|
from flask import Flask, render_template, send_from_directory, abort
|
|
|
|
app = Flask(__name__)
|
|
|
|
# 播放列表目录(相对路径)
|
|
PLAYLIST_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'playlists')
|
|
|
|
|
|
@app.route('/')
|
|
def index():
|
|
"""首页:列出所有可用的播放列表。"""
|
|
playlists = []
|
|
if os.path.isdir(PLAYLIST_DIR):
|
|
for filename in sorted(os.listdir(PLAYLIST_DIR)):
|
|
if filename.endswith('.m3u'):
|
|
filepath = os.path.join(PLAYLIST_DIR, filename)
|
|
size = os.path.getsize(filepath)
|
|
# 统计频道数量(以 #EXTINF 开头的行)
|
|
channel_count = 0
|
|
try:
|
|
with open(filepath, 'r', encoding='utf-8') as f:
|
|
for line in f:
|
|
if line.strip().startswith('#EXTINF'):
|
|
channel_count += 1
|
|
except Exception:
|
|
pass
|
|
playlists.append({
|
|
'name': filename,
|
|
'size': size,
|
|
'channels': channel_count,
|
|
'url': f'playlists/{filename}'
|
|
})
|
|
return render_template('index.html', playlists=playlists)
|
|
|
|
|
|
@app.route('/playlists/<path:filename>')
|
|
def serve_playlist(filename):
|
|
"""提供播放列表文件下载/订阅。"""
|
|
# 安全检查:防止路径穿越
|
|
if '..' in filename or filename.startswith('/'):
|
|
abort(400)
|
|
if not filename.endswith('.m3u'):
|
|
abort(404)
|
|
filepath = os.path.join(PLAYLIST_DIR, filename)
|
|
if not os.path.isfile(filepath):
|
|
abort(404)
|
|
return send_from_directory(
|
|
PLAYLIST_DIR,
|
|
filename,
|
|
mimetype='audio/x-mpegurl',
|
|
as_attachment=False
|
|
)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
# 监听所有网卡,方便局域网内其他设备订阅
|
|
app.run(host='0.0.0.0', port=5000, debug=True)
|