Compare commits
13 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
ac062aa1ba
|
|||
|
bcd45e34bf
|
|||
|
b3ee981bd1
|
|||
|
182b9a92ce
|
|||
|
fbc1870ce7
|
|||
|
edd18e92ed
|
|||
|
dc61d47b66
|
|||
|
10c3b8f5c1
|
|||
|
041b32e1df
|
|||
|
e98d923ce5
|
|||
|
01ddf25ed5
|
|||
|
4772f0179d
|
|||
|
c00dc8d33e
|
1
.gitignore
vendored
1
.gitignore
vendored
@@ -9,5 +9,6 @@ output/
|
||||
*.m3u8
|
||||
*.json
|
||||
*.ini
|
||||
iptvc
|
||||
|
||||
!/**/*.gitkeep
|
||||
|
||||
18
README.md
18
README.md
@@ -4,16 +4,17 @@
|
||||
|
||||
Консольная программа для проверки IPTV-плейлистов в формате m3u или m3u8.
|
||||
|
||||
> [!IMPORTANT]
|
||||
> Проект находится на ранней стадии разработки.
|
||||
> Реализован минимально необходимый функционал.
|
||||
> Возможны ошибки, неточности и обратно несовместимые изменения.
|
||||
|
||||
Для дополнительной документации можно обращаться в директорию [docs](./docs).
|
||||
> **Веб-сайт:** [m3u.su](https://m3u.su)
|
||||
> Исходный код: [git.axenov.dev/IPTV/iptvc](https://git.axenov.dev/IPTV/iptvc)
|
||||
> Telegram-канал: [@iptv_aggregator](https://t.me/iptv_aggregator)
|
||||
> Обсуждение: [@iptv_aggregator_chat](https://t.me/iptv_aggregator_chat)
|
||||
> Дополнительные сведения:
|
||||
> * [./docs](./docs)
|
||||
> * [git.axenov.dev/IPTV/.profile](https://git.axenov.dev/IPTV/.profile)
|
||||
|
||||
## Установка
|
||||
|
||||
Достаточно скачать и распаковать архив с подходящим исполняемым файлом [со страницы релизов](https://git.axenov.dev/IPTV/iptvc/releases):
|
||||
Достаточно скачать и распаковать архив с подходящим исполняемым файлом [со страницы последнего релиза](https://git.axenov.dev/IPTV/iptvc/releases/latest):
|
||||
|
||||
| ОС | Архив | Платформа |
|
||||
|---------|----------------------|-----------|
|
||||
@@ -62,10 +63,13 @@
|
||||
2. Выполнить команду `./iptvc check` или `./iptvc check -i playlist.ini` для проверки всех плейлистов из файла `./playlists.ini`
|
||||
3. Выполнить команду `./iptvc check -i test.ini -c ABC`, чтобы проверить только плейлист с кодом `ABC` из файла `./test.ini`
|
||||
|
||||
Если `-i` не указан явно, то будет попытка прочитать файл `playlists.ini`, находящийся в одной директории с iptvc.
|
||||
|
||||
Аргумент `-i` можно указывать только однажды, но его можно комбинировать с `-f` и `-u`.
|
||||
|
||||
### Другие возможности команды `check`
|
||||
|
||||
* `--random|-r X` -- проверить X случайных плейлистов из ini-файла
|
||||
* `--json|-j` -- вывести результаты проверки в формате JSON
|
||||
* `--quiet|-q` -- полностью подавить вывод лога (включая отладочную информацию)
|
||||
* `--verbose|-v` -- добавить в лог более подробную отладочную информацию (значительно увеличит количество строк!)
|
||||
|
||||
@@ -10,10 +10,11 @@ import (
|
||||
"axenov/iptv-checker/app/cache"
|
||||
"axenov/iptv-checker/app/config"
|
||||
"axenov/iptv-checker/app/logger"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
const VERSION = "1.0.2"
|
||||
const VERSION = "1.0.5"
|
||||
|
||||
// Arguments описывает аргументы командной строки
|
||||
type Arguments struct {
|
||||
|
||||
14
app/cache/cache.go
vendored
14
app/cache/cache.go
vendored
@@ -10,28 +10,30 @@ import (
|
||||
"axenov/iptv-checker/app/config"
|
||||
"context"
|
||||
"fmt"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"log"
|
||||
"strconv"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
func Init(cfg *config.CacheConfig) *redis.Client {
|
||||
redis := redis.NewClient(&redis.Options{
|
||||
Addr: fmt.Sprintf("%s:%s", cfg.Host, strconv.Itoa(int(cfg.Port))),
|
||||
redisUrl := fmt.Sprintf("%s:%s", cfg.Host, strconv.Itoa(int(cfg.Port)))
|
||||
redisClient := redis.NewClient(&redis.Options{
|
||||
Addr: redisUrl,
|
||||
DB: int(cfg.Db),
|
||||
PoolSize: 1000,
|
||||
ReadTimeout: -1,
|
||||
WriteTimeout: -1,
|
||||
})
|
||||
client := redis.Conn()
|
||||
client := redisClient.Conn()
|
||||
ctx := context.Background()
|
||||
err := client.Ping(ctx).Err()
|
||||
if err == nil {
|
||||
log.Println("Connected to cache DB")
|
||||
log.Println("Connected to cache DB:", redisUrl)
|
||||
cfg.IsActive = true
|
||||
} else {
|
||||
log.Println("Error while connecting to cache DB, program may work not as expected:", err)
|
||||
}
|
||||
|
||||
return redis
|
||||
return redisClient
|
||||
}
|
||||
|
||||
@@ -22,7 +22,6 @@ import (
|
||||
"math/rand"
|
||||
"net/http"
|
||||
"os"
|
||||
"runtime"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -166,7 +165,10 @@ func CheckPlaylists(lists []playlist.Playlist) (int, int) {
|
||||
}
|
||||
|
||||
func cachePlaylist(pls playlist.Playlist) {
|
||||
if app.Config.Cache.IsActive {
|
||||
if !app.Config.Cache.IsActive {
|
||||
return
|
||||
}
|
||||
|
||||
jsonBytes, err := json.Marshal(pls)
|
||||
if err != nil {
|
||||
log.Printf("Error while saving playlist to cache: %s", err)
|
||||
@@ -179,7 +181,6 @@ func cachePlaylist(pls playlist.Playlist) {
|
||||
}
|
||||
|
||||
log.Println("Cached sucessfully")
|
||||
}
|
||||
}
|
||||
|
||||
// CheckChannels проверяет каналы и возвращает их же с результатами проверки
|
||||
@@ -217,16 +218,16 @@ func CheckChannels(pls playlist.Playlist) playlist.Playlist {
|
||||
|
||||
http.DefaultTransport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
|
||||
req, err := http.NewRequest("GET", tvChannel.URL, nil)
|
||||
tvChannel.CheckedAt = time.Now().Unix()
|
||||
if err != nil {
|
||||
data := errorData{tvChannel: tvChannel, err: err}
|
||||
chError <- data
|
||||
return
|
||||
}
|
||||
|
||||
//TODO user-agent
|
||||
req.Header.Set("User-Agent", "Mozilla/5.0 WINK/1.31.1 (AndroidTV/9) HlsWinkPlayer")
|
||||
req.Header.Set("Range", "bytes=0-511") // 512 B, but sometimes servers ignore it
|
||||
resp, err := httpClient.Do(req)
|
||||
tvChannel.CheckedAt = time.Now().Unix()
|
||||
if err != nil {
|
||||
data := errorData{tvChannel: tvChannel, err: err}
|
||||
chError <- data
|
||||
@@ -236,7 +237,8 @@ func CheckChannels(pls playlist.Playlist) playlist.Playlist {
|
||||
tvChannel.Status = resp.StatusCode
|
||||
tvChannel.IsOnline = tvChannel.Status < http.StatusBadRequest
|
||||
tvChannel.ContentType = resp.Header.Get("Content-Type")
|
||||
bodyBytes, _ := io.ReadAll(resp.Body)
|
||||
chunk := io.LimitReader(resp.Body, 512) // just for sure
|
||||
bodyBytes, _ := io.ReadAll(chunk)
|
||||
bodyString := string(bodyBytes)
|
||||
_ = resp.Body.Close()
|
||||
contentType := http.DetectContentType(bodyBytes)
|
||||
@@ -246,20 +248,17 @@ func CheckChannels(pls playlist.Playlist) playlist.Playlist {
|
||||
|
||||
isContentCorrect := isContentBinary ||
|
||||
strings.Contains(bodyString, "#EXTM3U") ||
|
||||
strings.Contains(bodyString, "<SegmentTemplate")
|
||||
strings.Contains(bodyString, "#EXT-X-") ||
|
||||
strings.Contains(bodyString, "<MPD ") ||
|
||||
strings.Contains(bodyString, "<SegmentTemplate ") ||
|
||||
strings.Contains(bodyString, "<AdaptationSet ")
|
||||
|
||||
if tvChannel.Status >= http.StatusBadRequest || !isContentCorrect {
|
||||
if tvChannel.Status >= http.StatusBadRequest && !isContentCorrect {
|
||||
tvChannel.Error = bodyString
|
||||
chOffline <- tvChannel
|
||||
return
|
||||
}
|
||||
|
||||
if isContentBinary {
|
||||
tvChannel.Content = "binary"
|
||||
} else {
|
||||
tvChannel.Content = bodyString
|
||||
}
|
||||
|
||||
chOnline <- tvChannel
|
||||
return
|
||||
}(tvChannel)
|
||||
@@ -323,27 +322,22 @@ func CheckChannels(pls playlist.Playlist) playlist.Playlist {
|
||||
|
||||
// calcParameters вычисляет оптимальное количество горутин и таймаут запроса
|
||||
func calcParameters(count int) (time.Duration, int) {
|
||||
percentage := float32(runtime.NumCPU()) / 10
|
||||
for percentage >= 1 {
|
||||
percentage *= 0.5
|
||||
}
|
||||
|
||||
routines := int(float32(count) * percentage)
|
||||
if routines > 1500 {
|
||||
routines = 1500
|
||||
routines := count
|
||||
if routines > 3000 {
|
||||
routines = 3000
|
||||
}
|
||||
if routines < 1 {
|
||||
routines = 1
|
||||
}
|
||||
|
||||
var digits int
|
||||
var digits = 1
|
||||
x := count
|
||||
for x >= 10 {
|
||||
digits++
|
||||
x /= 10
|
||||
}
|
||||
|
||||
timeout := int(math.Ceil(math.Pow(10, float64(digits)) / float64(count) * 15))
|
||||
timeout := 10 - int(math.Ceil(float64(digits)*1.5))
|
||||
if timeout > 10 {
|
||||
timeout = 10
|
||||
}
|
||||
|
||||
@@ -32,7 +32,6 @@ type Channel struct {
|
||||
Status int `json:"status"` // Код статуса HTTP
|
||||
IsOnline bool `json:"isOnline"` // Признак доступности канала (при Status < 400)
|
||||
Error string `json:"error"` // Текст ошибки (при Status >= 400)
|
||||
Content string `json:"content"` // Тело ответа (формат m3u, либо маскированные бинарные данные, либо пусто)
|
||||
ContentType string `json:"contentType"` // MIME-тип тела ответа
|
||||
Tags []string `json:"tags"` // Список тегов канала
|
||||
CheckedAt int64 `json:"checkedAt"` // Время проверки в формате UNIX timestamp
|
||||
@@ -164,7 +163,7 @@ func (pls *Playlist) Parse() Playlist {
|
||||
}
|
||||
|
||||
if strings.HasPrefix(line, "#EXTM3U") {
|
||||
pls.Attributes = parseAttributes(content)
|
||||
pls.Attributes = parseAttributes(line)
|
||||
continue
|
||||
}
|
||||
|
||||
|
||||
@@ -19,6 +19,7 @@ import (
|
||||
// TagBlock описывает объект с набором тегов, который подходит для каналов по регулярному выражению
|
||||
type TagBlock struct {
|
||||
TvgId string `json:"tvg-id"`
|
||||
TvgName string `json:"tvg-name"`
|
||||
Title string `json:"title"`
|
||||
Tags []string `json:"tags"`
|
||||
}
|
||||
@@ -42,6 +43,18 @@ func (block *TagBlock) GetTags(ch playlist.Channel) []string {
|
||||
if checkString == "" {
|
||||
return result
|
||||
}
|
||||
} else if block.TvgName != "" {
|
||||
regex, err = regexp.Compile(block.TvgName)
|
||||
if err != nil {
|
||||
return result
|
||||
}
|
||||
if _, ok := ch.Attributes["tvg-name"]; !ok {
|
||||
return result
|
||||
}
|
||||
checkString = ch.Attributes["tvg-name"]
|
||||
if checkString == "" {
|
||||
return result
|
||||
}
|
||||
} else if block.Title != "" {
|
||||
regex, err = regexp.Compile(block.Title)
|
||||
if err != nil {
|
||||
|
||||
@@ -51,13 +51,9 @@ func Fetch(url string) ([]byte, error) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
req.Header.Set(
|
||||
"User-Agent",
|
||||
"Mozilla/5.0 WINK/1.31.1 (AndroidTV/9) HlsWinkPlayer",
|
||||
)
|
||||
|
||||
req.Header.Set("User-Agent", "Mozilla/5.0 WINK/1.31.1 (AndroidTV/9) HlsWinkPlayer")
|
||||
http.DefaultTransport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
|
||||
httpClient := http.Client{Timeout: 5 * time.Second}
|
||||
httpClient := http.Client{Timeout: 10 * time.Second}
|
||||
resp, err := httpClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -11,9 +11,10 @@ import (
|
||||
"axenov/iptv-checker/app/checker"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/spf13/cobra"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
// checkCmd represents the file command
|
||||
|
||||
@@ -16,8 +16,8 @@ import (
|
||||
// rootCmd represents the base command when called without any subcommands
|
||||
var rootCmd = &cobra.Command{
|
||||
Use: "iptvc",
|
||||
Short: "Simple utility to check iptv playlists. Part of iptv.axenov.dev project.",
|
||||
Long: `Simple utility to check iptv playlists. Part of iptv.axenov.dev project.
|
||||
Short: "Simple utility to check iptv playlists. Part of m3u.su project.",
|
||||
Long: `Simple utility to check iptv playlists. Part of m3u.su project.
|
||||
Copyright (c) 2025, Антон Аксенов, MIT license.`,
|
||||
// Uncomment the following line if your bare application
|
||||
// has an action associated with it:
|
||||
|
||||
Reference in New Issue
Block a user