Skip to content

Commit

Permalink
add variable placeholders for rename flag in 'add' and 'dltorrent' cmd
Browse files Browse the repository at this point in the history
  • Loading branch information
sagan committed Feb 20, 2024
1 parent ce3a5f7 commit 7a219f7
Show file tree
Hide file tree
Showing 17 changed files with 175 additions and 111 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -380,7 +380,7 @@ ptool dltorrent <torrentIdOrUrl>...

可选参数:

- --download-dir : 下载的种子文件保存路径。默认为当前目录(CWD)。
- --dir : 下载的种子文件保存路径。默认为当前目录(.)。

### 搜索 PT 站点种子 (search)

Expand Down
78 changes: 48 additions & 30 deletions cmd/add/add.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"fmt"
"io"
"os"
"path"
"strings"

log "github.com/sirupsen/logrus"
Expand All @@ -24,7 +25,15 @@ var command = &cobra.Command{
Short: "Add torrents to client.",
Long: `Add torrents to client.
Each arg could be a local filename (e.g. "*.torrent" or "[M-TEAM]CLANNAD (2007).torrent"),
torrent id (e.g.: "mteam.488424"), or torrent url (e.g.: "https://kp.m-team.cc/details.php?id=488424").`,
torrent id (e.g.: "mteam.488424"), or torrent url (e.g.: "https://kp.m-team.cc/details.php?id=488424").
Use "-" as arg to read torrent content from stdin.
--rename <name> flag supports the following variable placeholders:
* [size] : Torrent size
* [id] : Torrent id in site
* [site] : Torrent site
* [filename] : Original torrent filename, with ".torrent" extension removed
* [name] : Torrent name`,
Args: cobra.MatchAll(cobra.MinimumNArgs(2), cobra.OnlyValidArgs),
RunE: add,
}
Expand Down Expand Up @@ -55,7 +64,7 @@ func init() {
"Rename successfully added *.torrent file to *.torrent.added")
command.Flags().BoolVarP(&deleteAdded, "delete-added", "", false, "Delete successfully added *.torrent file")
command.Flags().BoolVarP(&forceLocal, "force-local", "", false, "Force treat all arg as local torrent filename")
command.Flags().StringVarP(&rename, "rename", "", "", "Rename added torrent (for adding single torrent only)")
command.Flags().StringVarP(&rename, "rename", "", "", "Rename added torrents (supports variables)")
command.Flags().StringVarP(&addCategory, "add-category", "", "", "Set category of added torrents")
command.Flags().StringVarP(&savePath, "add-save-path", "", "", "Set save path of added torrents")
command.Flags().StringVarP(&defaultSite, "site", "", "", "Set default site of added torrents")
Expand All @@ -71,9 +80,6 @@ func add(cmd *cobra.Command, args []string) error {
return fmt.Errorf("--rename-added and --delete-added flags are NOT compatible")
}
torrents := util.ParseFilenameArgs(args[1:]...)
if rename != "" && len(torrents) > 1 {
return fmt.Errorf("--rename flag can only be used with exact one torrent arg")
}
clientInstance, err := client.CreateClient(clientName)
if err != nil {
return fmt.Errorf("failed to create client: %v", err)
Expand All @@ -83,23 +89,24 @@ func add(cmd *cobra.Command, args []string) error {
SavePath: savePath,
SkipChecking: skipCheck,
SequentialDownload: sequentialDownload,
Name: rename,
}
var fixedTags []string
if addTags != "" {
fixedTags = strings.Split(addTags, ",")
}
domainSiteMap := map[string]string{}
siteInstanceMap := map[string]site.Site{}
cntError := int64(0)
errorCnt := int64(0)
cntAdded := int64(0)
sizeAdded := int64(0)
cntAll := len(torrents)

for i, torrent := range torrents {
var isLocal bool
var siteName string
var torrentContent []byte
var filename string // original torrent filename
var content []byte
var id string // site torrent id
var err error
var hr bool
if forceLocal || torrent == "-" || !util.IsUrl(torrent) && strings.HasSuffix(torrent, ".torrent") {
Expand All @@ -113,13 +120,12 @@ func add(cmd *cobra.Command, args []string) error {
i := strings.Index(torrent, ".")
if i != -1 && i < len(torrent)-1 {
siteName = torrent[:i]
torrent = torrent[i+1:]
}
} else {
domain := util.GetUrlDomain(torrent)
if domain == "" {
fmt.Printf("✕add (%d/%d) %s error: failed to parse domain", i+1, cntAll, torrent)
cntError++
fmt.Printf("✕add (%d/%d) %s: failed to parse domain", i+1, cntAll, torrent)
errorCnt++
continue
}
sitename := ""
Expand All @@ -138,8 +144,8 @@ func add(cmd *cobra.Command, args []string) error {
}
}
if siteName == "" {
fmt.Printf("✕add (%d/%d) %s error: no site found or provided\n", i+1, cntAll, torrent)
cntError++
fmt.Printf("✕add (%d/%d) %s: no site found or provided\n", i+1, cntAll, torrent)
errorCnt++
continue
}
if siteInstanceMap[siteName] == nil {
Expand All @@ -151,31 +157,31 @@ func add(cmd *cobra.Command, args []string) error {
}
siteInstance := siteInstanceMap[siteName]
hr = siteInstance.GetSiteConfig().GlobalHnR
torrentContent, _, err = siteInstance.DownloadTorrent(torrent)
content, filename, id, err = siteInstance.DownloadTorrent(torrent)
} else {
isLocal = true
if strings.HasSuffix(torrent, ".added") {
fmt.Printf("-skip (%d/%d) %s\n", i+1, cntAll, torrent)
continue
}
if torrent == "-" {
torrentContent, err = io.ReadAll(os.Stdin)
filename = ""
content, err = io.ReadAll(os.Stdin)
} else {
torrentContent, err = os.ReadFile(torrent)
filename = path.Base(torrent)
content, err = os.ReadFile(torrent)
}
}

if err != nil {
fmt.Printf("✕add (%d/%d) %s (site=%s) error: failed to get torrent: %v\n",
i+1, cntAll, torrent, siteName, err)
cntError++
fmt.Printf("✕add (%d/%d) %s (site=%s): failed to fetch: %v\n", i+1, cntAll, torrent, siteName, err)
errorCnt++
continue
}
tinfo, err := torrentutil.ParseTorrent(torrentContent, 99)
tinfo, err := torrentutil.ParseTorrent(content, 99)
if err != nil {
fmt.Printf("✕add (%d/%d) %s (site=%s) error: failed to parse torrent: %v\n",
i+1, cntAll, torrent, siteName, err)
cntError++
fmt.Printf("✕add (%d/%d) %s (site=%s): failed to parse torrent: %v\n", i+1, cntAll, torrent, siteName, err)
errorCnt++
continue
}
if siteName == "" {
Expand Down Expand Up @@ -203,11 +209,23 @@ func add(cmd *cobra.Command, args []string) error {
option.Tags = append(option.Tags, "_hr")
}
option.Tags = append(option.Tags, fixedTags...)
err = clientInstance.AddTorrent(torrentContent, option, nil)
if rename != "" {
basename := filename
if i := strings.LastIndex(basename, "."); i != -1 {
basename = basename[:i]
}
option.Name = rename
option.Name = strings.ReplaceAll(option.Name, "[size]", util.BytesSize(float64(tinfo.Size)))
option.Name = strings.ReplaceAll(option.Name, "[id]", id)
option.Name = strings.ReplaceAll(option.Name, "[site]", siteName)
option.Name = strings.ReplaceAll(option.Name, "[filename]", basename)
option.Name = strings.ReplaceAll(option.Name, "[name]", tinfo.Info.Name)
}
err = clientInstance.AddTorrent(content, option, nil)
if err != nil {
fmt.Printf("✕add (%d/%d) %s (site=%s) error: failed to add torrent to client: %v // %s\n",
fmt.Printf("✕add (%d/%d) %s (site=%s): failed to add torrent to client: %v // %s\n",
i+1, cntAll, torrent, siteName, err, tinfo.ContentPath)
cntError++
errorCnt++
continue
}
if isLocal {
Expand All @@ -223,13 +241,13 @@ func add(cmd *cobra.Command, args []string) error {
}
cntAdded++
sizeAdded += tinfo.Size
fmt.Printf("✓add (%d/%d) %s (site=%s) success. infoHash=%s // %s\n",
fmt.Printf("✓add (%d/%d) %s (site=%s). infoHash=%s // %s\n",
i+1, cntAll, torrent, siteName, tinfo.InfoHash, tinfo.ContentPath)
}
fmt.Printf("\nDone. Added torrent (Size/Cnt): %s / %d; ErrorCnt: %d\n",
util.BytesSize(float64(sizeAdded)), cntAdded, cntError)
if cntError > 0 {
return fmt.Errorf("%d errors", cntError)
util.BytesSize(float64(sizeAdded)), cntAdded, errorCnt)
if errorCnt > 0 {
return fmt.Errorf("%d errors", errorCnt)
}
return nil
}
Expand Down
4 changes: 2 additions & 2 deletions cmd/batchdl/batchdl.go
Original file line number Diff line number Diff line change
Expand Up @@ -353,9 +353,9 @@ mainloop:
var torrentContent []byte
var filename string
if torrent.DownloadUrl != "" {
torrentContent, filename, err = siteInstance.DownloadTorrent(torrent.DownloadUrl)
torrentContent, filename, _, err = siteInstance.DownloadTorrent(torrent.DownloadUrl)
} else {
torrentContent, filename, err = siteInstance.DownloadTorrent(torrent.Id)
torrentContent, filename, _, err = siteInstance.DownloadTorrent(torrent.Id)
}
if err != nil {
fmt.Printf("torrent %s (%s): failed to download: %v\n", torrent.Id, torrent.Name, err)
Expand Down
2 changes: 1 addition & 1 deletion cmd/brush/brush.go
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,7 @@ func brush(cmd *cobra.Command, args []string) error {
if dryRun {
continue
}
torrentdata, _, err := siteInstance.DownloadTorrent(torrent.DownloadUrl)
torrentdata, _, _, err := siteInstance.DownloadTorrent(torrent.DownloadUrl)
if err != nil {
log.Printf("Failed to download: %s. Skip \n", err)
continue
Expand Down
4 changes: 2 additions & 2 deletions cmd/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ import (
// Root represents the base command when called without any subcommands
var RootCmd = &cobra.Command{
Use: "ptool",
Short: "ptool is a command-line program which facilitate the use of private tracker sites and BitTorrent clients.",
Long: `ptool is a command-line program which facilitate the use of private tracker sites and BitTorrent clients.
Short: "ptool is a command-line program which facilitates the use of private tracker sites and BitTorrent clients.",
Long: `ptool is a command-line program which facilitates the use of private tracker sites and BitTorrent clients.
It's a free and open-source software, visit https://github.com/sagan/ptool for more infomation.`,
// Run: func(cmd *cobra.Command, args []string) { },
SilenceErrors: true,
Expand Down
12 changes: 6 additions & 6 deletions cmd/cookiecloud/get/get.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ func init() {
}

func get(cmd *cobra.Command, args []string) error {
cntError := int64(0)
errorCnt := int64(0)
cookiecloudProfiles := cookiecloud.ParseProfile(profile)
if len(cookiecloudProfiles) == 0 {
return fmt.Errorf("no cookiecloud profile specified or found")
Expand All @@ -65,7 +65,7 @@ func get(cmd *cobra.Command, args []string) error {
profile.Proxy, profile.Timeoout)
if err != nil {
log.Errorf("Cookiecloud server %s (uuid %s) connection failed: %v\n", profile.Server, profile.Uuid, err)
cntError++
errorCnt++
} else {
log.Infof("Cookiecloud server %s (uuid %s) connection ok: cookies of %d domains found\n",
profile.Server, profile.Uuid, len(data.Cookie_data))
Expand Down Expand Up @@ -98,13 +98,13 @@ func get(cmd *cobra.Command, args []string) error {
if domainOrUrl == "" {
fmt.Printf("%-20s %-20s %s\n",
util.First(util.StringPrefixInWidth(siteOrDomainOrUrl, 20)), "", "// Error: empty hostname")
cntError++
errorCnt++
continue
} else if !util.IsUrl(domainOrUrl) && !util.IsHostname(domainOrUrl) {
fmt.Printf("%-20s %-20s %s\n",
util.First(util.StringPrefixInWidth(siteOrDomainOrUrl, 20)),
"", "// Error: invalid site, url or hostname")
cntError++
errorCnt++
continue
} else if util.IsUrl(domainOrUrl) {
urlObj, err := url.Parse(domainOrUrl)
Expand All @@ -130,8 +130,8 @@ func get(cmd *cobra.Command, args []string) error {
}
}

if cntError > 0 {
return fmt.Errorf("%d errors", cntError)
if errorCnt > 0 {
return fmt.Errorf("%d errors", errorCnt)
}
return nil
}
8 changes: 4 additions & 4 deletions cmd/cookiecloud/importsites/importsites.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ func init() {
}

func importsites(cmd *cobra.Command, args []string) error {
cntError := int64(0)
errorCnt := int64(0)
cookiecloudProfiles := cookiecloud.ParseProfile(profile)
if len(cookiecloudProfiles) == 0 {
return fmt.Errorf("no cookiecloud profile specified or found")
Expand All @@ -61,7 +61,7 @@ func importsites(cmd *cobra.Command, args []string) error {
profile.Proxy, profile.Timeoout)
if err != nil {
log.Errorf("Cookiecloud server %s (uuid %s) connection failed: %v\n", profile.Server, profile.Uuid, err)
cntError++
errorCnt++
} else {
log.Infof("Cookiecloud server %s (uuid %s) connection ok: cookies of %d domains found\n",
profile.Server, profile.Uuid, len(data.Cookie_data))
Expand Down Expand Up @@ -172,8 +172,8 @@ func importsites(cmd *cobra.Command, args []string) error {
fmt.Printf("!No new sites found in cookiecloud datas\n")
}

if cntError > 0 {
return fmt.Errorf("%d errors", cntError)
if errorCnt > 0 {
return fmt.Errorf("%d errors", errorCnt)
}
return nil
}
8 changes: 4 additions & 4 deletions cmd/cookiecloud/status/status.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ func init() {
}

func status(cmd *cobra.Command, args []string) error {
cntError := int64(0)
errorCnt := int64(0)
cookiecloudProfiles := cookiecloud.ParseProfile(profile)
if len(cookiecloudProfiles) == 0 {
return fmt.Errorf("no cookiecloud profile specified or found")
Expand All @@ -38,14 +38,14 @@ func status(cmd *cobra.Command, args []string) error {
if err != nil {
fmt.Printf("✕cookiecloud server %s (uuid %s) test failed: %v\n",
util.ParseUrlHostname(profile.Server), profile.Uuid, err)
cntError++
errorCnt++
} else {
fmt.Printf("✓cookiecloud server %s (uuid %s) test ok: cookies of %d domains found\n",
util.ParseUrlHostname(profile.Server), profile.Uuid, len(data.Cookie_data))
}
}
if cntError > 0 {
return fmt.Errorf("%d errors", cntError)
if errorCnt > 0 {
return fmt.Errorf("%d errors", errorCnt)
}
return nil
}
8 changes: 4 additions & 4 deletions cmd/cookiecloud/sync/sync.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ func init() {
}

func sync(cmd *cobra.Command, args []string) error {
cntError := int64(0)
errorCnt := int64(0)
cookiecloudProfiles := cookiecloud.ParseProfile(profile)
if len(cookiecloudProfiles) == 0 {
return fmt.Errorf("no cookiecloud profile specified or found")
Expand All @@ -59,7 +59,7 @@ func sync(cmd *cobra.Command, args []string) error {
profile.Proxy, profile.Timeoout)
if err != nil {
log.Errorf("Cookiecloud server %s (uuid %s) connection failed: %v\n", profile.Server, profile.Uuid, err)
cntError++
errorCnt++
} else {
log.Infof("Cookiecloud server %s (uuid %s) connection ok: cookies of %d domains found\n",
profile.Server, profile.Uuid, len(data.Cookie_data))
Expand Down Expand Up @@ -247,8 +247,8 @@ func sync(cmd *cobra.Command, args []string) error {
fmt.Printf("!No new cookie found for any site\n")
}

if cntError > 0 {
return fmt.Errorf("%d errors", cntError)
if errorCnt > 0 {
return fmt.Errorf("%d errors", errorCnt)
}
return nil
}

0 comments on commit 7a219f7

Please sign in to comment.