Coverage for src/iptvtools/parsers.py: 38%

26 statements  

« prev     ^ index     » next       coverage.py v7.6.10, created at 2025-01-31 13:48 +0000

1#!/usr/bin/env python 

2"""Simplified parser for m3u8 file. 

3 

4File: parser.py 

5Author: huxuan 

6Email: i(at)huxuan.org 

7""" 

8 

9import os.path 

10import re 

11import tempfile 

12from collections.abc import Iterator 

13from typing import Any 

14 

15import requests 

16 

17from iptvtools.constants import patterns 

18 

19 

20def parse_content_to_lines(content: str, timeout: int | None = None) -> Iterator[str]: 

21 """Universal interface to split content into lines.""" 

22 if os.path.isfile(content): 

23 with open(content, encoding="utf-8") as fp: 

24 for line in fp: 

25 yield re.sub(r"[^\S ]+", "", line.strip()) 

26 else: 

27 with tempfile.TemporaryFile(mode="w+t") as fp: 

28 fp.write(requests.get(content, timeout=timeout).text) 

29 fp.seek(0) 

30 for line in fp: 

31 yield re.sub(r"[^\S ]+", "", line.strip()) 

32 

33 

34def parse_tag_inf(line: str) -> dict[str, Any]: 

35 """Parse INF content.""" 

36 match = patterns.EXTINF.fullmatch(line) 

37 res = match and match.groupdict() or {} 

38 if "params" in res: 

39 res["params"] = dict(patterns.PARAMS.findall(res["params"])) 

40 return res 

41 

42 

43def parse_tag_m3u(line: str) -> dict[str, Any]: 

44 """Parse M3U content.""" 

45 match = patterns.EXTM3U.fullmatch(line) 

46 return match and match.groupdict() or {}