Compare commits
10 Commits
Author | SHA1 | Date | |
---|---|---|---|
d6341c9844 | |||
1fac8757d0 | |||
aba7382113 | |||
a5e9b6745f | |||
224e7892ef | |||
6e5ba2c755 | |||
cbfcba4cbc | |||
d15bb9752a | |||
35a5ac37eb | |||
4909429390 |
4
.gitignore
vendored
4
.gitignore
vendored
@@ -2,6 +2,7 @@ downloads/
|
|||||||
downloading/
|
downloading/
|
||||||
downloaded/
|
downloaded/
|
||||||
uploadedTorrents/
|
uploadedTorrents/
|
||||||
|
boltBrowser/
|
||||||
storage.db.lock
|
storage.db.lock
|
||||||
storage.db
|
storage.db
|
||||||
storage.db.old
|
storage.db.old
|
||||||
@@ -23,4 +24,5 @@ config.toml.old
|
|||||||
/public/static/js/kickwebsocket.js.backup
|
/public/static/js/kickwebsocket.js.backup
|
||||||
/public/static/js/kickwebsocket-generated.js
|
/public/static/js/kickwebsocket-generated.js
|
||||||
clientAuth.txt
|
clientAuth.txt
|
||||||
dist
|
dist
|
||||||
|
debScripts/
|
3
Dockerfile
Normal file
3
Dockerfile
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
FROM scratch
|
||||||
|
COPY goTorrent /
|
||||||
|
ENTRYPOINT [ "/goTorrent" ]
|
11
config.toml
11
config.toml
@@ -1,7 +1,7 @@
|
|||||||
[serverConfig]
|
[serverConfig]
|
||||||
|
|
||||||
ServerPort = ":8000" #leave format as is it expects a string with colon
|
ServerPort = ":8000" #leave format as is it expects a string with colon
|
||||||
ServerAddr = "192.168.1.100" #Put in the IP address you want to bind to
|
ServerAddr = "192.168.1.8" #Put in the IP address you want to bind to
|
||||||
LogLevel = "Info" # Options = Debug, Info, Warn, Error, Fatal, Panic
|
LogLevel = "Info" # Options = Debug, Info, Warn, Error, Fatal, Panic
|
||||||
LogOutput = "stdout" #Options = file, stdout #file will print it to logs/server.log
|
LogOutput = "stdout" #Options = file, stdout #file will print it to logs/server.log
|
||||||
|
|
||||||
@@ -15,6 +15,8 @@
|
|||||||
#Low = ~.05MB/s, Medium = ~.5MB/s, High = ~1.5MB/s
|
#Low = ~.05MB/s, Medium = ~.5MB/s, High = ~1.5MB/s
|
||||||
UploadRateLimit = "Unlimited" #Options are "Low", "Medium", "High", "Unlimited" #Unlimited is default
|
UploadRateLimit = "Unlimited" #Options are "Low", "Medium", "High", "Unlimited" #Unlimited is default
|
||||||
DownloadRateLimit = "Unlimited"
|
DownloadRateLimit = "Unlimited"
|
||||||
|
#Maximum number of allowed active torrents, the rest will be queued
|
||||||
|
MaxActiveTorrents = 5
|
||||||
|
|
||||||
[goTorrentWebUI]
|
[goTorrentWebUI]
|
||||||
#Basic goTorrentWebUI authentication (not terribly secure, implemented in JS, password is hashed to SHA256, not salted, basically don't depend on this if you require very good security)
|
#Basic goTorrentWebUI authentication (not terribly secure, implemented in JS, password is hashed to SHA256, not salted, basically don't depend on this if you require very good security)
|
||||||
@@ -33,6 +35,13 @@
|
|||||||
#URL is CASE SENSITIVE
|
#URL is CASE SENSITIVE
|
||||||
BaseURL = "domain.com/subroute/" # MUST be in the format (if you have a subdomain, and must have trailing slash) "yoursubdomain.domain.org/subroute/"
|
BaseURL = "domain.com/subroute/" # MUST be in the format (if you have a subdomain, and must have trailing slash) "yoursubdomain.domain.org/subroute/"
|
||||||
|
|
||||||
|
[socksProxy]
|
||||||
|
SocksProxyEnabled = false #bool, either false or true
|
||||||
|
# Sets usage of Socks5 Proxy. Authentication should be included in the url if needed.
|
||||||
|
# Examples: socks5://demo:demo@192.168.99.100:1080
|
||||||
|
# http://proxy.domain.com:3128
|
||||||
|
SocksProxyURL = ""
|
||||||
|
|
||||||
[EncryptionPolicy]
|
[EncryptionPolicy]
|
||||||
|
|
||||||
DisableEncryption = false
|
DisableEncryption = false
|
||||||
|
@@ -22,7 +22,7 @@ func InitializeCronEngine() *cron.Cron {
|
|||||||
}
|
}
|
||||||
|
|
||||||
//CheckTorrentWatchFolder adds torrents from a watch folder //TODO see if you can use filepath.Abs instead of changing directory
|
//CheckTorrentWatchFolder adds torrents from a watch folder //TODO see if you can use filepath.Abs instead of changing directory
|
||||||
func CheckTorrentWatchFolder(c *cron.Cron, db *storm.DB, tclient *torrent.Client, torrentLocalStorage Storage.TorrentLocal, config Settings.FullClientSettings) {
|
func CheckTorrentWatchFolder(c *cron.Cron, db *storm.DB, tclient *torrent.Client, torrentLocalStorage Storage.TorrentLocal, config Settings.FullClientSettings, torrentQueues Storage.TorrentQueues) {
|
||||||
c.AddFunc("@every 5m", func() {
|
c.AddFunc("@every 5m", func() {
|
||||||
Logger.WithFields(logrus.Fields{"Watch Folder": config.TorrentWatchFolder}).Info("Running the watch folder cron job")
|
Logger.WithFields(logrus.Fields{"Watch Folder": config.TorrentWatchFolder}).Info("Running the watch folder cron job")
|
||||||
torrentFiles, err := ioutil.ReadDir(config.TorrentWatchFolder)
|
torrentFiles, err := ioutil.ReadDir(config.TorrentWatchFolder)
|
||||||
@@ -50,15 +50,62 @@ func CheckTorrentWatchFolder(c *cron.Cron, db *storm.DB, tclient *torrent.Client
|
|||||||
|
|
||||||
os.Remove(fullFilePathAbs) //delete the torrent after adding it and copying it over
|
os.Remove(fullFilePathAbs) //delete the torrent after adding it and copying it over
|
||||||
Logger.WithFields(logrus.Fields{"Source Folder": fullFilePathAbs, "Destination Folder": fullNewFilePathAbs, "Torrent": file.Name()}).Info("Added torrent from watch folder, and moved torrent file")
|
Logger.WithFields(logrus.Fields{"Source Folder": fullFilePathAbs, "Destination Folder": fullNewFilePathAbs, "Torrent": file.Name()}).Info("Added torrent from watch folder, and moved torrent file")
|
||||||
StartTorrent(clientTorrent, torrentLocalStorage, db, "file", fullNewFilePathAbs, config.DefaultMoveFolder, "default", config)
|
AddTorrent(clientTorrent, torrentLocalStorage, db, "file", fullNewFilePathAbs, config.DefaultMoveFolder, "default", config)
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//CheckTorrents runs a upload ratio check, a queue check (essentially anything that should not be frontend dependent)
|
||||||
|
func CheckTorrentsCron(c *cron.Cron, db *storm.DB, tclient *torrent.Client, config Settings.FullClientSettings) {
|
||||||
|
c.AddFunc("@every 30s", func() {
|
||||||
|
Logger.Debug("Running a torrent Ratio and Queue Check")
|
||||||
|
torrentLocalArray := Storage.FetchAllStoredTorrents(db)
|
||||||
|
torrentQueues := Storage.FetchQueues(db)
|
||||||
|
for _, singleTorrentFromStorage := range torrentLocalArray {
|
||||||
|
//torrentQueues := Storage.FetchQueues(db)
|
||||||
|
var singleTorrent *torrent.Torrent
|
||||||
|
for _, liveTorrent := range tclient.Torrents() { //matching the torrent from storage to the live torrent
|
||||||
|
if singleTorrentFromStorage.Hash == liveTorrent.InfoHash().String() {
|
||||||
|
singleTorrent = liveTorrent
|
||||||
|
}
|
||||||
|
}
|
||||||
|
//var TempHash metainfo.Hash
|
||||||
|
//calculatedTotalSize := CalculateDownloadSize(singleTorrentFromStorage, singleTorrent)
|
||||||
|
calculatedCompletedSize := CalculateCompletedSize(singleTorrentFromStorage, singleTorrent)
|
||||||
|
//TempHash = singleTorrent.InfoHash()
|
||||||
|
bytesCompleted := CalculateCompletedSize(singleTorrentFromStorage, singleTorrent)
|
||||||
|
if float64(singleTorrentFromStorage.UploadedBytes)/float64(bytesCompleted) >= config.SeedRatioStop && singleTorrentFromStorage.TorrentUploadLimit == true { //If storage shows torrent stopped or if it is over the seeding ratio AND is under the global limit
|
||||||
|
StopTorrent(singleTorrent, singleTorrentFromStorage, db)
|
||||||
|
}
|
||||||
|
if len(torrentQueues.ActiveTorrents) < config.MaxActiveTorrents && singleTorrentFromStorage.TorrentStatus == "Queued" {
|
||||||
|
Logger.WithFields(logrus.Fields{"Action: Adding Torrent to Active Queue": singleTorrentFromStorage.TorrentName}).Info()
|
||||||
|
AddTorrentToActive(singleTorrentFromStorage, singleTorrent, db)
|
||||||
|
}
|
||||||
|
if (calculatedCompletedSize == singleTorrentFromStorage.TorrentSize) && (singleTorrentFromStorage.TorrentMoved == false) { //if we are done downloading and haven't moved torrent yet
|
||||||
|
Logger.WithFields(logrus.Fields{"singleTorrent": singleTorrentFromStorage.TorrentName}).Info("Torrent Completed, moving...")
|
||||||
|
tStorage := Storage.FetchTorrentFromStorage(db, singleTorrent.InfoHash().String()) //Todo... find a better way to do this in the go-routine currently just to make sure it doesn't trigger multiple times
|
||||||
|
tStorage.TorrentMoved = true
|
||||||
|
Storage.UpdateStorageTick(db, tStorage)
|
||||||
|
go func() { //moving torrent in separate go-routine then verifying that the data is still there and correct
|
||||||
|
err := MoveAndLeaveSymlink(config, singleTorrent.InfoHash().String(), db, false, "") //can take some time to move file so running this in another thread TODO make this a goroutine and skip this block if the routine is still running
|
||||||
|
if err != nil { //If we fail, print the error and attempt a retry
|
||||||
|
Logger.WithFields(logrus.Fields{"singleTorrent": singleTorrentFromStorage.TorrentName, "error": err}).Error("Failed to move Torrent!")
|
||||||
|
VerifyData(singleTorrent)
|
||||||
|
tStorage.TorrentMoved = false
|
||||||
|
Storage.UpdateStorageTick(db, tStorage)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
ValidateQueues(db, config, tclient) //Ensure we don't have too many in activeQueue
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
//RefreshRSSCron refreshes all of the RSS feeds on an hourly basis
|
//RefreshRSSCron refreshes all of the RSS feeds on an hourly basis
|
||||||
func RefreshRSSCron(c *cron.Cron, db *storm.DB, tclient *torrent.Client, torrentLocalStorage Storage.TorrentLocal, config Settings.FullClientSettings) {
|
func RefreshRSSCron(c *cron.Cron, db *storm.DB, tclient *torrent.Client, torrentLocalStorage Storage.TorrentLocal, config Settings.FullClientSettings, torrentQueues Storage.TorrentQueues) {
|
||||||
c.AddFunc("@hourly", func() {
|
c.AddFunc("@hourly", func() {
|
||||||
torrentHashHistory := Storage.FetchHashHistory(db)
|
torrentHashHistory := Storage.FetchHashHistory(db)
|
||||||
RSSFeedStore := Storage.FetchRSSFeeds(db)
|
RSSFeedStore := Storage.FetchRSSFeeds(db)
|
||||||
@@ -86,7 +133,7 @@ func RefreshRSSCron(c *cron.Cron, db *storm.DB, tclient *torrent.Client, torrent
|
|||||||
Logger.WithFields(logrus.Fields{"err": err, "Torrent": RSSTorrent.Title}).Warn("Unable to add torrent to torrent client!")
|
Logger.WithFields(logrus.Fields{"err": err, "Torrent": RSSTorrent.Title}).Warn("Unable to add torrent to torrent client!")
|
||||||
break //break out of the loop entirely for this message since we hit an error
|
break //break out of the loop entirely for this message since we hit an error
|
||||||
}
|
}
|
||||||
StartTorrent(clientTorrent, torrentLocalStorage, db, "magnet", "", config.DefaultMoveFolder, "RSS", config) //TODO let user specify torrent default storage location and let change on fly
|
AddTorrent(clientTorrent, torrentLocalStorage, db, "magnet", "", config.DefaultMoveFolder, "RSS", config) //TODO let user specify torrent default storage location and let change on fly
|
||||||
singleFeed.Torrents = append(singleFeed.Torrents, singleRSSTorrent)
|
singleFeed.Torrents = append(singleFeed.Torrents, singleRSSTorrent)
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@@ -68,7 +68,6 @@ func MoveAndLeaveSymlink(config Settings.FullClientSettings, tHash string, db *s
|
|||||||
Logger.WithFields(logrus.Fields{"Old File Path": oldFilePath, "New File Path": newFilePath, "error": err}).Error("Error Copying Folder!")
|
Logger.WithFields(logrus.Fields{"Old File Path": oldFilePath, "New File Path": newFilePath, "error": err}).Error("Error Copying Folder!")
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
//os.Chmod(newFilePath, 0777)
|
|
||||||
err = filepath.Walk(newFilePath, func(path string, info os.FileInfo, err error) error { //Walking the file path to change the permissions
|
err = filepath.Walk(newFilePath, func(path string, info os.FileInfo, err error) error { //Walking the file path to change the permissions
|
||||||
if err != nil {
|
if err != nil {
|
||||||
Logger.WithFields(logrus.Fields{"file": path, "error": err}).Error("Potentially non-critical error, continuing..")
|
Logger.WithFields(logrus.Fields{"file": path, "error": err}).Error("Potentially non-critical error, continuing..")
|
||||||
|
127
engine/engine.go
127
engine/engine.go
@@ -129,15 +129,16 @@ func readTorrentFileFromDB(element *Storage.TorrentLocal, tclient *torrent.Clien
|
|||||||
return singleTorrent, nil
|
return singleTorrent, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
//StartTorrent creates the storage.db entry and starts A NEW TORRENT and adds to the running torrent array
|
//AddTorrent creates the storage.db entry and starts A NEW TORRENT and adds to the running torrent array
|
||||||
func StartTorrent(clientTorrent *torrent.Torrent, torrentLocalStorage Storage.TorrentLocal, torrentDbStorage *storm.DB, torrentType, torrentFilePathAbs, torrentStoragePath, labelValue string, config Settings.FullClientSettings) {
|
func AddTorrent(clientTorrent *torrent.Torrent, torrentLocalStorage Storage.TorrentLocal, db *storm.DB, torrentType, torrentFilePathAbs, torrentStoragePath, labelValue string, config Settings.FullClientSettings) {
|
||||||
timedOut := timeOutInfo(clientTorrent, 45) //seeing if adding the torrent times out (giving 45 seconds)
|
timedOut := timeOutInfo(clientTorrent, 45) //seeing if adding the torrent times out (giving 45 seconds)
|
||||||
if timedOut { //if we fail to add the torrent return
|
if timedOut { //if we fail to add the torrent return
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
var TempHash metainfo.Hash
|
var TempHash metainfo.Hash
|
||||||
TempHash = clientTorrent.InfoHash()
|
TempHash = clientTorrent.InfoHash()
|
||||||
allStoredTorrents := Storage.FetchAllStoredTorrents(torrentDbStorage)
|
fmt.Println("GOT INFOHASH", TempHash.String())
|
||||||
|
allStoredTorrents := Storage.FetchAllStoredTorrents(db)
|
||||||
for _, runningTorrentHashes := range allStoredTorrents {
|
for _, runningTorrentHashes := range allStoredTorrents {
|
||||||
if runningTorrentHashes.Hash == TempHash.String() {
|
if runningTorrentHashes.Hash == TempHash.String() {
|
||||||
Logger.WithFields(logrus.Fields{"Hash": TempHash.String()}).Info("Torrent has duplicate hash to already running torrent... will not add to storage")
|
Logger.WithFields(logrus.Fields{"Hash": TempHash.String()}).Info("Torrent has duplicate hash to already running torrent... will not add to storage")
|
||||||
@@ -164,7 +165,7 @@ func StartTorrent(clientTorrent *torrent.Torrent, torrentLocalStorage Storage.To
|
|||||||
}
|
}
|
||||||
torrentLocalStorage.TorrentFile = torrentfile //storing the entire file in to database
|
torrentLocalStorage.TorrentFile = torrentfile //storing the entire file in to database
|
||||||
}
|
}
|
||||||
Logger.WithFields(logrus.Fields{"Storage Path": torrentStoragePath, "Torrent Name": clientTorrent.Name()}).Info("Adding Torrent with following storage path")
|
Logger.WithFields(logrus.Fields{"Storage Path": torrentStoragePath, "Torrent Name": clientTorrent.Name()}).Info("Adding Torrent with following storage path, to active Queue")
|
||||||
torrentFiles := clientTorrent.Files() //storing all of the files in the database along with the priority
|
torrentFiles := clientTorrent.Files() //storing all of the files in the database along with the priority
|
||||||
var TorrentFilePriorityArray = []Storage.TorrentFilePriority{}
|
var TorrentFilePriorityArray = []Storage.TorrentFilePriority{}
|
||||||
for _, singleFile := range torrentFiles { //creating the database setup for the file array
|
for _, singleFile := range torrentFiles { //creating the database setup for the file array
|
||||||
@@ -175,20 +176,14 @@ func StartTorrent(clientTorrent *torrent.Torrent, torrentLocalStorage Storage.To
|
|||||||
TorrentFilePriorityArray = append(TorrentFilePriorityArray, torrentFilePriority)
|
TorrentFilePriorityArray = append(TorrentFilePriorityArray, torrentFilePriority)
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
torrentLocalStorage.TorrentFilePriority = TorrentFilePriorityArray
|
torrentLocalStorage.TorrentFilePriority = TorrentFilePriorityArray
|
||||||
Storage.AddTorrentLocalStorage(torrentDbStorage, torrentLocalStorage) //writing all of the data to the database
|
//torrentQueues := Storage.FetchQueues(db)
|
||||||
clientTorrent.DownloadAll() //set all pieces to download
|
AddTorrentToActive(&torrentLocalStorage, clientTorrent, db)
|
||||||
NumPieces := clientTorrent.NumPieces() //find the number of pieces
|
Storage.AddTorrentLocalStorage(db, torrentLocalStorage) //writing all of the data to the database
|
||||||
clientTorrent.CancelPieces(1, NumPieces) //cancel all of the pieces to use file priority
|
|
||||||
for _, singleFile := range clientTorrent.Files() { //setting all of the file priorities to normal
|
|
||||||
singleFile.SetPriority(torrent.PiecePriorityNormal)
|
|
||||||
}
|
|
||||||
CreateServerPushMessage(ServerPushMessage{MessageType: "serverPushMessage", MessageLevel: "success", Payload: "Torrent added!"}, Conn)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
//CreateInitialTorrentArray adds all the torrents on program start from the database
|
//CreateInitialTorrentArray adds all the torrents on program start from the database
|
||||||
func CreateInitialTorrentArray(tclient *torrent.Client, TorrentLocalArray []*Storage.TorrentLocal, db *storm.DB) {
|
func CreateInitialTorrentArray(tclient *torrent.Client, TorrentLocalArray []*Storage.TorrentLocal, db *storm.DB, config Settings.FullClientSettings) {
|
||||||
for _, singleTorrentFromStorage := range TorrentLocalArray {
|
for _, singleTorrentFromStorage := range TorrentLocalArray {
|
||||||
var singleTorrent *torrent.Torrent
|
var singleTorrent *torrent.Torrent
|
||||||
var err error
|
var err error
|
||||||
@@ -203,7 +198,6 @@ func CreateInitialTorrentArray(tclient *torrent.Client, TorrentLocalArray []*Sto
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
if len(singleTorrentFromStorage.InfoBytes) == 0 { //TODO.. kind of a fringe scenario.. not sure if needed since the db should always have the infobytes
|
if len(singleTorrentFromStorage.InfoBytes) == 0 { //TODO.. kind of a fringe scenario.. not sure if needed since the db should always have the infobytes
|
||||||
timeOut := timeOutInfo(singleTorrent, 45)
|
timeOut := timeOutInfo(singleTorrent, 45)
|
||||||
@@ -218,74 +212,103 @@ func CreateInitialTorrentArray(tclient *torrent.Client, TorrentLocalArray []*Sto
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
Logger.WithFields(logrus.Fields{"torrentFile": singleTorrent.Name(), "error": err}).Error("Unable to add infobytes to the torrent!")
|
Logger.WithFields(logrus.Fields{"torrentFile": singleTorrent.Name(), "error": err}).Error("Unable to add infobytes to the torrent!")
|
||||||
}
|
}
|
||||||
if singleTorrentFromStorage.TorrentStatus != "Completed" && singleTorrentFromStorage.TorrentStatus != "Stopped" {
|
torrentQueues := Storage.FetchQueues(db)
|
||||||
singleTorrent.DownloadAll() //set all of the pieces to download (piece prio is NE to file prio)
|
if singleTorrentFromStorage.TorrentStatus == "Stopped" {
|
||||||
NumPieces := singleTorrent.NumPieces() //find the number of pieces
|
singleTorrent.SetMaxEstablishedConns(0)
|
||||||
singleTorrent.CancelPieces(1, NumPieces) //cancel all of the pieces to use file priority
|
continue
|
||||||
for _, singleFile := range singleTorrent.Files() { //setting all of the file priorities to normal
|
}
|
||||||
singleFile.SetPriority(torrent.PiecePriorityNormal)
|
if singleTorrentFromStorage.TorrentStatus == "ForceStart" {
|
||||||
|
AddTorrentToForceStart(singleTorrentFromStorage, singleTorrent, db)
|
||||||
|
}
|
||||||
|
if len(torrentQueues.ActiveTorrents) == 0 && len(torrentQueues.QueuedTorrents) == 0 { // If empty, run through all the torrents and assign them
|
||||||
|
if len(torrentQueues.ActiveTorrents) < Config.MaxActiveTorrents {
|
||||||
|
if singleTorrentFromStorage.TorrentStatus == "Completed" || singleTorrentFromStorage.TorrentStatus == "Seeding" {
|
||||||
|
Logger.WithFields(logrus.Fields{"Torrent Name": singleTorrentFromStorage.TorrentName}).Info("Completed Torrents have lower priority, adding to Queued")
|
||||||
|
AddTorrentToQueue(singleTorrentFromStorage, singleTorrent, db)
|
||||||
|
} else {
|
||||||
|
Logger.WithFields(logrus.Fields{"Torrent Name": singleTorrentFromStorage.TorrentName}).Info("Adding Torrent to Active Queue (Initial Torrent Load)")
|
||||||
|
AddTorrentToActive(singleTorrentFromStorage, singleTorrent, db)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Logger.WithFields(logrus.Fields{"Torrent Name": singleTorrentFromStorage.TorrentName}).Info("Last resort for torrent, adding to Queued")
|
||||||
|
AddTorrentToQueue(singleTorrentFromStorage, singleTorrent, db)
|
||||||
|
}
|
||||||
|
} else { //If we already have a queue set up then assign torrents to queue
|
||||||
|
if singleTorrentFromStorage.TorrentStatus == "Queued" {
|
||||||
|
AddTorrentToQueue(singleTorrentFromStorage, singleTorrent, db)
|
||||||
|
} else {
|
||||||
|
if len(torrentQueues.ActiveTorrents) < Config.MaxActiveTorrents {
|
||||||
|
Logger.WithFields(logrus.Fields{"Torrent Name": singleTorrentFromStorage.TorrentName}).Info("Adding Torrent to Active Queue (Initial Torrent Load Second)")
|
||||||
|
AddTorrentToActive(singleTorrentFromStorage, singleTorrent, db)
|
||||||
|
} else {
|
||||||
|
AddTorrentToQueue(singleTorrentFromStorage, singleTorrent, db)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
RemoveDuplicatesFromQueues(db)
|
||||||
|
}
|
||||||
|
Storage.UpdateStorageTick(db, *singleTorrentFromStorage)
|
||||||
|
}
|
||||||
|
torrentQueues := Storage.FetchQueues(db)
|
||||||
|
if len(torrentQueues.ActiveTorrents) < config.MaxActiveTorrents && len(torrentQueues.QueuedTorrents) > 0 { //after all the torrents are added, see if out active torrent list isn't full, then add from the queue
|
||||||
|
Logger.WithFields(logrus.Fields{"Max Active: ": config.MaxActiveTorrents, "Current : ": torrentQueues.ActiveTorrents}).Info("Adding Torrents from queue to active to fill...")
|
||||||
|
maxCanSend := config.MaxActiveTorrents - len(torrentQueues.ActiveTorrents)
|
||||||
|
if maxCanSend > len(torrentQueues.QueuedTorrents) {
|
||||||
|
maxCanSend = len(torrentQueues.QueuedTorrents)
|
||||||
|
}
|
||||||
|
torrentsToStart := make([]string, maxCanSend)
|
||||||
|
copy(torrentsToStart, torrentQueues.QueuedTorrents[len(torrentsToStart)-1:])
|
||||||
|
for _, torrentStart := range torrentsToStart {
|
||||||
|
for _, singleTorrent := range tclient.Torrents() {
|
||||||
|
if singleTorrent.InfoHash().String() == torrentStart {
|
||||||
|
singleTorrentFromStorage := Storage.FetchTorrentFromStorage(db, torrentStart)
|
||||||
|
AddTorrentToActive(&singleTorrentFromStorage, singleTorrent, db)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
SetFilePriority(tclient, db) //Setting the desired file priority from storage
|
SetFilePriority(tclient, db) //Setting the desired file priority from storage
|
||||||
|
Logger.WithFields(logrus.Fields{"Max Active: ": config.MaxActiveTorrents, "Current : ": torrentQueues.ActiveTorrents}).Debug("Queue after all initial torrents have been added")
|
||||||
}
|
}
|
||||||
|
|
||||||
//CreateRunningTorrentArray creates the entire torrent list to pass to client
|
//CreateRunningTorrentArray creates the entire torrent list to pass to client
|
||||||
func CreateRunningTorrentArray(tclient *torrent.Client, TorrentLocalArray []*Storage.TorrentLocal, PreviousTorrentArray []ClientDB, config Settings.FullClientSettings, db *storm.DB) (RunningTorrentArray []ClientDB) {
|
func CreateRunningTorrentArray(tclient *torrent.Client, TorrentLocalArray []*Storage.TorrentLocal, PreviousTorrentArray []ClientDB, config Settings.FullClientSettings, db *storm.DB) (RunningTorrentArray []ClientDB) {
|
||||||
|
torrentQueues := Storage.FetchQueues(db)
|
||||||
|
Logger.WithFields(logrus.Fields{"Max Active: ": config.MaxActiveTorrents, "TorrentQueues": torrentQueues}).Debug("Current TorrentQueues")
|
||||||
for _, singleTorrentFromStorage := range TorrentLocalArray {
|
for _, singleTorrentFromStorage := range TorrentLocalArray {
|
||||||
|
torrentQueues := Storage.FetchQueues(db)
|
||||||
var singleTorrent *torrent.Torrent
|
var singleTorrent *torrent.Torrent
|
||||||
var TempHash metainfo.Hash
|
|
||||||
for _, liveTorrent := range tclient.Torrents() { //matching the torrent from storage to the live torrent
|
for _, liveTorrent := range tclient.Torrents() { //matching the torrent from storage to the live torrent
|
||||||
if singleTorrentFromStorage.Hash == liveTorrent.InfoHash().String() {
|
if singleTorrentFromStorage.Hash == liveTorrent.InfoHash().String() {
|
||||||
singleTorrent = liveTorrent
|
singleTorrent = liveTorrent
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
tickUpdateStruct := Storage.TorrentLocal{} //we are shoving the tick updates into a torrentlocal struct to pass to storage happens at the end of the routine
|
tickUpdateStruct := Storage.TorrentLocal{} //we are shoving the tick updates into a torrentlocal struct to pass to storage happens at the end of the routine
|
||||||
|
|
||||||
fullClientDB := new(ClientDB)
|
fullClientDB := new(ClientDB)
|
||||||
//singleTorrentStorageInfo := Storage.FetchTorrentFromStorage(db, TempHash.String()) //pulling the single torrent info from storage ()
|
//Handling deleted torrents here
|
||||||
|
|
||||||
if singleTorrentFromStorage.TorrentStatus == "Dropped" {
|
if singleTorrentFromStorage.TorrentStatus == "Dropped" {
|
||||||
Logger.WithFields(logrus.Fields{"selection": singleTorrentFromStorage.TorrentName}).Info("Deleting just the torrent")
|
Logger.WithFields(logrus.Fields{"selection": singleTorrentFromStorage.TorrentName}).Info("Deleting just the torrent")
|
||||||
|
DeleteTorrentFromQueues(singleTorrentFromStorage.Hash, db)
|
||||||
singleTorrent.Drop()
|
singleTorrent.Drop()
|
||||||
Storage.DelTorrentLocalStorage(db, singleTorrentFromStorage.Hash)
|
Storage.DelTorrentLocalStorage(db, singleTorrentFromStorage.Hash)
|
||||||
}
|
}
|
||||||
if singleTorrentFromStorage.TorrentStatus == "DroppedData" {
|
if singleTorrentFromStorage.TorrentStatus == "DroppedData" {
|
||||||
Logger.WithFields(logrus.Fields{"selection": singleTorrentFromStorage.TorrentName}).Info("Deleting just the torrent")
|
Logger.WithFields(logrus.Fields{"selection": singleTorrentFromStorage.TorrentName}).Info("Deleting torrent and data")
|
||||||
singleTorrent.Drop()
|
singleTorrent.Drop()
|
||||||
|
DeleteTorrentFromQueues(singleTorrentFromStorage.Hash, db)
|
||||||
Storage.DelTorrentLocalStorageAndFiles(db, singleTorrentFromStorage.Hash, Config.TorrentConfig.DataDir)
|
Storage.DelTorrentLocalStorageAndFiles(db, singleTorrentFromStorage.Hash, Config.TorrentConfig.DataDir)
|
||||||
|
|
||||||
}
|
}
|
||||||
if singleTorrentFromStorage.TorrentType == "file" { //if it is a file pull it from the uploaded torrent folder
|
if singleTorrentFromStorage.TorrentType == "file" { //if it is a file pull it from the uploaded torrent folder
|
||||||
fullClientDB.SourceType = "Torrent File"
|
fullClientDB.SourceType = "Torrent File"
|
||||||
} else {
|
} else {
|
||||||
fullClientDB.SourceType = "Magnet Link"
|
fullClientDB.SourceType = "Magnet Link"
|
||||||
}
|
}
|
||||||
|
var TempHash metainfo.Hash
|
||||||
|
TempHash = singleTorrent.InfoHash()
|
||||||
|
|
||||||
calculatedTotalSize := CalculateDownloadSize(singleTorrentFromStorage, singleTorrent)
|
calculatedTotalSize := CalculateDownloadSize(singleTorrentFromStorage, singleTorrent)
|
||||||
calculatedCompletedSize := CalculateCompletedSize(singleTorrentFromStorage, singleTorrent)
|
calculatedCompletedSize := CalculateCompletedSize(singleTorrentFromStorage, singleTorrent)
|
||||||
TempHash = singleTorrent.InfoHash()
|
|
||||||
if (calculatedCompletedSize == singleTorrentFromStorage.TorrentSize) && (singleTorrentFromStorage.TorrentMoved == false) { //if we are done downloading and haven't moved torrent yet
|
|
||||||
Logger.WithFields(logrus.Fields{"singleTorrent": singleTorrentFromStorage.TorrentName}).Info("Torrent Completed, moving...")
|
|
||||||
tStorage := Storage.FetchTorrentFromStorage(db, singleTorrent.InfoHash().String()) //Todo... find a better way to do this in the go-routine currently just to make sure it doesn't trigger multiple times
|
|
||||||
tStorage.TorrentMoved = true
|
|
||||||
Storage.UpdateStorageTick(db, tStorage)
|
|
||||||
go func() { //moving torrent in separate go-routine then verifying that the data is still there and correct
|
|
||||||
err := MoveAndLeaveSymlink(config, singleTorrent.InfoHash().String(), db, false, "") //can take some time to move file so running this in another thread TODO make this a goroutine and skip this block if the routine is still running
|
|
||||||
if err != nil { //If we fail, print the error and attempt a retry
|
|
||||||
Logger.WithFields(logrus.Fields{"singleTorrent": singleTorrentFromStorage.TorrentName, "error": err}).Error("Failed to move Torrent!")
|
|
||||||
VerifyData(singleTorrent)
|
|
||||||
tStorage.TorrentMoved = false
|
|
||||||
Storage.UpdateStorageTick(db, tStorage)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
fullStruct := singleTorrent.Stats()
|
fullStruct := singleTorrent.Stats()
|
||||||
|
|
||||||
activePeersString := strconv.Itoa(fullStruct.ActivePeers) //converting to strings
|
activePeersString := strconv.Itoa(fullStruct.ActivePeers) //converting to strings
|
||||||
totalPeersString := fmt.Sprintf("%v", fullStruct.TotalPeers)
|
totalPeersString := fmt.Sprintf("%v", fullStruct.TotalPeers)
|
||||||
fullClientDB.StoragePath = singleTorrentFromStorage.StoragePath
|
fullClientDB.StoragePath = singleTorrentFromStorage.StoragePath
|
||||||
@@ -298,8 +321,8 @@ func CreateRunningTorrentArray(tclient *torrent.Client, TorrentLocalArray []*Sto
|
|||||||
PercentDone := fmt.Sprintf("%.2f", float32(calculatedCompletedSize)/float32(calculatedTotalSize))
|
PercentDone := fmt.Sprintf("%.2f", float32(calculatedCompletedSize)/float32(calculatedTotalSize))
|
||||||
fullClientDB.TorrentHash = TempHash
|
fullClientDB.TorrentHash = TempHash
|
||||||
fullClientDB.PercentDone = PercentDone
|
fullClientDB.PercentDone = PercentDone
|
||||||
fullClientDB.DataBytesRead = fullStruct.ConnStats.BytesReadData //used for calculations not passed to client calculating up/down speed
|
fullClientDB.DataBytesRead = fullStruct.ConnStats.BytesReadData.Int64() //used for calculations not passed to client calculating up/down speed
|
||||||
fullClientDB.DataBytesWritten = fullStruct.ConnStats.BytesWrittenData //used for calculations not passed to client calculating up/down speed
|
fullClientDB.DataBytesWritten = fullStruct.ConnStats.BytesWrittenData.Int64() //used for calculations not passed to client calculating up/down speed
|
||||||
fullClientDB.ActivePeers = activePeersString + " / (" + totalPeersString + ")"
|
fullClientDB.ActivePeers = activePeersString + " / (" + totalPeersString + ")"
|
||||||
fullClientDB.TorrentHashString = TempHash.String()
|
fullClientDB.TorrentHashString = TempHash.String()
|
||||||
fullClientDB.TorrentName = singleTorrentFromStorage.TorrentName
|
fullClientDB.TorrentName = singleTorrentFromStorage.TorrentName
|
||||||
@@ -313,7 +336,7 @@ func CreateRunningTorrentArray(tclient *torrent.Client, TorrentLocalArray []*Sto
|
|||||||
TempHash := singleTorrent.InfoHash()
|
TempHash := singleTorrent.InfoHash()
|
||||||
if previousElement.TorrentHashString == TempHash.String() { //matching previous to new
|
if previousElement.TorrentHashString == TempHash.String() { //matching previous to new
|
||||||
CalculateTorrentSpeed(singleTorrent, fullClientDB, previousElement, calculatedCompletedSize)
|
CalculateTorrentSpeed(singleTorrent, fullClientDB, previousElement, calculatedCompletedSize)
|
||||||
fullClientDB.TotalUploadedBytes = singleTorrentFromStorage.UploadedBytes + (fullStruct.ConnStats.BytesWrittenData - previousElement.DataBytesWritten)
|
fullClientDB.TotalUploadedBytes = singleTorrentFromStorage.UploadedBytes + (fullStruct.ConnStats.BytesWrittenData.Int64() - previousElement.DataBytesWritten)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -322,7 +345,7 @@ func CreateRunningTorrentArray(tclient *torrent.Client, TorrentLocalArray []*Sto
|
|||||||
fullClientDB.TotalUploadedSize = HumanizeBytes(float32(fullClientDB.TotalUploadedBytes))
|
fullClientDB.TotalUploadedSize = HumanizeBytes(float32(fullClientDB.TotalUploadedBytes))
|
||||||
fullClientDB.UploadRatio = CalculateUploadRatio(singleTorrent, fullClientDB) //calculate the upload ratio
|
fullClientDB.UploadRatio = CalculateUploadRatio(singleTorrent, fullClientDB) //calculate the upload ratio
|
||||||
|
|
||||||
CalculateTorrentStatus(singleTorrent, fullClientDB, config, singleTorrentFromStorage, calculatedCompletedSize, calculatedTotalSize)
|
CalculateTorrentStatus(singleTorrent, fullClientDB, config, singleTorrentFromStorage, calculatedCompletedSize, calculatedTotalSize, torrentQueues, db) //add torrents to the queue, remove from queue, etc
|
||||||
|
|
||||||
tickUpdateStruct.UploadRatio = fullClientDB.UploadRatio
|
tickUpdateStruct.UploadRatio = fullClientDB.UploadRatio
|
||||||
tickUpdateStruct.TorrentSize = calculatedTotalSize
|
tickUpdateStruct.TorrentSize = calculatedTotalSize
|
||||||
|
@@ -109,7 +109,7 @@ func CalculateTorrentSpeed(t *torrent.Torrent, c *ClientDB, oc ClientDB, complet
|
|||||||
dt := float32(now.Sub(oc.UpdatedAt)) // get the delta time length between now and last updated
|
dt := float32(now.Sub(oc.UpdatedAt)) // get the delta time length between now and last updated
|
||||||
db := float32(bytes - oc.BytesCompleted) //getting the delta bytes
|
db := float32(bytes - oc.BytesCompleted) //getting the delta bytes
|
||||||
rate := db * (float32(time.Second) / dt) // converting into seconds
|
rate := db * (float32(time.Second) / dt) // converting into seconds
|
||||||
dbU := float32(bytesUpload - oc.DataBytesWritten)
|
dbU := float32(bytesUpload.Int64() - oc.DataBytesWritten)
|
||||||
rateUpload := dbU * (float32(time.Second) / dt)
|
rateUpload := dbU * (float32(time.Second) / dt)
|
||||||
if rate >= 0 {
|
if rate >= 0 {
|
||||||
rateMB := rate / 1024 / 1024 //creating MB to calculate ETA
|
rateMB := rate / 1024 / 1024 //creating MB to calculate ETA
|
||||||
@@ -184,28 +184,247 @@ func CalculateUploadRatio(t *torrent.Torrent, c *ClientDB) string {
|
|||||||
return uploadRatio
|
return uploadRatio
|
||||||
}
|
}
|
||||||
|
|
||||||
//CalculateTorrentStatus is used to determine what the STATUS column of the frontend will display ll2
|
//StopTorrent stops the torrent, updates the database and sends a message. Since stoptorrent is called by each loop (individually) no need to call an array
|
||||||
func CalculateTorrentStatus(t *torrent.Torrent, c *ClientDB, config Settings.FullClientSettings, tFromStorage *storage.TorrentLocal, bytesCompleted int64, totalSize int64) {
|
func StopTorrent(singleTorrent *torrent.Torrent, torrentLocalStorage *Storage.TorrentLocal, db *storm.DB) {
|
||||||
if (tFromStorage.TorrentStatus == "Stopped") || (float64(c.TotalUploadedBytes)/float64(bytesCompleted) >= config.SeedRatioStop && tFromStorage.TorrentUploadLimit == true) { //If storage shows torrent stopped or if it is over the seeding ratio AND is under the global limit
|
if torrentLocalStorage.TorrentStatus == "Stopped" { //if we are already stopped
|
||||||
c.Status = "Stopped"
|
Logger.WithFields(logrus.Fields{"Torrent Name": torrentLocalStorage.TorrentName}).Info("Torrent Already Stopped, returning...")
|
||||||
c.MaxConnections = 0
|
return
|
||||||
t.SetMaxEstablishedConns(0)
|
}
|
||||||
|
torrentLocalStorage.TorrentStatus = "Stopped"
|
||||||
|
torrentLocalStorage.MaxConnections = 0
|
||||||
|
singleTorrent.SetMaxEstablishedConns(0)
|
||||||
|
DeleteTorrentFromQueues(singleTorrent.InfoHash().String(), db)
|
||||||
|
Storage.UpdateStorageTick(db, *torrentLocalStorage)
|
||||||
|
CreateServerPushMessage(ServerPushMessage{MessageType: "serverPushMessage", MessageLevel: "success", Payload: "Torrent Stopped!"}, Conn)
|
||||||
|
Logger.WithFields(logrus.Fields{"Torrent Name": torrentLocalStorage.TorrentName}).Info("Torrent Stopped Success!")
|
||||||
|
}
|
||||||
|
|
||||||
} else { //Only has 2 states in storage, stopped or running, so we know it should be running, and the websocket request handled updating the database with connections and status
|
//AddTorrentToForceStart forces torrent to be high priority on start
|
||||||
bytesMissing := totalSize - bytesCompleted
|
func AddTorrentToForceStart(torrentLocalStorage *Storage.TorrentLocal, singleTorrent *torrent.Torrent, db *storm.DB) {
|
||||||
c.MaxConnections = 80
|
torrentQueues := Storage.FetchQueues(db)
|
||||||
t.SetMaxEstablishedConns(80)
|
for index, torrentHash := range torrentQueues.ActiveTorrents {
|
||||||
//t.DownloadAll() //ensure that we are setting the torrent to download
|
if torrentHash == singleTorrent.InfoHash().String() { //If torrent already in active remove from active
|
||||||
if t.Seeding() && t.Stats().ActivePeers > 0 && bytesMissing == 0 {
|
torrentQueues.ActiveTorrents = append(torrentQueues.ActiveTorrents[:index], torrentQueues.ActiveTorrents[index+1:]...)
|
||||||
c.Status = "Seeding"
|
}
|
||||||
} else if t.Stats().ActivePeers > 0 && bytesMissing > 0 {
|
}
|
||||||
c.Status = "Downloading"
|
for index, queuedTorrentHash := range torrentQueues.QueuedTorrents { //Removing from the queued torrents if in queued torrents
|
||||||
} else if t.Stats().ActivePeers == 0 && bytesMissing == 0 {
|
if queuedTorrentHash == singleTorrent.InfoHash().String() {
|
||||||
c.Status = "Completed"
|
torrentQueues.QueuedTorrents = append(torrentQueues.QueuedTorrents[:index], torrentQueues.QueuedTorrents[index+1:]...)
|
||||||
} else if t.Stats().ActivePeers == 0 && bytesMissing > 0 {
|
}
|
||||||
c.Status = "Awaiting Peers"
|
}
|
||||||
} else {
|
singleTorrent.NewReader()
|
||||||
c.Status = "Unknown"
|
singleTorrent.SetMaxEstablishedConns(80)
|
||||||
|
torrentQueues.ActiveTorrents = append(torrentQueues.ActiveTorrents, singleTorrent.InfoHash().String())
|
||||||
|
torrentLocalStorage.TorrentStatus = "ForceStart"
|
||||||
|
torrentLocalStorage.MaxConnections = 80
|
||||||
|
for _, file := range singleTorrent.Files() {
|
||||||
|
for _, sentFile := range torrentLocalStorage.TorrentFilePriority {
|
||||||
|
if file.DisplayPath() == sentFile.TorrentFilePath {
|
||||||
|
switch sentFile.TorrentFilePriority {
|
||||||
|
case "High":
|
||||||
|
file.SetPriority(torrent.PiecePriorityHigh)
|
||||||
|
case "Normal":
|
||||||
|
file.SetPriority(torrent.PiecePriorityNormal)
|
||||||
|
case "Cancel":
|
||||||
|
file.SetPriority(torrent.PiecePriorityNone)
|
||||||
|
default:
|
||||||
|
file.SetPriority(torrent.PiecePriorityNormal)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Logger.WithFields(logrus.Fields{"Torrent Name": torrentLocalStorage.TorrentName}).Info("Adding Torrent to ForceStart Queue")
|
||||||
|
Storage.UpdateStorageTick(db, *torrentLocalStorage)
|
||||||
|
Storage.UpdateQueues(db, torrentQueues)
|
||||||
|
}
|
||||||
|
|
||||||
|
//AddTorrentToActive adds a torrent to the active slice
|
||||||
|
func AddTorrentToActive(torrentLocalStorage *Storage.TorrentLocal, singleTorrent *torrent.Torrent, db *storm.DB) {
|
||||||
|
torrentQueues := Storage.FetchQueues(db)
|
||||||
|
if torrentLocalStorage.TorrentStatus == "Stopped" {
|
||||||
|
Logger.WithFields(logrus.Fields{"Torrent Name": torrentLocalStorage.TorrentName}).Info("Torrent set as stopped, skipping add")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for _, torrentHash := range torrentQueues.ActiveTorrents {
|
||||||
|
if torrentHash == singleTorrent.InfoHash().String() { //If torrent already in active skip
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for index, queuedTorrentHash := range torrentQueues.QueuedTorrents { //Removing from the queued torrents if in queued torrents
|
||||||
|
if queuedTorrentHash == singleTorrent.InfoHash().String() {
|
||||||
|
torrentQueues.QueuedTorrents = append(torrentQueues.QueuedTorrents[:index], torrentQueues.QueuedTorrents[index+1:]...)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
singleTorrent.NewReader()
|
||||||
|
singleTorrent.SetMaxEstablishedConns(80)
|
||||||
|
torrentQueues.ActiveTorrents = append(torrentQueues.ActiveTorrents, singleTorrent.InfoHash().String())
|
||||||
|
torrentLocalStorage.TorrentStatus = "Running"
|
||||||
|
torrentLocalStorage.MaxConnections = 80
|
||||||
|
for _, file := range singleTorrent.Files() {
|
||||||
|
for _, sentFile := range torrentLocalStorage.TorrentFilePriority {
|
||||||
|
if file.DisplayPath() == sentFile.TorrentFilePath {
|
||||||
|
switch sentFile.TorrentFilePriority {
|
||||||
|
case "High":
|
||||||
|
file.SetPriority(torrent.PiecePriorityHigh)
|
||||||
|
case "Normal":
|
||||||
|
file.SetPriority(torrent.PiecePriorityNormal)
|
||||||
|
case "Cancel":
|
||||||
|
file.SetPriority(torrent.PiecePriorityNone)
|
||||||
|
default:
|
||||||
|
file.SetPriority(torrent.PiecePriorityNormal)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Logger.WithFields(logrus.Fields{"Torrent Name": torrentLocalStorage.TorrentName}).Info("Adding Torrent to Active Queue (Manual Call)")
|
||||||
|
Storage.UpdateStorageTick(db, *torrentLocalStorage)
|
||||||
|
Storage.UpdateQueues(db, torrentQueues)
|
||||||
|
}
|
||||||
|
|
||||||
|
//RemoveTorrentFromActive forces a torrent to be removed from the active list if the max limit is already there and user forces a new torrent to be added
|
||||||
|
func RemoveTorrentFromActive(torrentLocalStorage *Storage.TorrentLocal, singleTorrent *torrent.Torrent, db *storm.DB) {
|
||||||
|
torrentQueues := Storage.FetchQueues(db)
|
||||||
|
for x, torrentHash := range torrentQueues.ActiveTorrents {
|
||||||
|
if torrentHash == singleTorrent.InfoHash().String() {
|
||||||
|
torrentQueues.ActiveTorrents = append(torrentQueues.ActiveTorrents[:x], torrentQueues.ActiveTorrents[x+1:]...)
|
||||||
|
torrentQueues.QueuedTorrents = append(torrentQueues.QueuedTorrents, torrentHash)
|
||||||
|
torrentLocalStorage.TorrentStatus = "Queued"
|
||||||
|
torrentLocalStorage.MaxConnections = 0
|
||||||
|
singleTorrent.SetMaxEstablishedConns(0)
|
||||||
|
Storage.UpdateQueues(db, torrentQueues)
|
||||||
|
//AddTorrentToQueue(torrentLocalStorage, singleTorrent, db) //Adding the lasttorrent from active to queued
|
||||||
|
Storage.UpdateStorageTick(db, *torrentLocalStorage)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
//DeleteTorrentFromQueues deletes the torrent from all queues (for a stop or delete action)
|
||||||
|
func DeleteTorrentFromQueues(torrentHash string, db *storm.DB) {
|
||||||
|
torrentQueues := Storage.FetchQueues(db)
|
||||||
|
for x, torrentHashActive := range torrentQueues.ActiveTorrents { //FOR EXTRA CAUTION deleting it from both queues in case a mistake occurred.
|
||||||
|
if torrentHash == torrentHashActive {
|
||||||
|
torrentQueues.ActiveTorrents = append(torrentQueues.ActiveTorrents[:x], torrentQueues.ActiveTorrents[x+1:]...)
|
||||||
|
Logger.Info("Removing Torrent from Active: ", torrentHash)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for x, torrentHashQueued := range torrentQueues.QueuedTorrents { //FOR EXTRA CAUTION deleting it from both queues in case a mistake occurred.
|
||||||
|
if torrentHash == torrentHashQueued {
|
||||||
|
torrentQueues.QueuedTorrents = append(torrentQueues.QueuedTorrents[:x], torrentQueues.QueuedTorrents[x+1:]...)
|
||||||
|
Logger.Info("Removing Torrent from Queued", torrentHash)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for x, torrentHashActive := range torrentQueues.ForcedTorrents { //FOR EXTRA CAUTION deleting it from all queues in case a mistake occurred.
|
||||||
|
if torrentHash == torrentHashActive {
|
||||||
|
torrentQueues.ForcedTorrents = append(torrentQueues.ForcedTorrents[:x], torrentQueues.ForcedTorrents[x+1:]...)
|
||||||
|
Logger.Info("Removing Torrent from Forced: ", torrentHash)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Storage.UpdateQueues(db, torrentQueues)
|
||||||
|
Logger.WithFields(logrus.Fields{"Torrent Hash": torrentHash, "TorrentQueues": torrentQueues}).Info("Removing Torrent from all Queues")
|
||||||
|
}
|
||||||
|
|
||||||
|
//AddTorrentToQueue adds a torrent to the queue
|
||||||
|
func AddTorrentToQueue(torrentLocalStorage *Storage.TorrentLocal, singleTorrent *torrent.Torrent, db *storm.DB) {
|
||||||
|
torrentQueues := Storage.FetchQueues(db)
|
||||||
|
for _, torrentHash := range torrentQueues.QueuedTorrents {
|
||||||
|
if singleTorrent.InfoHash().String() == torrentHash { //don't add duplicate to que but do everything else (TODO, maybe find a better way?)
|
||||||
|
singleTorrent.SetMaxEstablishedConns(0)
|
||||||
|
torrentLocalStorage.MaxConnections = 0
|
||||||
|
torrentLocalStorage.TorrentStatus = "Queued"
|
||||||
|
Logger.WithFields(logrus.Fields{"TorrentName": torrentLocalStorage.TorrentName}).Info("Adding torrent to the queue, not active")
|
||||||
|
Storage.UpdateStorageTick(db, *torrentLocalStorage)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
torrentQueues.QueuedTorrents = append(torrentQueues.QueuedTorrents, singleTorrent.InfoHash().String())
|
||||||
|
singleTorrent.SetMaxEstablishedConns(0)
|
||||||
|
torrentLocalStorage.MaxConnections = 0
|
||||||
|
torrentLocalStorage.TorrentStatus = "Queued"
|
||||||
|
Logger.WithFields(logrus.Fields{"TorrentName": torrentLocalStorage.TorrentName}).Info("Adding torrent to the queue, not active")
|
||||||
|
Storage.UpdateQueues(db, torrentQueues)
|
||||||
|
Storage.UpdateStorageTick(db, *torrentLocalStorage)
|
||||||
|
}
|
||||||
|
|
||||||
|
//RemoveDuplicatesFromQueues removes any duplicates from torrentQueues.QueuedTorrents (which will happen if it is read in from DB)
|
||||||
|
func RemoveDuplicatesFromQueues(db *storm.DB) {
|
||||||
|
torrentQueues := Storage.FetchQueues(db)
|
||||||
|
for _, torrentHash := range torrentQueues.ActiveTorrents {
|
||||||
|
for i, queuedHash := range torrentQueues.QueuedTorrents {
|
||||||
|
if torrentHash == queuedHash {
|
||||||
|
torrentQueues.QueuedTorrents = append(torrentQueues.QueuedTorrents[:i], torrentQueues.QueuedTorrents[i+1:]...)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Storage.UpdateQueues(db, torrentQueues)
|
||||||
|
}
|
||||||
|
|
||||||
|
//ValidateQueues is a sanity check that runs every tick to make sure the queues are in order... tried to avoid this but seems to be required
|
||||||
|
func ValidateQueues(db *storm.DB, config Settings.FullClientSettings, tclient *torrent.Client) {
|
||||||
|
torrentQueues := Storage.FetchQueues(db)
|
||||||
|
for len(torrentQueues.ActiveTorrents) > config.MaxActiveTorrents {
|
||||||
|
removeTorrent := torrentQueues.ActiveTorrents[:1]
|
||||||
|
for _, singleTorrent := range tclient.Torrents() {
|
||||||
|
if singleTorrent.InfoHash().String() == removeTorrent[0] {
|
||||||
|
singleTorrentFromStorage := Storage.FetchTorrentFromStorage(db, removeTorrent[0])
|
||||||
|
RemoveTorrentFromActive(&singleTorrentFromStorage, singleTorrent, db)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
torrentQueues = Storage.FetchQueues(db)
|
||||||
|
for _, singleTorrent := range tclient.Torrents() {
|
||||||
|
singleTorrentFromStorage := Storage.FetchTorrentFromStorage(db, singleTorrent.InfoHash().String())
|
||||||
|
if singleTorrentFromStorage.TorrentStatus == "Stopped" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for _, queuedTorrent := range torrentQueues.QueuedTorrents { //If we have a queued torrent that is missing data, and an active torrent that is seeding, then prioritize the missing data one
|
||||||
|
if singleTorrent.InfoHash().String() == queuedTorrent {
|
||||||
|
if singleTorrent.BytesMissing() > 0 {
|
||||||
|
for _, activeTorrent := range torrentQueues.ActiveTorrents {
|
||||||
|
for _, singleActiveTorrent := range tclient.Torrents() {
|
||||||
|
if activeTorrent == singleActiveTorrent.InfoHash().String() {
|
||||||
|
if singleActiveTorrent.Seeding() == true {
|
||||||
|
singleActiveTFS := Storage.FetchTorrentFromStorage(db, activeTorrent)
|
||||||
|
Logger.WithFields(logrus.Fields{"TorrentName": singleActiveTFS.TorrentName}).Info("Seeding, Removing from active to add queued")
|
||||||
|
RemoveTorrentFromActive(&singleActiveTFS, singleActiveTorrent, db)
|
||||||
|
singleQueuedTFS := Storage.FetchTorrentFromStorage(db, queuedTorrent)
|
||||||
|
Logger.WithFields(logrus.Fields{"TorrentName": singleQueuedTFS.TorrentName}).Info("Adding torrent to the queue, not active")
|
||||||
|
AddTorrentToActive(&singleQueuedTFS, singleTorrent, db)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//CalculateTorrentStatus is used to determine what the STATUS column of the frontend will display ll2
|
||||||
|
func CalculateTorrentStatus(t *torrent.Torrent, c *ClientDB, config Settings.FullClientSettings, tFromStorage *storage.TorrentLocal, bytesCompleted int64, totalSize int64, torrentQueues Storage.TorrentQueues, db *storm.DB) {
|
||||||
|
if tFromStorage.TorrentStatus == "Stopped" {
|
||||||
|
c.Status = "Stopped"
|
||||||
|
return
|
||||||
|
}
|
||||||
|
//Only has 2 states in storage, stopped or running, so we know it should be running, and the websocket request handled updating the database with connections and status
|
||||||
|
for _, torrentHash := range torrentQueues.QueuedTorrents {
|
||||||
|
if tFromStorage.Hash == torrentHash {
|
||||||
|
c.Status = "Queued"
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
bytesMissing := totalSize - bytesCompleted
|
||||||
|
c.MaxConnections = 80
|
||||||
|
t.SetMaxEstablishedConns(80)
|
||||||
|
if t.Seeding() && t.Stats().ActivePeers > 0 && bytesMissing == 0 {
|
||||||
|
c.Status = "Seeding"
|
||||||
|
} else if t.Stats().ActivePeers > 0 && bytesMissing > 0 {
|
||||||
|
c.Status = "Downloading"
|
||||||
|
} else if t.Stats().ActivePeers == 0 && bytesMissing == 0 {
|
||||||
|
c.Status = "Completed"
|
||||||
|
} else if t.Stats().ActivePeers == 0 && bytesMissing > 0 {
|
||||||
|
c.Status = "Awaiting Peers"
|
||||||
|
} else {
|
||||||
|
c.Status = "Unknown"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@@ -35,6 +35,7 @@ class ClientSettingsTab extends React.PureComponent {
|
|||||||
<Paper className={classes.paper}>HTTP Port: <span className={classes.floatRight}>{this.props.settingsFile["HTTPAddr"]} </span> </Paper>
|
<Paper className={classes.paper}>HTTP Port: <span className={classes.floatRight}>{this.props.settingsFile["HTTPAddr"]} </span> </Paper>
|
||||||
<Paper className={classes.paper}>Use Proxy: <span className={classes.floatRight}>{String(this.props.settingsFile["UseProxy"])} </span> </Paper>
|
<Paper className={classes.paper}>Use Proxy: <span className={classes.floatRight}>{String(this.props.settingsFile["UseProxy"])} </span> </Paper>
|
||||||
<Paper className={classes.paper}>Base URL: <span className={classes.floatRight}>{this.props.settingsFile["BaseURL"]} </span> </Paper>
|
<Paper className={classes.paper}>Base URL: <span className={classes.floatRight}>{this.props.settingsFile["BaseURL"]} </span> </Paper>
|
||||||
|
<Paper className={classes.paper}>Max Active Torrents: <span className={classes.floatRight}>{this.props.settingsFile["MaxActiveTorrents"]} </span> </Paper>
|
||||||
|
|
||||||
|
|
||||||
</Grid>
|
</Grid>
|
||||||
|
@@ -53,7 +53,7 @@ class LoggingSettingsTab extends React.Component {
|
|||||||
<Grid container spacing={8}>
|
<Grid container spacing={8}>
|
||||||
<Grid item xs={12} sm={4}>
|
<Grid item xs={12} sm={4}>
|
||||||
<Paper className={classes.paper}>Logging Output: <span className={classes.floatRight}>{this.props.settingsFile["LoggingOutput"]} </span></Paper>
|
<Paper className={classes.paper}>Logging Output: <span className={classes.floatRight}>{this.props.settingsFile["LoggingOutput"]} </span></Paper>
|
||||||
<Paper className={classes.paper}>Logging Level: <span className={classes.floatRight}>{logLevel} </span> </Paper>
|
<Paper className={classes.paper}>Logging Level: <span className={classes.floatRight}>{this.props.settingsFile["LoggingLevel"]} </span> </Paper>
|
||||||
|
|
||||||
|
|
||||||
</Grid>
|
</Grid>
|
||||||
|
@@ -151,10 +151,9 @@ const reducer = (state = initialState, action) => {
|
|||||||
selectedRows.push(state.torrentList[element]) //pushing the selected rows out of torrentlist
|
selectedRows.push(state.torrentList[element]) //pushing the selected rows out of torrentlist
|
||||||
});
|
});
|
||||||
|
|
||||||
|
let buttonStateTest = selectedRows.filter(element => {
|
||||||
let buttonStateTest = selectedRows.filter(element => { //TODO fix this bad mess... we literally just need to filter for stopped and go from there
|
|
||||||
let result = []
|
let result = []
|
||||||
if (element.Status === "Downloading" || element.Status === "Awaiting Peers" || element.Status === "Seeding" || element.Status === "Completed"){
|
if (element.Status === "Downloading" || element.Status === "Awaiting Peers" || element.Status === "Seeding" || element.Status === "Completed" || element.Status === "Queued"){
|
||||||
result.push(element.Status)
|
result.push(element.Status)
|
||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
@@ -164,7 +163,6 @@ const reducer = (state = initialState, action) => {
|
|||||||
if (buttonStateTest.length > 0 && buttonStateTest2.length === 0){
|
if (buttonStateTest.length > 0 && buttonStateTest2.length === 0){
|
||||||
|
|
||||||
let buttonStateFinal = [{startButton: "default", stopButton: "primary", deleteButton: "secondary", fSeedButton: "default", fRecheckButton: "primary"}]
|
let buttonStateFinal = [{startButton: "default", stopButton: "primary", deleteButton: "secondary", fSeedButton: "default", fRecheckButton: "primary"}]
|
||||||
console.log("ButtonStateFil")
|
|
||||||
return {
|
return {
|
||||||
...state,
|
...state,
|
||||||
buttonState: buttonStateFinal
|
buttonState: buttonStateFinal
|
||||||
|
137
main.go
137
main.go
@@ -33,6 +33,7 @@ var (
|
|||||||
//Authenticated stores the value of the result of the client that connects to the server
|
//Authenticated stores the value of the result of the client that connects to the server
|
||||||
Authenticated = false
|
Authenticated = false
|
||||||
APP_ID = os.Getenv("APP_ID")
|
APP_ID = os.Getenv("APP_ID")
|
||||||
|
sendJSON = make(chan interface{})
|
||||||
)
|
)
|
||||||
|
|
||||||
var upgrader = websocket.Upgrader{
|
var upgrader = websocket.Upgrader{
|
||||||
@@ -48,10 +49,18 @@ func serveHome(w http.ResponseWriter, r *http.Request) {
|
|||||||
s1.ExecuteTemplate(w, "base", map[string]string{"APP_ID": APP_ID})
|
s1.ExecuteTemplate(w, "base", map[string]string{"APP_ID": APP_ID})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//HandleMessages creates a queue of JSON messages from the client and executes them in order
|
||||||
|
func handleMessages(conn *websocket.Conn) {
|
||||||
|
for {
|
||||||
|
msgJSON := <-sendJSON
|
||||||
|
conn.WriteJSON(msgJSON)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func handleAuthentication(conn *websocket.Conn, db *storm.DB) {
|
func handleAuthentication(conn *websocket.Conn, db *storm.DB) {
|
||||||
msg := Engine.Message{}
|
msg := Engine.Message{}
|
||||||
err := conn.ReadJSON(&msg)
|
err := conn.ReadJSON(&msg)
|
||||||
conn.WriteJSON(msg) //TODO just for testing, remove
|
//conn.WriteJSON(msg) //TODO just for testing, remove
|
||||||
payloadData, ok := msg.Payload.(map[string]interface{})
|
payloadData, ok := msg.Payload.(map[string]interface{})
|
||||||
clientAuthToken, tokenOk := payloadData["ClientAuthString"].(string)
|
clientAuthToken, tokenOk := payloadData["ClientAuthString"].(string)
|
||||||
fmt.Println("ClientAuthToken:", clientAuthToken, "TokenOkay", tokenOk, "PayloadData", payloadData, "PayloadData Okay?", ok)
|
fmt.Println("ClientAuthToken:", clientAuthToken, "TokenOkay", tokenOk, "PayloadData", payloadData, "PayloadData Okay?", ok)
|
||||||
@@ -65,6 +74,7 @@ func handleAuthentication(conn *websocket.Conn, db *storm.DB) {
|
|||||||
Logger.WithFields(logrus.Fields{"error": err, "SuppliedToken": clientAuthToken}).Error("Unable to read authentication message")
|
Logger.WithFields(logrus.Fields{"error": err, "SuppliedToken": clientAuthToken}).Error("Unable to read authentication message")
|
||||||
}
|
}
|
||||||
fmt.Println("Authstring", clientAuthToken)
|
fmt.Println("Authstring", clientAuthToken)
|
||||||
|
//clientAuthToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjbGllbnROYW1lIjoiZ29Ub3JyZW50V2ViVUkiLCJpc3MiOiJnb1RvcnJlbnRTZXJ2ZXIifQ.Lfqp9tm06CY4XfrqnNDeVLkq9c7rsbibDrUdPko8ffQ"
|
||||||
signingKeyStruct := Storage.FetchJWTTokens(db)
|
signingKeyStruct := Storage.FetchJWTTokens(db)
|
||||||
singingKey := signingKeyStruct.SigningKey
|
singingKey := signingKeyStruct.SigningKey
|
||||||
token, err := jwt.Parse(clientAuthToken, func(token *jwt.Token) (interface{}, error) {
|
token, err := jwt.Parse(clientAuthToken, func(token *jwt.Token) (interface{}, error) {
|
||||||
@@ -77,6 +87,7 @@ func handleAuthentication(conn *websocket.Conn, db *storm.DB) {
|
|||||||
authFail := Engine.AuthResponse{MessageType: "authResponse", Payload: "Parsing of Token failed, ensure you have the correct token! Closing Connection"}
|
authFail := Engine.AuthResponse{MessageType: "authResponse", Payload: "Parsing of Token failed, ensure you have the correct token! Closing Connection"}
|
||||||
conn.WriteJSON(authFail)
|
conn.WriteJSON(authFail)
|
||||||
Logger.WithFields(logrus.Fields{"error": err, "SuppliedToken": token}).Error("Unable to parse token!")
|
Logger.WithFields(logrus.Fields{"error": err, "SuppliedToken": token}).Error("Unable to parse token!")
|
||||||
|
fmt.Println("ENTIRE SUPPLIED TOKEN:", token, "CLIENTAUTHTOKEN", clientAuthToken)
|
||||||
conn.Close()
|
conn.Close()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -94,6 +105,7 @@ func main() {
|
|||||||
Engine.Logger = Logger //Injecting the logger into all the packages
|
Engine.Logger = Logger //Injecting the logger into all the packages
|
||||||
Storage.Logger = Logger
|
Storage.Logger = Logger
|
||||||
Settings.Logger = Logger
|
Settings.Logger = Logger
|
||||||
|
var torrentQueues = Storage.TorrentQueues{}
|
||||||
Config := Settings.FullClientSettingsNew() //grabbing from settings.go
|
Config := Settings.FullClientSettingsNew() //grabbing from settings.go
|
||||||
Engine.Config = Config
|
Engine.Config = Config
|
||||||
if Config.LoggingOutput == "file" {
|
if Config.LoggingOutput == "file" {
|
||||||
@@ -123,26 +135,33 @@ func main() {
|
|||||||
httpAddr := Config.HTTPAddr
|
httpAddr := Config.HTTPAddr
|
||||||
os.MkdirAll(Config.TFileUploadFolder, 0755) //creating a directory to store uploaded torrent files
|
os.MkdirAll(Config.TFileUploadFolder, 0755) //creating a directory to store uploaded torrent files
|
||||||
os.MkdirAll(Config.TorrentWatchFolder, 0755) //creating a directory to watch for added .torrent files
|
os.MkdirAll(Config.TorrentWatchFolder, 0755) //creating a directory to watch for added .torrent files
|
||||||
//Logger.WithFields(logrus.Fields{"Config": Config}).Info("Torrent Client Config has been generated...")
|
Logger.WithFields(logrus.Fields{"Config": Config}).Info("Torrent Client Config has been generated...")
|
||||||
|
|
||||||
tclient, err := torrent.NewClient(&Config.TorrentConfig) //pulling out the torrent specific config to use
|
tclient, err := torrent.NewClient(&Config.TorrentConfig) //pulling out the torrent specific config to use
|
||||||
if err != nil {
|
if err != nil {
|
||||||
Logger.WithFields(logrus.Fields{"error": err}).Fatalf("Error creating torrent client: %s")
|
Logger.WithFields(logrus.Fields{"error": err}).Fatalf("Error creating torrent client: %s")
|
||||||
}
|
}
|
||||||
fmt.Printf("%+v\n", Config.TorrentConfig)
|
//fmt.Printf("%+v\n", Config.TorrentConfig)
|
||||||
db, err := storm.Open("storage.db") //initializing the boltDB store that contains all the added torrents
|
db, err := storm.Open("storage.db") //initializing the boltDB store that contains all the added torrents
|
||||||
if err != nil {
|
if err != nil {
|
||||||
Logger.WithFields(logrus.Fields{"error": err}).Fatal("Error opening/creating storage.db")
|
Logger.WithFields(logrus.Fields{"error": err}).Fatal("Error opening/creating storage.db")
|
||||||
|
} else {
|
||||||
|
Logger.WithFields(logrus.Fields{"error": err}).Info("Opening or creating storage.db...")
|
||||||
}
|
}
|
||||||
defer db.Close() //defering closing the database until the program closes
|
defer db.Close() //defering closing the database until the program closes
|
||||||
|
|
||||||
|
err = db.One("ID", 5, &torrentQueues)
|
||||||
|
if err != nil { //Create the torrent que database
|
||||||
|
Logger.WithFields(logrus.Fields{"error": err}).Info("No Queue database found, assuming first run, creating database")
|
||||||
|
torrentQueues.ID = 5
|
||||||
|
db.Save(&torrentQueues)
|
||||||
|
}
|
||||||
|
|
||||||
tokens := Storage.IssuedTokensList{} //if first run setting up the authentication tokens
|
tokens := Storage.IssuedTokensList{} //if first run setting up the authentication tokens
|
||||||
var signingKey []byte
|
var signingKey []byte
|
||||||
err = db.One("ID", 3, &tokens)
|
err = db.One("ID", 3, &tokens)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
Logger.WithFields(logrus.Fields{"RSSFeedStore": tokens, "error": err}).Info("No Tokens database found, assuming first run, generating token...")
|
Logger.WithFields(logrus.Fields{"RSSFeedStore": tokens, "error": err}).Info("No Tokens database found, assuming first run, generating token...")
|
||||||
fmt.Println("Error", err)
|
|
||||||
fmt.Println("MAIN TOKEN: %+v\n", tokens)
|
|
||||||
tokens.ID = 3 //creating the initial store
|
tokens.ID = 3 //creating the initial store
|
||||||
claims := Settings.GoTorrentClaims{
|
claims := Settings.GoTorrentClaims{
|
||||||
"goTorrentWebUI",
|
"goTorrentWebUI",
|
||||||
@@ -189,12 +208,14 @@ func main() {
|
|||||||
TorrentLocalArray := Storage.FetchAllStoredTorrents(db) //pulling in all the already added torrents - this is an array of ALL of the local storage torrents, they will be added back in via hash
|
TorrentLocalArray := Storage.FetchAllStoredTorrents(db) //pulling in all the already added torrents - this is an array of ALL of the local storage torrents, they will be added back in via hash
|
||||||
|
|
||||||
if TorrentLocalArray != nil { //the first creation of the running torrent array //since we are adding all of them in we use a coroutine... just allows the web ui to load then it will load in the torrents
|
if TorrentLocalArray != nil { //the first creation of the running torrent array //since we are adding all of them in we use a coroutine... just allows the web ui to load then it will load in the torrents
|
||||||
go Engine.CreateInitialTorrentArray(tclient, TorrentLocalArray, db) //adding all of the stored torrents into the torrent client
|
Engine.CreateInitialTorrentArray(tclient, TorrentLocalArray, db, Config) //adding all of the stored torrents into the torrent client
|
||||||
|
//TODO add GO to this
|
||||||
} else {
|
} else {
|
||||||
Logger.Info("Database is empty, no torrents loaded")
|
Logger.Info("Database is empty, no torrents loaded")
|
||||||
}
|
}
|
||||||
Engine.CheckTorrentWatchFolder(cronEngine, db, tclient, torrentLocalStorage, Config) //Every 5 minutes the engine will check the specified folder for new .torrent files
|
Engine.CheckTorrentWatchFolder(cronEngine, db, tclient, torrentLocalStorage, Config, torrentQueues) //Every 5 minutes the engine will check the specified folder for new .torrent files
|
||||||
Engine.RefreshRSSCron(cronEngine, db, tclient, torrentLocalStorage, Config) // Refresing the RSS feeds on an hourly basis to add torrents that show up in the RSS feed
|
Engine.RefreshRSSCron(cronEngine, db, tclient, torrentLocalStorage, Config, torrentQueues) // Refresing the RSS feeds on an hourly basis to add torrents that show up in the RSS feed
|
||||||
|
Engine.CheckTorrentsCron(cronEngine, db, tclient, Config)
|
||||||
|
|
||||||
router := mux.NewRouter() //setting up the handler for the web backend
|
router := mux.NewRouter() //setting up the handler for the web backend
|
||||||
router.HandleFunc("/", serveHome) //Serving the main page for our SPA
|
router.HandleFunc("/", serveHome) //Serving the main page for our SPA
|
||||||
@@ -232,6 +253,8 @@ func main() {
|
|||||||
Engine.Conn = conn
|
Engine.Conn = conn
|
||||||
Storage.Conn = conn
|
Storage.Conn = conn
|
||||||
|
|
||||||
|
go handleMessages(conn) //Starting the message channel to handle all the JSON requests from the client
|
||||||
|
|
||||||
MessageLoop: //Tagging this so we can continue out of it with any errors we encounter that are failing
|
MessageLoop: //Tagging this so we can continue out of it with any errors we encounter that are failing
|
||||||
for {
|
for {
|
||||||
runningTorrents := tclient.Torrents() //getting running torrents here since multiple cases ask for the running torrents
|
runningTorrents := tclient.Torrents() //getting running torrents here since multiple cases ask for the running torrents
|
||||||
@@ -269,31 +292,30 @@ func main() {
|
|||||||
tokensDB := Storage.FetchJWTTokens(db)
|
tokensDB := Storage.FetchJWTTokens(db)
|
||||||
tokensDB.TokenNames = append(tokens.TokenNames, Storage.SingleToken{payloadData["ClientName"].(string)})
|
tokensDB.TokenNames = append(tokens.TokenNames, Storage.SingleToken{payloadData["ClientName"].(string)})
|
||||||
db.Update(&tokensDB) //adding the new token client name to the database
|
db.Update(&tokensDB) //adding the new token client name to the database
|
||||||
conn.WriteJSON(tokenReturn)
|
sendJSON <- tokenReturn
|
||||||
|
|
||||||
case "torrentListRequest":
|
case "torrentListRequest": //This will run automatically if a webUI is open
|
||||||
Logger.WithFields(logrus.Fields{"message": msg}).Debug("Client Requested TorrentList Update")
|
Logger.WithFields(logrus.Fields{"message": msg}).Debug("Client Requested TorrentList Update")
|
||||||
|
|
||||||
go func() { //running updates in separate thread so can still accept commands
|
go func() { //running updates in separate thread so can still accept commands
|
||||||
TorrentLocalArray = Storage.FetchAllStoredTorrents(db) //Required to re-read th database since we write to the DB and this will pull the changes from it
|
TorrentLocalArray = Storage.FetchAllStoredTorrents(db) //Required to re-read the database since we write to the DB and this will pull the changes from it
|
||||||
RunningTorrentArray = Engine.CreateRunningTorrentArray(tclient, TorrentLocalArray, PreviousTorrentArray, Config, db) //Updates the RunningTorrentArray with the current client data as well
|
RunningTorrentArray = Engine.CreateRunningTorrentArray(tclient, TorrentLocalArray, PreviousTorrentArray, Config, db) //Updates the RunningTorrentArray with the current client data as well
|
||||||
PreviousTorrentArray = RunningTorrentArray
|
PreviousTorrentArray = RunningTorrentArray
|
||||||
torrentlistArray := Engine.TorrentList{MessageType: "torrentList", ClientDBstruct: RunningTorrentArray, Totaltorrents: len(RunningTorrentArray)}
|
torrentlistArray := Engine.TorrentList{MessageType: "torrentList", ClientDBstruct: RunningTorrentArray, Totaltorrents: len(RunningTorrentArray)}
|
||||||
Logger.WithFields(logrus.Fields{"torrentList": torrentlistArray, "previousTorrentList": PreviousTorrentArray}).Debug("Previous and Current Torrent Lists for sending to client")
|
Logger.WithFields(logrus.Fields{"torrentList": torrentlistArray, "previousTorrentList": PreviousTorrentArray}).Debug("Previous and Current Torrent Lists for sending to client")
|
||||||
conn.WriteJSON(torrentlistArray)
|
sendJSON <- torrentlistArray
|
||||||
}()
|
}()
|
||||||
|
|
||||||
case "torrentFileListRequest": //client requested a filelist update
|
case "torrentFileListRequest": //client requested a filelist update
|
||||||
Logger.WithFields(logrus.Fields{"message": msg}).Info("Client Requested FileList Update")
|
Logger.WithFields(logrus.Fields{"message": msg}).Info("Client Requested FileList Update")
|
||||||
fileListArrayRequest := payloadData["FileListHash"].(string)
|
fileListArrayRequest := payloadData["FileListHash"].(string)
|
||||||
FileListArray := Engine.CreateFileListArray(tclient, fileListArrayRequest, db, Config)
|
FileListArray := Engine.CreateFileListArray(tclient, fileListArrayRequest, db, Config)
|
||||||
conn.WriteJSON(FileListArray) //writing the JSON to the client
|
sendJSON <- FileListArray
|
||||||
|
|
||||||
case "torrentPeerListRequest":
|
case "torrentPeerListRequest":
|
||||||
Logger.WithFields(logrus.Fields{"message": msg}).Info("Client Requested PeerList Update")
|
Logger.WithFields(logrus.Fields{"message": msg}).Info("Client Requested PeerList Update")
|
||||||
peerListArrayRequest := payloadData["PeerListHash"].(string)
|
peerListArrayRequest := payloadData["PeerListHash"].(string)
|
||||||
torrentPeerList := Engine.CreatePeerListArray(tclient, peerListArrayRequest)
|
torrentPeerList := Engine.CreatePeerListArray(tclient, peerListArrayRequest)
|
||||||
conn.WriteJSON(torrentPeerList)
|
sendJSON <- torrentPeerList
|
||||||
|
|
||||||
case "fetchTorrentsByLabel":
|
case "fetchTorrentsByLabel":
|
||||||
Logger.WithFields(logrus.Fields{"message": msg}).Info("Client Requested Torrents by Label")
|
Logger.WithFields(logrus.Fields{"message": msg}).Info("Client Requested Torrents by Label")
|
||||||
@@ -308,7 +330,7 @@ func main() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
conn.WriteJSON(labelRunningArray)
|
sendJSON <- labelRunningArray
|
||||||
|
|
||||||
case "changeStorageValue":
|
case "changeStorageValue":
|
||||||
Logger.WithFields(logrus.Fields{"message": msg}).Info("Client Requested Storage Location Update")
|
Logger.WithFields(logrus.Fields{"message": msg}).Info("Client Requested Storage Location Update")
|
||||||
@@ -334,7 +356,7 @@ func main() {
|
|||||||
case "settingsFileRequest":
|
case "settingsFileRequest":
|
||||||
Logger.WithFields(logrus.Fields{"message": msg}).Info("Client Requested Settings File")
|
Logger.WithFields(logrus.Fields{"message": msg}).Info("Client Requested Settings File")
|
||||||
clientSettingsFile := Engine.SettingsFile{MessageType: "settingsFile", Config: Config}
|
clientSettingsFile := Engine.SettingsFile{MessageType: "settingsFile", Config: Config}
|
||||||
conn.WriteJSON(clientSettingsFile)
|
sendJSON <- clientSettingsFile
|
||||||
|
|
||||||
case "rssFeedRequest":
|
case "rssFeedRequest":
|
||||||
Logger.WithFields(logrus.Fields{"message": msg}).Info("Client Requested RSS Update")
|
Logger.WithFields(logrus.Fields{"message": msg}).Info("Client Requested RSS Update")
|
||||||
@@ -346,7 +368,7 @@ func main() {
|
|||||||
RSSsingleFeed.RSSFeedURL = singleFeed.URL
|
RSSsingleFeed.RSSFeedURL = singleFeed.URL
|
||||||
RSSJSONFeed.RSSFeeds = append(RSSJSONFeed.RSSFeeds, RSSsingleFeed)
|
RSSJSONFeed.RSSFeeds = append(RSSJSONFeed.RSSFeeds, RSSsingleFeed)
|
||||||
}
|
}
|
||||||
conn.WriteJSON(RSSJSONFeed)
|
sendJSON <- RSSJSONFeed
|
||||||
|
|
||||||
case "addRSSFeed":
|
case "addRSSFeed":
|
||||||
newRSSFeed := payloadData["RSSURL"].(string)
|
newRSSFeed := payloadData["RSSURL"].(string)
|
||||||
@@ -391,7 +413,7 @@ func main() {
|
|||||||
UpdatedRSSFeed := Engine.RefreshSingleRSSFeed(db, Storage.FetchSpecificRSSFeed(db, RSSFeedURL))
|
UpdatedRSSFeed := Engine.RefreshSingleRSSFeed(db, Storage.FetchSpecificRSSFeed(db, RSSFeedURL))
|
||||||
TorrentRSSList := Engine.SingleRSSFeedMessage{MessageType: "rssTorrentList", URL: RSSFeedURL, Name: UpdatedRSSFeed.Name, TotalTorrents: len(UpdatedRSSFeed.Torrents), Torrents: UpdatedRSSFeed.Torrents}
|
TorrentRSSList := Engine.SingleRSSFeedMessage{MessageType: "rssTorrentList", URL: RSSFeedURL, Name: UpdatedRSSFeed.Name, TotalTorrents: len(UpdatedRSSFeed.Torrents), Torrents: UpdatedRSSFeed.Torrents}
|
||||||
Logger.WithFields(logrus.Fields{"TorrentRSSList": TorrentRSSList}).Info("Returning Torrent list from RSSFeed to client")
|
Logger.WithFields(logrus.Fields{"TorrentRSSList": TorrentRSSList}).Info("Returning Torrent list from RSSFeed to client")
|
||||||
conn.WriteJSON(TorrentRSSList)
|
sendJSON <- TorrentRSSList
|
||||||
|
|
||||||
case "magnetLinkSubmit": //if we detect a magnet link we will be adding a magnet torrent
|
case "magnetLinkSubmit": //if we detect a magnet link we will be adding a magnet torrent
|
||||||
storageValue, ok := payloadData["StorageValue"].(string)
|
storageValue, ok := payloadData["StorageValue"].(string)
|
||||||
@@ -422,8 +444,18 @@ func main() {
|
|||||||
}
|
}
|
||||||
Logger.WithFields(logrus.Fields{"clientTorrent": clientTorrent, "magnetLink": magnetLink}).Info("Adding torrent to client!")
|
Logger.WithFields(logrus.Fields{"clientTorrent": clientTorrent, "magnetLink": magnetLink}).Info("Adding torrent to client!")
|
||||||
Engine.CreateServerPushMessage(Engine.ServerPushMessage{MessageType: "serverPushMessage", MessageLevel: "info", Payload: "Received MagnetLink"}, conn)
|
Engine.CreateServerPushMessage(Engine.ServerPushMessage{MessageType: "serverPushMessage", MessageLevel: "info", Payload: "Received MagnetLink"}, conn)
|
||||||
go Engine.StartTorrent(clientTorrent, torrentLocalStorage, db, "magnet", "", storageValue, labelValue, Config) //starting the torrent and creating local DB entry
|
if len(torrentQueues.ActiveTorrents) > Config.MaxActiveTorrents {
|
||||||
|
Logger.WithFields(logrus.Fields{"Name: ": clientTorrent.Name()}).Info("Adding New torrent to active, pushing other torrent to queue")
|
||||||
|
removeTorrent := torrentQueues.ActiveTorrents[:1]
|
||||||
|
for _, singleTorrent := range runningTorrents {
|
||||||
|
if singleTorrent.InfoHash().String() == removeTorrent[0] {
|
||||||
|
oldTorrentInfo := Storage.FetchTorrentFromStorage(db, singleTorrent.InfoHash().String())
|
||||||
|
Engine.RemoveTorrentFromActive(&oldTorrentInfo, singleTorrent, db)
|
||||||
|
Storage.UpdateStorageTick(db, oldTorrentInfo)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
go Engine.AddTorrent(clientTorrent, torrentLocalStorage, db, "magnet", "", storageValue, labelValue, Config) //starting the torrent and creating local DB entry
|
||||||
}
|
}
|
||||||
|
|
||||||
case "torrentFileSubmit":
|
case "torrentFileSubmit":
|
||||||
@@ -469,7 +501,18 @@ func main() {
|
|||||||
Engine.CreateServerPushMessage(Engine.ServerPushMessage{MessageType: "serverPushMessage", MessageLevel: "error", Payload: "Unable to add Torrent to torrent server"}, conn)
|
Engine.CreateServerPushMessage(Engine.ServerPushMessage{MessageType: "serverPushMessage", MessageLevel: "error", Payload: "Unable to add Torrent to torrent server"}, conn)
|
||||||
}
|
}
|
||||||
Logger.WithFields(logrus.Fields{"clienttorrent": clientTorrent.Name(), "filename": filePathAbs}).Info("Added torrent")
|
Logger.WithFields(logrus.Fields{"clienttorrent": clientTorrent.Name(), "filename": filePathAbs}).Info("Added torrent")
|
||||||
go Engine.StartTorrent(clientTorrent, torrentLocalStorage, db, "file", filePathAbs, storageValue, labelValue, Config)
|
if len(torrentQueues.ActiveTorrents) >= Config.MaxActiveTorrents {
|
||||||
|
Logger.WithFields(logrus.Fields{"Name: ": clientTorrent.Name()}).Info("Adding New torrent to active, pushing other torrent to queue")
|
||||||
|
removeTorrent := torrentQueues.ActiveTorrents[:1]
|
||||||
|
for _, singleTorrent := range runningTorrents {
|
||||||
|
if singleTorrent.InfoHash().String() == removeTorrent[0] {
|
||||||
|
oldTorrentInfo := Storage.FetchTorrentFromStorage(db, singleTorrent.InfoHash().String())
|
||||||
|
Engine.RemoveTorrentFromActive(&oldTorrentInfo, singleTorrent, db)
|
||||||
|
Storage.UpdateStorageTick(db, oldTorrentInfo)
|
||||||
|
go Engine.AddTorrent(clientTorrent, torrentLocalStorage, db, "file", filePathAbs, storageValue, labelValue, Config)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
case "stopTorrents":
|
case "stopTorrents":
|
||||||
torrentHashes := payloadData["TorrentHashes"].([]interface{})
|
torrentHashes := payloadData["TorrentHashes"].([]interface{})
|
||||||
@@ -479,9 +522,7 @@ func main() {
|
|||||||
if singleTorrent.InfoHash().String() == singleSelection {
|
if singleTorrent.InfoHash().String() == singleSelection {
|
||||||
Logger.WithFields(logrus.Fields{"selection": singleSelection}).Info("Matched for stopping torrents")
|
Logger.WithFields(logrus.Fields{"selection": singleSelection}).Info("Matched for stopping torrents")
|
||||||
oldTorrentInfo := Storage.FetchTorrentFromStorage(db, singleTorrent.InfoHash().String())
|
oldTorrentInfo := Storage.FetchTorrentFromStorage(db, singleTorrent.InfoHash().String())
|
||||||
oldTorrentInfo.TorrentStatus = "Stopped"
|
Engine.StopTorrent(singleTorrent, &oldTorrentInfo, db)
|
||||||
oldTorrentInfo.MaxConnections = 0
|
|
||||||
Storage.UpdateStorageTick(db, oldTorrentInfo) //Updating the torrent status
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -495,6 +536,8 @@ func main() {
|
|||||||
for _, singleSelection := range torrentHashes {
|
for _, singleSelection := range torrentHashes {
|
||||||
if singleTorrent.InfoHash().String() == singleSelection {
|
if singleTorrent.InfoHash().String() == singleSelection {
|
||||||
oldTorrentInfo := Storage.FetchTorrentFromStorage(db, singleTorrent.InfoHash().String())
|
oldTorrentInfo := Storage.FetchTorrentFromStorage(db, singleTorrent.InfoHash().String())
|
||||||
|
torrentQueues = Storage.FetchQueues(db)
|
||||||
|
|
||||||
Logger.WithFields(logrus.Fields{"selection": singleSelection}).Info("Matched for deleting torrents")
|
Logger.WithFields(logrus.Fields{"selection": singleSelection}).Info("Matched for deleting torrents")
|
||||||
if withData {
|
if withData {
|
||||||
oldTorrentInfo.TorrentStatus = "DroppedData" //Will be cleaned up the next engine loop since deleting a torrent mid loop can cause issues
|
oldTorrentInfo.TorrentStatus = "DroppedData" //Will be cleaned up the next engine loop since deleting a torrent mid loop can cause issues
|
||||||
@@ -502,6 +545,7 @@ func main() {
|
|||||||
oldTorrentInfo.TorrentStatus = "Dropped"
|
oldTorrentInfo.TorrentStatus = "Dropped"
|
||||||
}
|
}
|
||||||
Storage.UpdateStorageTick(db, oldTorrentInfo)
|
Storage.UpdateStorageTick(db, oldTorrentInfo)
|
||||||
|
Storage.UpdateQueues(db, torrentQueues)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -515,34 +559,29 @@ func main() {
|
|||||||
if singleTorrent.InfoHash().String() == singleSelection {
|
if singleTorrent.InfoHash().String() == singleSelection {
|
||||||
Logger.WithFields(logrus.Fields{"infoHash": singleTorrent.InfoHash().String()}).Info("Found matching torrent to start")
|
Logger.WithFields(logrus.Fields{"infoHash": singleTorrent.InfoHash().String()}).Info("Found matching torrent to start")
|
||||||
oldTorrentInfo := Storage.FetchTorrentFromStorage(db, singleTorrent.InfoHash().String())
|
oldTorrentInfo := Storage.FetchTorrentFromStorage(db, singleTorrent.InfoHash().String())
|
||||||
oldTorrentInfo.TorrentStatus = "Running"
|
Logger.WithFields(logrus.Fields{"Torrent": oldTorrentInfo.TorrentName}).Info("Changing database to torrent running with 80 max connections")
|
||||||
|
oldTorrentInfo.TorrentStatus = "ForceStart"
|
||||||
oldTorrentInfo.MaxConnections = 80
|
oldTorrentInfo.MaxConnections = 80
|
||||||
singleTorrent.DownloadAll() //set all of the pieces to download (piece prio is NE to file prio)
|
Storage.UpdateStorageTick(db, oldTorrentInfo) //Updating the torrent status
|
||||||
NumPieces := singleTorrent.NumPieces() //find the number of pieces
|
Engine.AddTorrentToForceStart(&oldTorrentInfo, singleTorrent, db)
|
||||||
singleTorrent.CancelPieces(1, NumPieces) //cancel all of the pieces to use file priority
|
|
||||||
for _, file := range singleTorrent.Files() {
|
}
|
||||||
for _, sentFile := range oldTorrentInfo.TorrentFilePriority {
|
torrentQueues = Storage.FetchQueues(db)
|
||||||
if file.DisplayPath() == sentFile.TorrentFilePath {
|
if len(torrentQueues.ActiveTorrents) > Config.MaxActiveTorrents { //Since we are starting a new torrent stop the last torrent in the que if running is full
|
||||||
switch sentFile.TorrentFilePriority {
|
//removeTorrent := torrentQueues.ActiveTorrents[len(torrentQueues.ActiveTorrents)-1]
|
||||||
case "High":
|
removeTorrent := torrentQueues.ActiveTorrents[len(torrentQueues.ActiveTorrents)-1]
|
||||||
file.SetPriority(torrent.PiecePriorityHigh)
|
for _, singleTorrent := range runningTorrents {
|
||||||
case "Normal":
|
if singleTorrent.InfoHash().String() == removeTorrent {
|
||||||
file.SetPriority(torrent.PiecePriorityNormal)
|
oldTorrentInfo := Storage.FetchTorrentFromStorage(db, singleTorrent.InfoHash().String())
|
||||||
case "Cancel":
|
Engine.RemoveTorrentFromActive(&oldTorrentInfo, singleTorrent, db)
|
||||||
file.SetPriority(torrent.PiecePriorityNone)
|
Storage.UpdateStorageTick(db, oldTorrentInfo)
|
||||||
default:
|
|
||||||
file.SetPriority(torrent.PiecePriorityNormal)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Logger.WithFields(logrus.Fields{"Torrent": oldTorrentInfo.TorrentName}).Info("Changing database to torrent running with 80 max connections")
|
|
||||||
Storage.UpdateStorageTick(db, oldTorrentInfo) //Updating the torrent status
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
case "forceUploadTorrents":
|
case "forceUploadTorrents": //TODO allow force to override total limit of queued torrents?
|
||||||
torrentHashes := payloadData["TorrentHashes"].([]interface{})
|
torrentHashes := payloadData["TorrentHashes"].([]interface{})
|
||||||
Logger.WithFields(logrus.Fields{"selection": msg.Payload}).Info("Matched for force Uploading Torrents")
|
Logger.WithFields(logrus.Fields{"selection": msg.Payload}).Info("Matched for force Uploading Torrents")
|
||||||
Engine.CreateServerPushMessage(Engine.ServerPushMessage{MessageType: "serverPushMessage", MessageLevel: "info", Payload: "Received Force Start Request"}, conn)
|
Engine.CreateServerPushMessage(Engine.ServerPushMessage{MessageType: "serverPushMessage", MessageLevel: "info", Payload: "Received Force Start Request"}, conn)
|
||||||
@@ -554,7 +593,6 @@ func main() {
|
|||||||
oldTorrentInfo.TorrentUploadLimit = false // no upload limit for this torrent
|
oldTorrentInfo.TorrentUploadLimit = false // no upload limit for this torrent
|
||||||
oldTorrentInfo.TorrentStatus = "Running"
|
oldTorrentInfo.TorrentStatus = "Running"
|
||||||
oldTorrentInfo.MaxConnections = 80
|
oldTorrentInfo.MaxConnections = 80
|
||||||
fmt.Println("OldtorrentinfoName", oldTorrentInfo.TorrentName)
|
|
||||||
Logger.WithFields(logrus.Fields{"NewMax": oldTorrentInfo.MaxConnections, "Torrent": oldTorrentInfo.TorrentName}).Info("Setting max connection from zero to 80")
|
Logger.WithFields(logrus.Fields{"NewMax": oldTorrentInfo.MaxConnections, "Torrent": oldTorrentInfo.TorrentName}).Info("Setting max connection from zero to 80")
|
||||||
Storage.UpdateStorageTick(db, oldTorrentInfo) //Updating the torrent status
|
Storage.UpdateStorageTick(db, oldTorrentInfo) //Updating the torrent status
|
||||||
}
|
}
|
||||||
@@ -604,14 +642,13 @@ func main() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
default:
|
default:
|
||||||
//conn.Close()
|
|
||||||
Logger.WithFields(logrus.Fields{"message": msg}).Info("Unrecognized Message from client... ignoring")
|
Logger.WithFields(logrus.Fields{"message": msg}).Info("Unrecognized Message from client... ignoring")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
})
|
})
|
||||||
if Config.UseProxy {
|
if Config.UseReverseProxy {
|
||||||
err := http.ListenAndServe(httpAddr, handlers.ProxyHeaders(router))
|
err := http.ListenAndServe(httpAddr, handlers.ProxyHeaders(router))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
Logger.WithFields(logrus.Fields{"error": err}).Fatal("Unable to listen on the http Server!")
|
Logger.WithFields(logrus.Fields{"error": err}).Fatal("Unable to listen on the http Server!")
|
||||||
@@ -619,7 +656,7 @@ func main() {
|
|||||||
} else {
|
} else {
|
||||||
err := http.ListenAndServe(httpAddr, nil) //Can't send proxy headers if not used since that can be a security issue
|
err := http.ListenAndServe(httpAddr, nil) //Can't send proxy headers if not used since that can be a security issue
|
||||||
if err != nil {
|
if err != nil {
|
||||||
Logger.WithFields(logrus.Fields{"error": err}).Fatal("Unable to listen on the http Server with no proxy headers!")
|
Logger.WithFields(logrus.Fields{"error": err}).Fatal("Unable to listen on the http Server! (Maybe wrong IP in config, port already in use?) (Config: Not using proxy, see error for more details)")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -80052,9 +80052,8 @@ var reducer = function reducer() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
var buttonStateTest = selectedRows.filter(function (element) {
|
var buttonStateTest = selectedRows.filter(function (element) {
|
||||||
//TODO fix this bad mess... we literally just need to filter for stopped and go from there
|
|
||||||
var result = [];
|
var result = [];
|
||||||
if (element.Status === "Downloading" || element.Status === "Awaiting Peers" || element.Status === "Seeding" || element.Status === "Completed") {
|
if (element.Status === "Downloading" || element.Status === "Awaiting Peers" || element.Status === "Seeding" || element.Status === "Completed" || element.Status === "Queued") {
|
||||||
result.push(element.Status);
|
result.push(element.Status);
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
@@ -80066,7 +80065,6 @@ var reducer = function reducer() {
|
|||||||
if (buttonStateTest.length > 0 && buttonStateTest2.length === 0) {
|
if (buttonStateTest.length > 0 && buttonStateTest2.length === 0) {
|
||||||
|
|
||||||
var _buttonStateFinal2 = [{ startButton: "default", stopButton: "primary", deleteButton: "secondary", fSeedButton: "default", fRecheckButton: "primary" }];
|
var _buttonStateFinal2 = [{ startButton: "default", stopButton: "primary", deleteButton: "secondary", fSeedButton: "default", fRecheckButton: "primary" }];
|
||||||
console.log("ButtonStateFil");
|
|
||||||
return _extends({}, state, {
|
return _extends({}, state, {
|
||||||
buttonState: _buttonStateFinal2
|
buttonState: _buttonStateFinal2
|
||||||
});
|
});
|
||||||
@@ -109786,6 +109784,18 @@ var ClientSettingsTab = function (_React$PureComponent) {
|
|||||||
' '
|
' '
|
||||||
),
|
),
|
||||||
' '
|
' '
|
||||||
|
),
|
||||||
|
_react2.default.createElement(
|
||||||
|
_Paper2.default,
|
||||||
|
{ className: classes.paper },
|
||||||
|
'Max Active Torrents: ',
|
||||||
|
_react2.default.createElement(
|
||||||
|
'span',
|
||||||
|
{ className: classes.floatRight },
|
||||||
|
this.props.settingsFile["MaxActiveTorrents"],
|
||||||
|
' '
|
||||||
|
),
|
||||||
|
' '
|
||||||
)
|
)
|
||||||
),
|
),
|
||||||
_react2.default.createElement(
|
_react2.default.createElement(
|
||||||
@@ -109957,7 +109967,7 @@ var LoggingSettingsTab = function (_React$Component) {
|
|||||||
_react2.default.createElement(
|
_react2.default.createElement(
|
||||||
'span',
|
'span',
|
||||||
{ className: classes.floatRight },
|
{ className: classes.floatRight },
|
||||||
logLevel,
|
this.props.settingsFile["LoggingLevel"],
|
||||||
' '
|
' '
|
||||||
),
|
),
|
||||||
' '
|
' '
|
||||||
|
@@ -42,7 +42,7 @@ func GenerateClientConfigFile(config FullClientSettings, authString string) {
|
|||||||
`
|
`
|
||||||
}
|
}
|
||||||
|
|
||||||
if config.UseProxy {
|
if config.UseReverseProxy {
|
||||||
clientFile = `
|
clientFile = `
|
||||||
ClientAuthString = "` + authString + `"
|
ClientAuthString = "` + authString + `"
|
||||||
` + webUIAuth + `
|
` + webUIAuth + `
|
||||||
|
@@ -4,6 +4,7 @@ import (
|
|||||||
"crypto/sha256"
|
"crypto/sha256"
|
||||||
"fmt"
|
"fmt"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"golang.org/x/time/rate"
|
"golang.org/x/time/rate"
|
||||||
@@ -20,9 +21,11 @@ var Logger *logrus.Logger
|
|||||||
type ClientConnectSettings struct {
|
type ClientConnectSettings struct {
|
||||||
HTTPAddr string
|
HTTPAddr string
|
||||||
HTTPAddrIP string
|
HTTPAddrIP string
|
||||||
UseProxy bool
|
UseReverseProxy bool
|
||||||
|
UseSocksProxy bool
|
||||||
WebsocketClientPort string
|
WebsocketClientPort string
|
||||||
BaseURL string
|
BaseURL string
|
||||||
|
SocksProxyURL string
|
||||||
ClientUsername string
|
ClientUsername string
|
||||||
ClientPassword string
|
ClientPassword string
|
||||||
PushBulletToken string `json:"-"`
|
PushBulletToken string `json:"-"`
|
||||||
@@ -34,12 +37,13 @@ type FullClientSettings struct {
|
|||||||
LoggingLevel logrus.Level
|
LoggingLevel logrus.Level
|
||||||
LoggingOutput string
|
LoggingOutput string
|
||||||
Version int
|
Version int
|
||||||
TorrentConfig torrent.Config `json:"-"`
|
TorrentConfig torrent.ClientConfig `json:"-"`
|
||||||
TFileUploadFolder string
|
TFileUploadFolder string
|
||||||
SeedRatioStop float64
|
SeedRatioStop float64
|
||||||
DefaultMoveFolder string
|
DefaultMoveFolder string
|
||||||
TorrentWatchFolder string
|
TorrentWatchFolder string
|
||||||
ClientConnectSettings
|
ClientConnectSettings
|
||||||
|
MaxActiveTorrents int
|
||||||
}
|
}
|
||||||
|
|
||||||
//default is called if there is a parsing error
|
//default is called if there is a parsing error
|
||||||
@@ -54,9 +58,9 @@ func defaultConfig() FullClientSettings {
|
|||||||
Config.HTTPAddr = ":8000"
|
Config.HTTPAddr = ":8000"
|
||||||
Config.SeedRatioStop = 1.50
|
Config.SeedRatioStop = 1.50
|
||||||
|
|
||||||
Config.TorrentConfig.DHTConfig = dht.ServerConfig{
|
//Config.TorrentConfig.DhtStartingNodes = dht.StartingNodesGetter{
|
||||||
StartingNodes: dht.GlobalBootstrapAddrs,
|
// StartingNodes: dht.GlobalBootstrapAddrs,
|
||||||
}
|
//}
|
||||||
|
|
||||||
return Config
|
return Config
|
||||||
}
|
}
|
||||||
@@ -70,6 +74,8 @@ func dhtServerSettings(dhtConfig dht.ServerConfig) dht.ServerConfig {
|
|||||||
func calculateRateLimiters(uploadRate, downloadRate string) (*rate.Limiter, *rate.Limiter) { //TODO reorg
|
func calculateRateLimiters(uploadRate, downloadRate string) (*rate.Limiter, *rate.Limiter) { //TODO reorg
|
||||||
var uploadRateLimiterSize int
|
var uploadRateLimiterSize int
|
||||||
var downloadRateLimiterSize int
|
var downloadRateLimiterSize int
|
||||||
|
var downloadRateLimiter *rate.Limiter
|
||||||
|
var uploadRateLimiter *rate.Limiter
|
||||||
|
|
||||||
switch uploadRate {
|
switch uploadRate {
|
||||||
case "Low":
|
case "Low":
|
||||||
@@ -79,8 +85,8 @@ func calculateRateLimiters(uploadRate, downloadRate string) (*rate.Limiter, *rat
|
|||||||
case "High":
|
case "High":
|
||||||
uploadRateLimiterSize = 1500000
|
uploadRateLimiterSize = 1500000
|
||||||
default:
|
default:
|
||||||
downloadRateLimiter := rate.NewLimiter(rate.Inf, 0)
|
downloadRateLimiter = rate.NewLimiter(rate.Inf, 0)
|
||||||
uploadRateLimiter := rate.NewLimiter(rate.Inf, 0)
|
uploadRateLimiter = rate.NewLimiter(rate.Inf, 0)
|
||||||
return downloadRateLimiter, uploadRateLimiter
|
return downloadRateLimiter, uploadRateLimiter
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -89,17 +95,16 @@ func calculateRateLimiters(uploadRate, downloadRate string) (*rate.Limiter, *rat
|
|||||||
downloadRateLimiterSize = 50000
|
downloadRateLimiterSize = 50000
|
||||||
case "Medium":
|
case "Medium":
|
||||||
downloadRateLimiterSize = 500000
|
downloadRateLimiterSize = 500000
|
||||||
|
fmt.Println("Medium Rate Limit...")
|
||||||
case "High":
|
case "High":
|
||||||
downloadRateLimiterSize = 1500000
|
downloadRateLimiterSize = 1500000
|
||||||
default:
|
default:
|
||||||
downloadRateLimiter := rate.NewLimiter(rate.Inf, 0)
|
downloadRateLimiter = rate.NewLimiter(rate.Inf, 0)
|
||||||
uploadRateLimiter := rate.NewLimiter(rate.Inf, 0)
|
uploadRateLimiter = rate.NewLimiter(rate.Inf, 0)
|
||||||
return downloadRateLimiter, uploadRateLimiter
|
return downloadRateLimiter, uploadRateLimiter
|
||||||
}
|
}
|
||||||
var limitPerSecondUl = rate.Limit(uploadRateLimiterSize)
|
uploadRateLimiter = rate.NewLimiter(rate.Limit(uploadRateLimiterSize), uploadRateLimiterSize)
|
||||||
uploadRateLimiter := rate.NewLimiter(limitPerSecondUl, uploadRateLimiterSize)
|
downloadRateLimiter = rate.NewLimiter(rate.Limit(downloadRateLimiterSize), downloadRateLimiterSize)
|
||||||
var limitPerSecondDl = rate.Limit(uploadRateLimiterSize)
|
|
||||||
downloadRateLimiter := rate.NewLimiter(limitPerSecondDl, downloadRateLimiterSize)
|
|
||||||
return downloadRateLimiter, uploadRateLimiter
|
return downloadRateLimiter, uploadRateLimiter
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -116,6 +121,7 @@ func FullClientSettingsNew() FullClientSettings {
|
|||||||
|
|
||||||
var httpAddr string
|
var httpAddr string
|
||||||
var baseURL string
|
var baseURL string
|
||||||
|
var socksProxyURLBase string
|
||||||
var websocketClientPort string
|
var websocketClientPort string
|
||||||
var logLevel logrus.Level
|
var logLevel logrus.Level
|
||||||
//logging
|
//logging
|
||||||
@@ -148,6 +154,10 @@ func FullClientSettingsNew() FullClientSettings {
|
|||||||
baseURL = viper.GetString("reverseProxy.BaseURL")
|
baseURL = viper.GetString("reverseProxy.BaseURL")
|
||||||
fmt.Println("WebsocketClientPort", viper.GetString("serverConfig.ServerPort"))
|
fmt.Println("WebsocketClientPort", viper.GetString("serverConfig.ServerPort"))
|
||||||
}
|
}
|
||||||
|
socksProxySet := viper.GetBool("socksProxy.ProxyEnabled")
|
||||||
|
if socksProxySet {
|
||||||
|
socksProxyURLBase = viper.GetString("reverseProxy.BaseURL")
|
||||||
|
}
|
||||||
//Client Authentication
|
//Client Authentication
|
||||||
clientAuthEnabled := viper.GetBool("goTorrentWebUI.WebUIAuth")
|
clientAuthEnabled := viper.GetBool("goTorrentWebUI.WebUIAuth")
|
||||||
var webUIUser string
|
var webUIUser string
|
||||||
@@ -177,9 +187,9 @@ func FullClientSettingsNew() FullClientSettings {
|
|||||||
//Rate Limiters
|
//Rate Limiters
|
||||||
//var uploadRateLimiter *rate.Limiter
|
//var uploadRateLimiter *rate.Limiter
|
||||||
//var downloadRateLimiter *rate.Limiter
|
//var downloadRateLimiter *rate.Limiter
|
||||||
//uploadRate := viper.GetString("serverConfig.UploadRateLimit")
|
uploadRate := viper.GetString("serverConfig.UploadRateLimit")
|
||||||
//downloadRate := viper.GetString("serverConfig.DownloadRateLimit")
|
downloadRate := viper.GetString("serverConfig.DownloadRateLimit")
|
||||||
//downloadRateLimiter, uploadRateLimiter = calculateRateLimiters(uploadRate, downloadRate)
|
downloadRateLimiter, uploadRateLimiter := calculateRateLimiters(uploadRate, downloadRate)
|
||||||
//Internals
|
//Internals
|
||||||
dataDir := filepath.ToSlash(viper.GetString("torrentClientConfig.DownloadDir")) //Converting the string literal into a filepath
|
dataDir := filepath.ToSlash(viper.GetString("torrentClientConfig.DownloadDir")) //Converting the string literal into a filepath
|
||||||
dataDirAbs, err := filepath.Abs(dataDir) //Converting to an absolute file path
|
dataDirAbs, err := filepath.Abs(dataDir) //Converting to an absolute file path
|
||||||
@@ -191,6 +201,7 @@ func FullClientSettingsNew() FullClientSettings {
|
|||||||
noDHT := viper.GetBool("torrentClientConfig.NoDHT")
|
noDHT := viper.GetBool("torrentClientConfig.NoDHT")
|
||||||
noUpload := viper.GetBool("torrentClientConfig.NoUpload")
|
noUpload := viper.GetBool("torrentClientConfig.NoUpload")
|
||||||
seed := viper.GetBool("torrentClientConfig.Seed")
|
seed := viper.GetBool("torrentClientConfig.Seed")
|
||||||
|
maxActiveTorrents := viper.GetInt("serverConfig.MaxActiveTorrents")
|
||||||
|
|
||||||
peerID := viper.GetString("torrentClientConfig.PeerID")
|
peerID := viper.GetString("torrentClientConfig.PeerID")
|
||||||
disableUTP := viper.GetBool("torrentClientConfig.DisableUTP")
|
disableUTP := viper.GetBool("torrentClientConfig.DisableUTP")
|
||||||
@@ -198,13 +209,17 @@ func FullClientSettingsNew() FullClientSettings {
|
|||||||
disableIPv6 := viper.GetBool("torrentClientConfig.DisableIPv6")
|
disableIPv6 := viper.GetBool("torrentClientConfig.DisableIPv6")
|
||||||
debug := viper.GetBool("torrentClientConfig.Debug")
|
debug := viper.GetBool("torrentClientConfig.Debug")
|
||||||
|
|
||||||
dhtServerConfig := dht.ServerConfig{
|
//dhtServerConfig := dht.StartingNodesGetter()
|
||||||
StartingNodes: dht.GlobalBootstrapAddrs,
|
|
||||||
}
|
//if viper.IsSet("DHTConfig") {
|
||||||
if viper.IsSet("DHTConfig") {
|
// fmt.Println("Reading in custom DHT config")
|
||||||
fmt.Println("Reading in custom DHT config")
|
// dhtServerConfig = dhtServerSettings(dhtServerConfig)
|
||||||
dhtServerConfig = dhtServerSettings(dhtServerConfig)
|
//}
|
||||||
|
httpAddrPortInt64, err := strconv.ParseInt(httpAddrPort, 10, 0)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println("Failed creating 64-bit integer for goTorrent Port!", err)
|
||||||
}
|
}
|
||||||
|
httpAddrPortInt := int(httpAddrPortInt64) //converting to integer
|
||||||
|
|
||||||
encryptionPolicy := torrent.EncryptionPolicy{
|
encryptionPolicy := torrent.EncryptionPolicy{
|
||||||
DisableEncryption: viper.GetBool("EncryptionPolicy.DisableEncryption"),
|
DisableEncryption: viper.GetBool("EncryptionPolicy.DisableEncryption"),
|
||||||
@@ -212,22 +227,24 @@ func FullClientSettingsNew() FullClientSettings {
|
|||||||
PreferNoEncryption: viper.GetBool("EncryptionPolicy.PreferNoEncryption"),
|
PreferNoEncryption: viper.GetBool("EncryptionPolicy.PreferNoEncryption"),
|
||||||
}
|
}
|
||||||
|
|
||||||
tConfig := torrent.Config{
|
tConfig := torrent.NewDefaultClientConfig()
|
||||||
DataDir: dataDirAbs,
|
|
||||||
ListenAddr: listenAddr,
|
tConfig.DataDir = dataDirAbs
|
||||||
DisablePEX: disablePex,
|
tConfig.ListenPort = httpAddrPortInt
|
||||||
NoDHT: noDHT,
|
tConfig.DisablePEX = disablePex
|
||||||
DHTConfig: dhtServerConfig,
|
tConfig.NoDHT = noDHT
|
||||||
NoUpload: noUpload,
|
tConfig.NoUpload = noUpload
|
||||||
Seed: seed,
|
tConfig.Seed = seed
|
||||||
//UploadRateLimiter: uploadRateLimiter,
|
tConfig.UploadRateLimiter = uploadRateLimiter
|
||||||
//DownloadRateLimiter: downloadRateLimiter,
|
tConfig.DownloadRateLimiter = downloadRateLimiter
|
||||||
PeerID: peerID,
|
tConfig.PeerID = peerID
|
||||||
DisableUTP: disableUTP,
|
tConfig.DisableUTP = disableUTP
|
||||||
DisableTCP: disableTCP,
|
tConfig.DisableTCP = disableTCP
|
||||||
DisableIPv6: disableIPv6,
|
tConfig.DisableIPv6 = disableIPv6
|
||||||
Debug: debug,
|
tConfig.Debug = debug
|
||||||
EncryptionPolicy: encryptionPolicy,
|
tConfig.EncryptionPolicy = encryptionPolicy
|
||||||
|
if listenAddr != "" {
|
||||||
|
tConfig.SetListenAddr(listenAddr) //Setting the IP address to listen on
|
||||||
}
|
}
|
||||||
|
|
||||||
Config := FullClientSettings{
|
Config := FullClientSettings{
|
||||||
@@ -237,17 +254,20 @@ func FullClientSettingsNew() FullClientSettings {
|
|||||||
ClientConnectSettings: ClientConnectSettings{
|
ClientConnectSettings: ClientConnectSettings{
|
||||||
HTTPAddr: httpAddr,
|
HTTPAddr: httpAddr,
|
||||||
HTTPAddrIP: httpAddrIP,
|
HTTPAddrIP: httpAddrIP,
|
||||||
UseProxy: proxySet,
|
UseReverseProxy: proxySet,
|
||||||
|
UseSocksProxy: socksProxySet,
|
||||||
WebsocketClientPort: websocketClientPort,
|
WebsocketClientPort: websocketClientPort,
|
||||||
ClientUsername: webUIUser,
|
ClientUsername: webUIUser,
|
||||||
ClientPassword: webUIPasswordHash,
|
ClientPassword: webUIPasswordHash,
|
||||||
BaseURL: baseURL,
|
BaseURL: baseURL,
|
||||||
|
SocksProxyURL: socksProxyURLBase,
|
||||||
PushBulletToken: pushBulletToken,
|
PushBulletToken: pushBulletToken,
|
||||||
},
|
},
|
||||||
TFileUploadFolder: "uploadedTorrents",
|
TFileUploadFolder: "uploadedTorrents",
|
||||||
TorrentConfig: tConfig,
|
TorrentConfig: *tConfig,
|
||||||
DefaultMoveFolder: defaultMoveFolderAbs,
|
DefaultMoveFolder: defaultMoveFolderAbs,
|
||||||
TorrentWatchFolder: torrentWatchFolderAbs,
|
TorrentWatchFolder: torrentWatchFolderAbs,
|
||||||
|
MaxActiveTorrents: maxActiveTorrents,
|
||||||
}
|
}
|
||||||
|
|
||||||
return Config
|
return Config
|
||||||
|
@@ -1,6 +1,7 @@
|
|||||||
package storage
|
package storage
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
|
|
||||||
@@ -16,6 +17,14 @@ var Logger *logrus.Logger
|
|||||||
//Conn is the global websocket connection used to push server notification messages
|
//Conn is the global websocket connection used to push server notification messages
|
||||||
var Conn *websocket.Conn
|
var Conn *websocket.Conn
|
||||||
|
|
||||||
|
//TorrentQueues contains the active and queued torrent hashes in slices
|
||||||
|
type TorrentQueues struct {
|
||||||
|
ID int `storm:"id,unique"` //storm requires unique ID (will be 5)
|
||||||
|
ActiveTorrents []string
|
||||||
|
QueuedTorrents []string
|
||||||
|
ForcedTorrents []string
|
||||||
|
}
|
||||||
|
|
||||||
//IssuedTokensList contains a slice of all the tokens issues to applications
|
//IssuedTokensList contains a slice of all the tokens issues to applications
|
||||||
type IssuedTokensList struct {
|
type IssuedTokensList struct {
|
||||||
ID int `storm:"id,unique"` //storm requires unique ID (will be 3) to save although there will only be one of these
|
ID int `storm:"id,unique"` //storm requires unique ID (will be 3) to save although there will only be one of these
|
||||||
@@ -69,20 +78,20 @@ type TorrentLocal struct {
|
|||||||
DateAdded string
|
DateAdded string
|
||||||
StoragePath string //The absolute value of the path where the torrent will be moved when completed
|
StoragePath string //The absolute value of the path where the torrent will be moved when completed
|
||||||
TempStoragePath string //The absolute path of where the torrent is temporarily stored as it is downloaded
|
TempStoragePath string //The absolute path of where the torrent is temporarily stored as it is downloaded
|
||||||
TorrentMoved bool
|
TorrentMoved bool //If completed has the torrent been moved to the end location
|
||||||
TorrentName string
|
TorrentName string
|
||||||
TorrentStatus string
|
TorrentStatus string //"Stopped", "Running", "ForceStart"
|
||||||
TorrentUploadLimit bool //if true this torrent will bypass the upload storage limit (effectively unlimited)
|
TorrentUploadLimit bool //if true this torrent will bypass the upload storage limit (effectively unlimited)
|
||||||
MaxConnections int
|
MaxConnections int //Max connections that the torrent can have to it at one time
|
||||||
TorrentType string //magnet or .torrent file
|
TorrentType string //magnet or .torrent file
|
||||||
TorrentFileName string //Should be just the name of the torrent
|
TorrentFileName string //Should be just the name of the torrent
|
||||||
TorrentFile []byte
|
TorrentFile []byte //If torrent was from .torrent file, store the entire file for re-adding on restart
|
||||||
Label string
|
Label string //User enterable label to sort torrents by
|
||||||
UploadedBytes int64
|
UploadedBytes int64 //Total amount the client has uploaded on this torrent
|
||||||
DownloadedBytes int64
|
DownloadedBytes int64 //Total amount the client has downloaded on this torrent
|
||||||
TorrentSize int64 //If we cancel a file change the download size since we won't be downloading that file
|
TorrentSize int64 //If we cancel a file change the download size since we won't be downloading that file
|
||||||
UploadRatio string
|
UploadRatio string
|
||||||
TorrentFilePriority []TorrentFilePriority
|
TorrentFilePriority []TorrentFilePriority //Slice of all the files the torrent contains and the priority of each file
|
||||||
}
|
}
|
||||||
|
|
||||||
//SaveConfig saves the config to the database to compare for changes to settings.toml on restart
|
//SaveConfig saves the config to the database to compare for changes to settings.toml on restart
|
||||||
@@ -94,6 +103,26 @@ func SaveConfig(torrentStorage *storm.DB, config Settings.FullClientSettings) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//UpdateQueues Saves the slice of hashes that contain the active Torrents
|
||||||
|
func UpdateQueues(db *storm.DB, torrentQueues TorrentQueues) {
|
||||||
|
torrentQueues.ID = 5
|
||||||
|
err := db.Save(&torrentQueues)
|
||||||
|
if err != nil {
|
||||||
|
Logger.WithFields(logrus.Fields{"database": db, "error": err}).Error("Unable to write Queues to database!")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//FetchQueues fetches the activetorrent and queuedtorrent slices from the database
|
||||||
|
func FetchQueues(db *storm.DB) TorrentQueues {
|
||||||
|
torrentQueues := TorrentQueues{}
|
||||||
|
err := db.One("ID", 5, &torrentQueues)
|
||||||
|
if err != nil {
|
||||||
|
Logger.WithFields(logrus.Fields{"database": db, "error": err}).Error("Unable to read Database into torrentQueues!")
|
||||||
|
return torrentQueues
|
||||||
|
}
|
||||||
|
return torrentQueues
|
||||||
|
}
|
||||||
|
|
||||||
//FetchConfig fetches the client config from the database
|
//FetchConfig fetches the client config from the database
|
||||||
func FetchConfig(torrentStorage *storm.DB) (Settings.FullClientSettings, error) {
|
func FetchConfig(torrentStorage *storm.DB) (Settings.FullClientSettings, error) {
|
||||||
config := Settings.FullClientSettings{}
|
config := Settings.FullClientSettings{}
|
||||||
@@ -119,11 +148,11 @@ func FetchAllStoredTorrents(torrentStorage *storm.DB) (torrentLocalArray []*Torr
|
|||||||
//AddTorrentLocalStorage is called when adding a new torrent via any method, requires the boltdb pointer and the torrentlocal struct
|
//AddTorrentLocalStorage is called when adding a new torrent via any method, requires the boltdb pointer and the torrentlocal struct
|
||||||
func AddTorrentLocalStorage(torrentStorage *storm.DB, local TorrentLocal) {
|
func AddTorrentLocalStorage(torrentStorage *storm.DB, local TorrentLocal) {
|
||||||
Logger.WithFields(logrus.Fields{"Storage Path": local.StoragePath, "Torrent": local.TorrentName, "File(if file)": local.TorrentFileName}).Info("Adding new Torrent to database")
|
Logger.WithFields(logrus.Fields{"Storage Path": local.StoragePath, "Torrent": local.TorrentName, "File(if file)": local.TorrentFileName}).Info("Adding new Torrent to database")
|
||||||
|
fmt.Println("ENTIRE TORRENT", local)
|
||||||
err := torrentStorage.Save(&local)
|
err := torrentStorage.Save(&local)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
Logger.WithFields(logrus.Fields{"database": torrentStorage, "error": err}).Error("Error adding new Torrent to database!")
|
Logger.WithFields(logrus.Fields{"database": torrentStorage, "error": err}).Error("Error adding new Torrent to database!")
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
//DelTorrentLocalStorage is called to delete a torrent when we fail (for whatever reason to load the information for it). Deleted by HASH matching.
|
//DelTorrentLocalStorage is called to delete a torrent when we fail (for whatever reason to load the information for it). Deleted by HASH matching.
|
||||||
@@ -166,6 +195,8 @@ func UpdateStorageTick(torrentStorage *storm.DB, torrentLocal TorrentLocal) {
|
|||||||
err := torrentStorage.Update(&torrentLocal)
|
err := torrentStorage.Update(&torrentLocal)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
Logger.WithFields(logrus.Fields{"UpdateContents": torrentLocal, "error": err}).Error("Error performing tick update to database!")
|
Logger.WithFields(logrus.Fields{"UpdateContents": torrentLocal, "error": err}).Error("Error performing tick update to database!")
|
||||||
|
} else {
|
||||||
|
Logger.WithFields(logrus.Fields{"UpdateContents": torrentLocal, "error": err}).Debug("Performed Update to database!")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user