/** * 视频播放地址处理工具函数(TypeScript版本) * 用于前端处理HTTP资源在HTTPS网站中的访问问题 * * 使用方法: * import { getVideoPlayUrl, processVideoList } from './video-url-helper' * * const playUrl = getVideoPlayUrl('http://example.com/video.m3u8') */ export interface VideoItem { id: number title: string m3u8: string image?: string [key: string]: any } export interface VideoUrlOptions { baseUrl?: string forceProxy?: boolean } /** * 获取视频播放地址(自动处理HTTP资源) * @param m3u8Url 后端返回的m3u8地址 * @param options 配置选项 * @returns 处理后的播放地址 */ export function getVideoPlayUrl( m3u8Url: string, options: VideoUrlOptions = {} ): string { if (!m3u8Url || typeof m3u8Url !== 'string') { return m3u8Url } try { const url = new URL(m3u8Url) const baseUrl = options.baseUrl || window.location.origin // 强制使用代理 if (options.forceProxy) { const path = url.pathname + url.search + url.hash return `${baseUrl}/api/proxy/m3u8${path}` } // HTTPS直接使用 if (url.protocol === 'https:') { return m3u8Url } // HTTP转换为代理地址 if (url.protocol === 'http:') { const path = url.pathname + url.search + url.hash return `${baseUrl}/api/proxy/m3u8${path}` } // 其他情况,直接返回 return m3u8Url } catch (error) { console.warn('处理视频地址失败:', error, m3u8Url) return m3u8Url } } /** * 批量处理视频列表的播放地址 * @param videos 视频列表数组 * @param options 配置选项 * @returns 处理后的视频列表 */ export function processVideoList( videos: T[], options: VideoUrlOptions = {} ): T[] { if (!Array.isArray(videos)) { return videos } return videos.map(video => { if (video.m3u8) { return { ...video, m3u8: getVideoPlayUrl(video.m3u8, options) } } return video }) } /** * 检查地址是否需要代理 * @param m3u8Url m3u8地址 * @returns 是否需要代理 */ export function needsProxy(m3u8Url: string): boolean { if (!m3u8Url || typeof m3u8Url !== 'string') { return false } try { const url = new URL(m3u8Url) return url.protocol === 'http:' } catch { return false } } /** * 默认导出(方便使用) */ export default { getVideoPlayUrl, processVideoList, needsProxy }