begin working on M3U parser. came up with very good regex to extract extinf data
This commit is contained in:
parent
0439b78b6b
commit
fbec61ffa5
2 changed files with 82 additions and 0 deletions
64
src/main/java/com/mykola2312/mptv/parser/M3U.java
Normal file
64
src/main/java/com/mykola2312/mptv/parser/M3U.java
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
package com.mykola2312.mptv.parser;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Scanner;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
|
||||
import com.mykola2312.mptv.parser.M3UException.Type;
|
||||
|
||||
public class M3U {
|
||||
public class Item {
|
||||
@NonNull
|
||||
public String title;
|
||||
|
||||
public String groupTitle;
|
||||
public String tvgLogo;
|
||||
|
||||
@NonNull
|
||||
public String url;
|
||||
}
|
||||
|
||||
public ArrayList<Item> items = new ArrayList<>();
|
||||
|
||||
public M3U(ArrayList<Item> items) {
|
||||
this.items = items;
|
||||
}
|
||||
|
||||
private static final Pattern HEADER = Pattern.compile("^#EXTM3U");
|
||||
private static final Pattern EXTINF = Pattern.compile("^(?:#EXTINF:-?\\d\\s*)(.*?),(.*)$");
|
||||
|
||||
public static M3U parse(String data) throws M3UException {
|
||||
ArrayList<Item> items = new ArrayList<>();
|
||||
|
||||
// state
|
||||
boolean headerLine = true;
|
||||
|
||||
try (Scanner scanner = new Scanner(data)) {
|
||||
while (scanner.hasNextLine()) {
|
||||
String line = scanner.nextLine();
|
||||
|
||||
if (headerLine) {
|
||||
Matcher matcher = HEADER.matcher(line);
|
||||
if (!matcher.find()) {
|
||||
throw new M3UException(Type.NOT_AN_M3U);
|
||||
}
|
||||
|
||||
headerLine = false;
|
||||
} else {
|
||||
Matcher matcher = EXTINF.matcher(line);
|
||||
if (matcher.find()) {
|
||||
String tags = matcher.group(1);
|
||||
String title = matcher.group(2);
|
||||
|
||||
System.out.printf("tags: %s | title: %s\n", tags, title);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return new M3U(items);
|
||||
}
|
||||
}
|
||||
18
src/main/java/com/mykola2312/mptv/parser/M3UException.java
Normal file
18
src/main/java/com/mykola2312/mptv/parser/M3UException.java
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
package com.mykola2312.mptv.parser;
|
||||
|
||||
public class M3UException extends RuntimeException {
|
||||
public enum Type {
|
||||
NOT_AN_M3U
|
||||
};
|
||||
|
||||
private static String typeToString(Type type) {
|
||||
switch (type) {
|
||||
case NOT_AN_M3U: return "not an m3u";
|
||||
default: return type.toString();
|
||||
}
|
||||
}
|
||||
|
||||
public M3UException(Type type) {
|
||||
super(typeToString(type));
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Reference in a new issue