Files
goyomi/sources/base/mangotheme/mangotheme.go
T
2026-05-11 06:48:23 +00:00

257 lines
7.7 KiB
Go
Executable File

// Package mangotheme implements the MangoTheme Brazilian manga base.
// JSON REST + AES/CBC decryption on all API responses.
package mangotheme
import (
"bytes"
"context"
"crypto/aes"
"crypto/cipher"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"goyomi/internal/httpclient"
"goyomi/internal/source"
"goyomi/sources/base/util"
)
type Config struct {
Name string
BaseURL string
Lang string
EncryptionKey string
APIPath string // defaults to "/api"
}
type Source struct {
cfg Config
client *httpclient.Client
id int64
}
func New(cfg Config) *Source {
if cfg.APIPath == "" {
cfg.APIPath = "/api"
}
c := httpclient.NewClient(httpclient.WithRateLimit(2, 1))
return &Source{cfg: cfg, client: c, id: source.GenerateSourceID(cfg.Name, cfg.Lang)}
}
func (s *Source) ID() int64 { return s.id }
func (s *Source) Name() string { return s.cfg.Name }
func (s *Source) Lang() string { return s.cfg.Lang }
func (s *Source) SupportsLatest() bool { return true }
func (s *Source) apiBase() string {
return strings.TrimRight(s.cfg.BaseURL, "/") + s.cfg.APIPath
}
// decrypt decrypts a MangoTheme payload: format "{iv_hex}:{ciphertext_hex}"
// with AES-256-CBC, key derived as SHA-256(encryptionKey+"salt").
func (s *Source) decrypt(payload string) (string, error) {
payload = strings.TrimSpace(payload)
if strings.HasPrefix(payload, "{") || strings.HasPrefix(payload, "[") {
return payload, nil
}
parts := strings.SplitN(payload, ":", 2)
if len(parts) != 2 {
return "", fmt.Errorf("mangotheme: invalid encrypted payload")
}
keyHash := sha256.Sum256([]byte(s.cfg.EncryptionKey + "salt"))
iv, err := hex.DecodeString(parts[0])
if err != nil {
return "", fmt.Errorf("mangotheme: bad iv: %w", err)
}
ciphertext, err := hex.DecodeString(parts[1])
if err != nil {
return "", fmt.Errorf("mangotheme: bad ciphertext: %w", err)
}
block, err := aes.NewCipher(keyHash[:])
if err != nil {
return "", err
}
if len(ciphertext)%aes.BlockSize != 0 {
return "", fmt.Errorf("mangotheme: ciphertext not block-aligned")
}
cipher.NewCBCDecrypter(block, iv).CryptBlocks(ciphertext, ciphertext)
// PKCS7 unpad
if len(ciphertext) == 0 {
return "", fmt.Errorf("mangotheme: empty after decrypt")
}
pad := int(ciphertext[len(ciphertext)-1])
if pad == 0 || pad > aes.BlockSize {
return "", fmt.Errorf("mangotheme: invalid padding")
}
return string(ciphertext[:len(ciphertext)-pad]), nil
}
func (s *Source) getJSON(ctx context.Context, rawURL string, out any) error {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil)
if err != nil {
return err
}
req.Header.Set("Accept", "application/json")
req.Header.Set("Referer", s.cfg.BaseURL+"/")
resp, err := s.client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("mangotheme: HTTP %d", resp.StatusCode)
}
raw, _ := io.ReadAll(resp.Body)
body := string(raw)
if s.cfg.EncryptionKey != "" {
body, err = s.decrypt(body)
if err != nil {
return err
}
}
return json.NewDecoder(bytes.NewReader([]byte(body))).Decode(out)
}
type mangaDTO struct {
ID int `json:"id"`
Slug string `json:"slug"`
Title string `json:"title"`
Cover string `json:"cover"`
Synopsis string `json:"synopsis"`
Author string `json:"author"`
Status string `json:"status"`
Tags []struct{ Name string `json:"name"` } `json:"tags"`
Chapters []chapterDTO `json:"chapters"`
}
type chapterDTO struct {
ID int `json:"id"`
MangaID int `json:"obra_id"`
Number string `json:"numero"`
Title string `json:"nome"`
Date string `json:"criado_em"`
}
type pageDTO struct {
Number int `json:"numero"`
URL string `json:"url"`
}
type responseDTO[T any] struct {
Success bool `json:"sucesso"`
Payload T `json:"dados"`
Pagination *struct {
HasNextPage bool `json:"hasNextPage"`
} `json:"pagination"`
}
func (s *Source) toSManga(m mangaDTO) source.SManga {
genres := make([]string, len(m.Tags))
for i, t := range m.Tags {
genres[i] = t.Name
}
return source.SManga{
URL: fmt.Sprintf("%d", m.ID),
Title: m.Title,
Author: m.Author,
Description: m.Synopsis,
Genre: strings.Join(genres, ", "),
Status: util.StatusFromString(m.Status),
ThumbnailURL: util.AbsURL(s.cfg.BaseURL, m.Cover),
}
}
func (s *Source) GetPopularManga(page int) (source.MangasPage, error) {
var result responseDTO[[]mangaDTO]
if err := s.getJSON(context.Background(), s.apiBase()+"/obras/top10/views?periodo=total", &result); err != nil {
return source.MangasPage{}, err
}
mangas := make([]source.SManga, len(result.Payload))
for i, m := range result.Payload {
mangas[i] = s.toSManga(m)
}
return source.MangasPage{Mangas: mangas, HasNextPage: false}, nil
}
func (s *Source) GetLatestUpdates(page int) (source.MangasPage, error) {
var result responseDTO[[]mangaDTO]
if err := s.getJSON(context.Background(), fmt.Sprintf("%s/capitulos/recentes?pagina=%d&limite=20", s.apiBase(), page), &result); err != nil {
return source.MangasPage{}, err
}
mangas := make([]source.SManga, len(result.Payload))
for i, m := range result.Payload {
mangas[i] = s.toSManga(m)
}
hasNext := result.Pagination != nil && result.Pagination.HasNextPage
return source.MangasPage{Mangas: mangas, HasNextPage: hasNext}, nil
}
func (s *Source) GetSearchManga(page int, query string, filters []source.Filter) (source.MangasPage, error) {
var result responseDTO[[]mangaDTO]
u := fmt.Sprintf("%s/obras?pagina=%d&limite=20&busca=%s", s.apiBase(), page, query)
if err := s.getJSON(context.Background(), u, &result); err != nil {
return source.MangasPage{}, err
}
mangas := make([]source.SManga, len(result.Payload))
for i, m := range result.Payload {
mangas[i] = s.toSManga(m)
}
hasNext := result.Pagination != nil && result.Pagination.HasNextPage
return source.MangasPage{Mangas: mangas, HasNextPage: hasNext}, nil
}
func (s *Source) GetMangaDetails(manga source.SManga) (source.SManga, error) {
var result responseDTO[mangaDTO]
if err := s.getJSON(context.Background(), fmt.Sprintf("%s/obras/%s", s.apiBase(), manga.URL), &result); err != nil {
return manga, err
}
return s.toSManga(result.Payload), nil
}
func (s *Source) GetChapterList(manga source.SManga) ([]source.SChapter, error) {
var result responseDTO[mangaDTO]
if err := s.getJSON(context.Background(), fmt.Sprintf("%s/obras/%s", s.apiBase(), manga.URL), &result); err != nil {
return nil, err
}
chapters := make([]source.SChapter, len(result.Payload.Chapters))
for i, ch := range result.Payload.Chapters {
name := "Chapter " + ch.Number
if ch.Title != "" {
name += " - " + ch.Title
}
chapters[i] = source.SChapter{
URL: fmt.Sprintf("%d/%s", ch.MangaID, ch.Number),
Name: name,
DateUpload: util.ParseAbsoluteDate(ch.Date, "2006-01-02T15:04:05Z"),
}
}
return chapters, nil
}
func (s *Source) GetPageList(chapter source.SChapter) ([]source.Page, error) {
parts := strings.SplitN(chapter.URL, "/", 2)
if len(parts) != 2 {
return nil, fmt.Errorf("mangotheme: invalid chapter URL")
}
mangaID, chapterNumber := parts[0], parts[1]
var result responseDTO[[]pageDTO]
if err := s.getJSON(context.Background(), fmt.Sprintf("%s/obras/%s/capitulos/%s", s.apiBase(), mangaID, chapterNumber), &result); err != nil {
return nil, err
}
pages := make([]source.Page, len(result.Payload))
for i, p := range result.Payload {
pages[i] = source.Page{Index: p.Number - 1, ImageURL: util.AbsURL(s.cfg.BaseURL, p.URL)}
if pages[i].Index < 0 {
pages[i].Index = i
}
}
return pages, nil
}
func (s *Source) GetImageURL(page source.Page) (string, error) { return page.ImageURL, nil }
func (s *Source) GetFilterList() []source.Filter { return nil }