bt2qbt/b2q.go

381 lines
13 KiB
Go
Raw Normal View History

2017-12-26 16:25:10 +01:00
package main
import (
"bufio"
2017-12-26 16:25:10 +01:00
"crypto/sha1"
"encoding/hex"
"fmt"
2018-04-02 12:17:50 +02:00
"github.com/fatih/color"
"github.com/zeebo/bencode"
2017-12-26 16:25:10 +01:00
"io"
"io/ioutil"
2018-04-09 15:02:46 +02:00
"launchpad.net/gnuflag"
"log"
"os"
"path/filepath"
2017-12-27 21:43:12 +01:00
"strconv"
2018-04-02 12:17:50 +02:00
"strings"
2018-04-09 15:02:46 +02:00
"time"
2017-12-26 16:25:10 +01:00
)
2018-04-02 12:17:50 +02:00
func decodetorrentfile(path string) (map[string]interface{}, error) {
2017-12-26 16:25:10 +01:00
dat, err := ioutil.ReadFile(path)
if err != nil {
2018-04-02 12:17:50 +02:00
return nil, err
2017-12-26 16:25:10 +01:00
}
var torrent map[string]interface{}
if err := bencode.DecodeBytes([]byte(dat), &torrent); err != nil {
2018-04-02 12:17:50 +02:00
return nil, err
2017-12-26 16:25:10 +01:00
}
2018-04-02 12:17:50 +02:00
return torrent, nil
2017-12-26 16:25:10 +01:00
}
2017-12-30 16:17:58 +01:00
func encodetorrentfile(path string, newstructure map[string]interface{}) error {
2018-04-09 15:02:46 +02:00
if _, err := os.Stat(path); os.IsNotExist(err) {
os.Create(path)
}
file, err := os.OpenFile(path, os.O_WRONLY, 0666)
if err != nil {
2017-12-28 21:19:46 +01:00
return err
}
defer file.Close()
bufferedWriter := bufio.NewWriter(file)
enc := bencode.NewEncoder(bufferedWriter)
2017-12-30 16:17:58 +01:00
if err := enc.Encode(newstructure); err != nil {
2018-04-02 12:17:50 +02:00
return err
}
bufferedWriter.Flush()
2017-12-28 21:19:46 +01:00
return nil
}
2017-12-30 16:17:58 +01:00
func gethash(info map[string]interface{}) (hash string) {
torinfo, _ := bencode.EncodeString(info)
2017-12-26 16:25:10 +01:00
h := sha1.New()
io.WriteString(h, torinfo)
2017-12-28 21:19:46 +01:00
hash = hex.EncodeToString(h.Sum(nil))
return
2017-12-26 16:25:10 +01:00
}
2018-04-04 11:55:09 +02:00
func fillnothavefiles(npieces *int64) []byte {
2018-04-09 15:02:46 +02:00
var newpieces = make([]byte, 0, *npieces)
2018-04-03 00:59:50 +02:00
for i := int64(0); i < *npieces; i++ {
chr, _ := strconv.Atoi("1")
newpieces = append(newpieces, byte(chr))
}
return newpieces
}
2018-04-04 11:55:09 +02:00
func fillhavefiles(sizeandprio *[][]int64, npieces *int64, piecelenght *int64) []byte {
2018-04-09 15:02:46 +02:00
var newpieces = make([]byte, 0, *npieces)
var allocation [][]int64
offset := int64(0)
2018-04-04 11:55:09 +02:00
for _, pair := range *sizeandprio {
2018-04-03 21:14:14 +02:00
allocation = append(allocation, []int64{offset + 1, offset + pair[0], pair[1]})
offset = offset + pair[0]
}
2018-04-04 11:55:09 +02:00
for i := int64(0); i < *npieces; i++ {
2018-04-03 00:59:50 +02:00
belongs := false
2018-04-09 15:02:46 +02:00
first, last := i**piecelenght, (i+1)**piecelenght
for _, trio := range allocation {
if (first >= trio[0]-*piecelenght && last <= trio[1]+*piecelenght) && trio[2] == 1 {
2018-04-09 15:02:46 +02:00
belongs = true
}
2018-04-03 00:59:50 +02:00
}
var chr int
if belongs {
chr, _ = strconv.Atoi("1")
} else {
chr, _ = strconv.Atoi("0")
}
newpieces = append(newpieces, byte(chr))
}
return newpieces
}
2017-12-30 16:17:58 +01:00
func prioconvert(src string) (newprio []int) {
for _, c := range []byte(src) {
if i := int(c); (i == 0) || (i == 128) { // if not selected
2017-12-28 21:19:46 +01:00
newprio = append(newprio, 0)
} else if (i == 4) || (i == 8) { // if low or normal prio
2017-12-28 21:19:46 +01:00
newprio = append(newprio, 1)
} else if i == 12 { // if high prio
2017-12-28 21:19:46 +01:00
newprio = append(newprio, 6)
}
}
return
}
func fmtime(path string) (mtime int64) {
2018-04-06 15:18:06 +02:00
if fi, err := os.Stat(path); err != nil {
2017-12-28 21:19:46 +01:00
return 0
2018-04-06 15:18:06 +02:00
} else {
mtime = int64(fi.ModTime().Unix())
return
2017-12-28 21:19:46 +01:00
}
}
func copyfile(src string, dst string) error {
2017-12-28 22:43:07 +01:00
originalFile, err := os.Open(src)
if err != nil {
return err
}
defer originalFile.Close()
newFile, err := os.Create(dst)
if err != nil {
return err
}
defer newFile.Close()
if _, err := io.Copy(newFile, originalFile); err != nil {
return err
}
2018-04-06 15:18:06 +02:00
if err := newFile.Sync(); err != nil {
2017-12-28 22:43:07 +01:00
return err
}
return nil
}
func logic(key string, value map[string]interface{}, bitdir *string, with_label *bool, with_tags *bool, qbitdir *string, comChannel chan string, position int64) error {
newstructure := map[string]interface{}{"active_time": 0, "added_time": 0, "announce_to_dht": 0,
"announce_to_lsd": 0, "announce_to_trackers": 0, "auto_managed": 0,
"banned_peers": new(string), "banned_peers6": new(string), "blocks per piece": 0,
2017-12-28 21:19:46 +01:00
"completed_time": 0, "download_rate_limit": -1, "file sizes": new([][]int64),
2017-12-28 14:28:16 +01:00
"file-format": "libtorrent resume file", "file-version": 1, "file_priority": new([]int), "finished_time": 0,
2018-04-02 16:26:29 +02:00
"info-hash": new([]byte), "last_seen_complete": 0, "libtorrent-version": "1.1.6.0",
2018-04-03 00:59:50 +02:00
"max_connections": 100, "max_uploads": 100, "num_downloaded": 0,
2018-04-02 16:26:29 +02:00
"num_incomplete": 0, "paused": new(int), "peers": new(string), "peers6": new(string),
2018-04-02 12:17:50 +02:00
"pieces": new([]byte), "qBt-category": new(string), "qBt-name": new(string),
2018-04-03 00:59:50 +02:00
"qBt-queuePosition": 1, "qBt-ratioLimit": -2000, "qBt-savePath": new(string),
"qBt-seedStatus": 1, "qBt-seedingTimeLimit": -2, "qBt-tags": new([]string),
"qBt-tempPathDisabled": 0, "save_path": new(string), "seed_mode": 0, "seeding_time": 0,
"sequential_download": 0, "super_seeding": 0, "total_downloaded": 0,
2018-04-02 16:26:29 +02:00
"total_uploaded": 0, "trackers": new([][]interface{}), "upload_rate_limit": 0,
}
2018-04-02 12:17:50 +02:00
torrentfilepath := *bitdir + key
if _, err := os.Stat(torrentfilepath); os.IsNotExist(err) {
comChannel <- fmt.Sprintf("Can't find torrent file %v for %v", torrentfilepath, key)
return err
}
torrentfile, err := decodetorrentfile(torrentfilepath)
if err != nil {
comChannel <- fmt.Sprintf("Can't decode torrent file %v for %v", torrentfilepath, key)
return err
}
2017-12-30 16:17:58 +01:00
newstructure["active_time"] = value["runtime"]
newstructure["added_time"] = value["added_on"]
newstructure["completed_time"] = value["completed_on"]
newstructure["info-hash"] = value["info"]
newstructure["qBt-tags"] = value["labels"]
newstructure["seeding_time"] = value["runtime"]
newstructure["qBt-queuePosition"] = position
if value["started"].(int64) == int64(0) {
newstructure["paused"] = 1
newstructure["auto_managed"] = 0
newstructure["announce_to_dht"] = 0
newstructure["announce_to_lsd"] = 0
newstructure["announce_to_trackers"] = 0
2018-04-02 12:17:50 +02:00
} else {
newstructure["paused"] = 0
newstructure["auto_managed"] = 1
newstructure["announce_to_dht"] = 1
newstructure["announce_to_lsd"] = 1
newstructure["announce_to_trackers"] = 1
2018-04-04 11:55:09 +02:00
}
2018-04-03 00:59:50 +02:00
newstructure["paused"] = 1
2017-12-30 16:17:58 +01:00
newstructure["finished_time"] = int(time.Since(time.Unix(value["completed_on"].(int64), 0)).Minutes())
if value["completed_on"] != 0 {
newstructure["last_seen_complete"] = int(time.Now().Unix())
}
2017-12-30 16:17:58 +01:00
newstructure["total_downloaded"] = value["downloaded"]
newstructure["total_uploaded"] = value["uploaded"]
newstructure["upload_rate_limit"] = value["upspeed"]
if *with_label == true {
2017-12-30 16:17:58 +01:00
newstructure["qBt-category"] = value["label"]
2018-04-02 12:17:50 +02:00
} else {
newstructure["qBt-category"] = ""
}
if *with_tags == true {
2017-12-30 16:17:58 +01:00
newstructure["qBt-tags"] = value["labels"]
2018-04-02 12:17:50 +02:00
} else {
newstructure["qBt-tags"] = ""
}
var trackers []interface{}
2017-12-30 16:17:58 +01:00
for _, tracker := range value["trackers"].([]interface{}) {
2017-12-30 20:24:41 +01:00
trackers = append(trackers, []interface{}{tracker})
}
newstructure["trackers"] = trackers
2017-12-30 16:17:58 +01:00
newstructure["file_priority"] = prioconvert(value["prio"].(string))
var hasfiles bool
2018-04-09 15:02:46 +02:00
if _, ok := torrentfile["info"].(map[string]interface{})["files"]; ok {
2018-04-03 00:59:50 +02:00
hasfiles = true
} else {
hasfiles = false
}
if value["path"].(string)[len(value["path"].(string))-1] == os.PathSeparator {
value["path"] = value["path"].(string)[:len(value["path"].(string))-1]
}
2018-04-04 11:55:09 +02:00
filesizes := float32(0)
2018-04-03 00:59:50 +02:00
var sizeandprio [][]int64
2018-04-09 22:06:30 +02:00
var torrentfilelist []string
2017-12-28 22:10:57 +01:00
if files, ok := torrentfile["info"].(map[string]interface{})["files"]; ok {
var filelists []interface{}
for num, file := range files.([]interface{}) {
var lenght, mtime int64
var filestrings []string
if path, ok := file.(map[string]interface{})["path.utf-8"].([]interface{}); ok {
for _, f := range path {
filestrings = append(filestrings, f.(string))
}
} else {
for _, f := range file.(map[string]interface{})["path"].([]interface{}) {
filestrings = append(filestrings, f.(string))
}
}
filename := strings.Join(filestrings, string(os.PathSeparator))
2018-04-09 22:06:30 +02:00
torrentfilelist = append(torrentfilelist, filename)
2017-12-30 16:17:58 +01:00
fullpath := value["path"].(string) + "\\" + filename
2018-04-03 00:59:50 +02:00
filesizes += float32(file.(map[string]interface{})["length"].(int64))
2017-12-28 22:10:57 +01:00
if n := newstructure["file_priority"].([]int)[num]; n != 0 {
lenght = file.(map[string]interface{})["length"].(int64)
2018-04-09 15:02:46 +02:00
sizeandprio = append(sizeandprio, []int64{lenght, 1})
2017-12-28 22:10:57 +01:00
mtime = fmtime(fullpath)
} else {
lenght, mtime = 0, 0
2018-04-09 15:02:46 +02:00
sizeandprio = append(sizeandprio, []int64{file.(map[string]interface{})["length"].(int64), 0})
}
2017-12-28 22:10:57 +01:00
flenmtime := []int64{lenght, mtime}
filelists = append(filelists, flenmtime)
}
newstructure["file sizes"] = filelists
2017-12-28 21:19:46 +01:00
} else {
2018-04-03 00:59:50 +02:00
filesizes = float32(torrentfile["info"].(map[string]interface{})["length"].(int64))
2017-12-30 16:17:58 +01:00
newstructure["file sizes"] = [][]int64{{torrentfile["info"].(map[string]interface{})["length"].(int64), fmtime(value["path"].(string))}}
2017-12-28 21:19:46 +01:00
}
2018-04-02 16:26:29 +02:00
newstructure["blocks per piece"] = torrentfile["info"].(map[string]interface{})["piece length"].(int64) / value["blocksize"].(int64)
2018-04-03 00:59:50 +02:00
var npieces int64
piecelenght := torrentfile["info"].(map[string]interface{})["piece length"].(int64)
if ((filesizes / float32(piecelenght)) - float32((int64(filesizes) / piecelenght))) != 0 { // check fraction
2018-04-09 15:02:46 +02:00
npieces = int64(filesizes)/torrentfile["info"].(map[string]interface{})["piece length"].(int64) + 1
2018-04-03 00:59:50 +02:00
} else {
npieces = int64(filesizes) / torrentfile["info"].(map[string]interface{})["piece length"].(int64)
}
2018-04-09 15:02:46 +02:00
if hasfiles {
2018-04-04 11:55:09 +02:00
newstructure["pieces"] = fillhavefiles(&sizeandprio, &npieces, &piecelenght)
2018-04-03 00:59:50 +02:00
} else {
2018-04-04 11:55:09 +02:00
newstructure["pieces"] = fillnothavefiles(&npieces)
2018-04-03 00:59:50 +02:00
}
var torrentname string
if name, ok := torrentfile["info"].(map[string]interface{})["name.utf-8"].(string); ok {
torrentname = name
} else {
torrentname = torrentfile["info"].(map[string]interface{})["name"].(string)
}
2018-04-02 12:17:50 +02:00
origpath := value["path"].(string)
_, lastdirname := filepath.Split(strings.Replace(origpath, "\\", "/", -1))
if hasfiles {
if lastdirname == torrentname {
newstructure["qBt-hasRootFolder"] = 1
2018-04-03 00:59:50 +02:00
newstructure["save_path"] = origpath[0 : len(origpath)-len(lastdirname)]
} else {
newstructure["qBt-hasRootFolder"] = 0
2018-04-03 00:59:50 +02:00
newstructure["save_path"] = value["path"].(string) + "\\"
2018-04-09 22:06:30 +02:00
newstructure["mapped_files"] = torrentfilelist
}
2018-04-02 12:17:50 +02:00
} else {
2018-04-09 22:06:30 +02:00
if lastdirname == torrentname {
newstructure["qBt-hasRootFolder"] = 0
newstructure["save_path"] = origpath[0 : len(origpath)-len(lastdirname)]
} else {
newstructure["qBt-hasRootFolder"] = 0
torrentfilelist = append(torrentfilelist, lastdirname)
newstructure["mapped_files"] = torrentfilelist
newstructure["save_path"] = origpath[0 : len(origpath)-len(lastdirname)]
}
2018-04-02 12:17:50 +02:00
}
newstructure["qBt-savePath"] = newstructure["save_path"]
2017-12-30 16:17:58 +01:00
newbasename := gethash(torrentfile["info"].(map[string]interface{}))
if err := encodetorrentfile(*qbitdir+newbasename+".fastresume", newstructure); err != nil {
2018-04-02 12:17:50 +02:00
comChannel <- fmt.Sprintf("Can't create qBittorrent fastresume file %v", *qbitdir+newbasename+".fastresume")
return err
2017-12-28 22:43:07 +01:00
}
if err := copyfile(*bitdir+key, *qbitdir+newbasename+".torrent"); err != nil {
2018-04-02 12:17:50 +02:00
comChannel <- fmt.Sprintf("Can't create qBittorrent torrent file %v", *qbitdir+newbasename+".torrent")
return err
2017-12-28 22:43:07 +01:00
}
comChannel <- fmt.Sprintf("Sucessfully imported %v", key)
2018-04-02 12:17:50 +02:00
return nil
2017-12-26 16:25:10 +01:00
}
func main() {
2018-04-09 12:09:59 +02:00
var bitdir, qbitdir string
var with_label, with_tags bool = true, true
var without_label, without_tags bool
gnuflag.StringVar(&bitdir, "source", (os.Getenv("APPDATA") + "\\uTorrent\\"), "Source directory that contains resume.dat and torrents files")
gnuflag.StringVar(&bitdir, "s", (os.Getenv("APPDATA") + "\\uTorrent\\"), "Source directory that contains resume.dat and torrents files")
2018-04-09 12:09:59 +02:00
gnuflag.StringVar(&qbitdir, "destination", (os.Getenv("LOCALAPPDATA") + "\\qBittorrent\\BT_backup\\"), "Destination directory BT_backup (as default)")
gnuflag.StringVar(&qbitdir, "d", (os.Getenv("LOCALAPPDATA") + "\\qBittorrent\\BT_backup\\"), "Destination directory BT_backup (as default)")
2018-04-09 14:51:56 +02:00
gnuflag.BoolVar(&without_label, "without-labels", false, "Do not export/import labels")
gnuflag.BoolVar(&without_tags, "without-tags", false, "Do not export/import tags")
2018-04-09 12:09:59 +02:00
gnuflag.Parse(true)
if without_label {
with_label = false
}
if without_tags {
with_tags = false
}
if bitdir[len(bitdir)-1] != os.PathSeparator {
bitdir += string(os.PathSeparator)
}
if qbitdir[len(qbitdir)-1] != os.PathSeparator {
qbitdir += string(os.PathSeparator)
}
2018-04-02 12:17:50 +02:00
if _, err := os.Stat(bitdir); os.IsNotExist(err) {
log.Println("Can't find uTorrent\\Bittorrent folder")
time.Sleep(30 * time.Second)
os.Exit(1)
}
if _, err := os.Stat(qbitdir); os.IsNotExist(err) {
log.Println("Can't find qBittorrent folder")
time.Sleep(30 * time.Second)
os.Exit(1)
}
resumefilepath := bitdir + "resume.dat"
if _, err := os.Stat(resumefilepath); os.IsNotExist(err) {
log.Println("Can't find uTorrent\\Bittorrent resume file")
time.Sleep(30 * time.Second)
os.Exit(1)
}
resumefile, err := decodetorrentfile(resumefilepath)
if err != nil {
log.Println("Can't decode uTorrent\\Bittorrent resume file")
time.Sleep(30 * time.Second)
os.Exit(1)
}
2018-04-09 16:42:21 +02:00
color.Green("It will be performed processing from directory %v to directory %v\n", bitdir, qbitdir)
2018-04-02 12:17:50 +02:00
color.HiRed("Check that the qBittorrent is turned off and the directory %v is backed up.\n\n", qbitdir)
fmt.Println("Press Enter to start")
fmt.Scanln()
fmt.Println("Started")
totaljobs := int64(0)
numjob := int64(1)
2018-04-02 12:17:50 +02:00
comChannel := make(chan string, totaljobs)
for key, value := range resumefile {
2017-12-27 22:00:50 +01:00
if key != ".fileguard" && key != "rec" {
totaljobs += 1
go logic(key, value.(map[string]interface{}), &bitdir, &with_label, &with_tags, &qbitdir, comChannel, totaljobs)
2017-12-26 16:25:10 +01:00
}
}
2018-04-02 12:17:50 +02:00
for message := range comChannel {
fmt.Printf("%v/%v %v \n", numjob, totaljobs, message)
numjob++
2018-04-09 15:02:46 +02:00
if numjob-1 == totaljobs {
2018-04-04 12:00:46 +02:00
break
}
2018-04-02 12:17:50 +02:00
}
fmt.Println("\nPress Enter to exit")
fmt.Scanln()
2018-04-09 15:02:46 +02:00
}