fix 'head', 'tail' updating crash

https://github.com/pyed/transmission-telegram/issues/2
This commit is contained in:
pyed 2016-12-07 23:48:41 +03:00
parent 3800b83569
commit d8ac43c1a1

View File

@ -156,7 +156,7 @@ func init() {
// set the usage message
flag.Usage = func() {
fmt.Fprint(os.Stderr, "Usage: transmission-bot -token=<TOKEN> -master=<@tuser> -master=<@yuser2> -url=[http://] -username=[user] -password=[pass]\n\n")
fmt.Fprint(os.Stderr, "Usage: transmission-bot <-token=TOKEN> <-master=@tuser> [-master=@yuser2] [-url=http://] [-username=user] [-password=pass]\n\n")
flag.PrintDefaults()
}
@ -175,7 +175,6 @@ func init() {
Masters[i] = strings.Replace(Masters[i], "@", "", -1)
}
// if we got a log file, log to it
if LogFile != "" {
logf, err := os.OpenFile(LogFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
@ -430,12 +429,21 @@ func head(ud tgbotapi.Update, tokens []string) {
continue // try again if some error heppened
}
for i := range torrents[:n] {
torrentName := mdReplacer.Replace(torrents[i].Name) // escape markdown
if len(torrents) < 1 {
continue
}
// make sure that we stay in the boundaries
if n <= 0 || n > len(torrents) {
n = len(torrents)
}
for _, torrent := range torrents[:n] {
torrentName := mdReplacer.Replace(torrent.Name) // escape markdown
buf.WriteString(fmt.Sprintf("`<%d>` *%s*\n%s *%s* of *%s* (*%.1f%%*) ↓ *%s* ↑ *%s* R: *%s*\n\n",
torrents[i].ID, torrentName, torrents[i].TorrentStatus(), humanize.Bytes(torrents[i].Have()),
humanize.Bytes(torrents[i].SizeWhenDone), torrents[i].PercentDone*100, humanize.Bytes(torrents[i].RateDownload),
humanize.Bytes(torrents[i].RateUpload), torrents[i].Ratio()))
torrent.ID, torrentName, torrent.TorrentStatus(), humanize.Bytes(torrent.Have()),
humanize.Bytes(torrent.SizeWhenDone), torrent.PercentDone*100, humanize.Bytes(torrent.RateDownload),
humanize.Bytes(torrent.RateUpload), torrent.Ratio()))
}
// no need to check if it is empty, as if the buffer is empty telegram won't change the message
@ -498,6 +506,15 @@ func tail(ud tgbotapi.Update, tokens []string) {
continue // try again if some error heppened
}
if len(torrents) < 1 {
continue
}
// make sure that we stay in the boundaries
if n <= 0 || n > len(torrents) {
n = len(torrents)
}
for _, torrent := range torrents[len(torrents)-n:] {
torrentName := mdReplacer.Replace(torrent.Name) // escape markdown
buf.WriteString(fmt.Sprintf("`<%d>` *%s*\n%s *%s* of *%s* (*%.1f%%*) ↓ *%s* ↑ *%s* R: *%s*\n\n",