Adding logic to change torrent storage path

This commit is contained in:
2018-01-25 23:08:10 -05:00
parent f58ca5bb09
commit 6af49b317d
15 changed files with 279 additions and 60 deletions

11
.vscode/settings.json vendored
View File

@@ -1,3 +1,12 @@
{ {
"git.ignoreLimitWarning": true "git.ignoreLimitWarning": true,
"cSpell.words": [
"anacrolix",
"asdine",
"btih",
"gofeed",
"logrus",
"mmcdole",
"otiai"
]
} }

View File

@@ -9,15 +9,17 @@ import (
//All the message types are first, first the server handling messages from the client //All the message types are first, first the server handling messages from the client
//Message contains the JSON messages from the client, we first unmarshal to get the messagetype, then each module unmarshalls the actual message once we know the type //Message contains the JSON messages from the client, we first unmarshal to get the messagetype, then each module un-marshalls the actual message once we know the type
type Message struct { type Message struct {
MessageType string MessageType string
MessageDetail string `json:",omitempty"` MessageDetail string `json:",omitempty"`
MessageDetailTwo string `json:",omitempty"` MessageDetailTwo string `json:",omitempty"`
Payload []string MessageDetailThree string `json:",omitempty"`
Payload []string
} }
//Next are the messages the server sends to the client //Next are the messages the server sends to the client
//ServerPushMessage is information (usually logs and status messages) that the server pushes to the client //ServerPushMessage is information (usually logs and status messages) that the server pushes to the client
type ServerPushMessage struct { type ServerPushMessage struct {
MessageType string MessageType string
@@ -70,7 +72,7 @@ type TorrentFile struct {
} }
//ClientDB struct contains the struct that is used to compose the torrentlist //ClientDB struct contains the struct that is used to compose the torrentlist
type ClientDB struct { //TODO maybe seperate out the internal bits into another client struct type ClientDB struct { //TODO maybe separate out the internal bits into another client struct
TorrentHashString string `json:"TorrentHashString"` //Passed to client for displaying hash and is used to uniquly identify all torrents TorrentHashString string `json:"TorrentHashString"` //Passed to client for displaying hash and is used to uniquly identify all torrents
TorrentName string `json:"TorrentName"` TorrentName string `json:"TorrentName"`
DownloadedSize string `json:"DownloadedSize"` //how much the client has downloaded total DownloadedSize string `json:"DownloadedSize"` //how much the client has downloaded total
@@ -83,7 +85,7 @@ type ClientDB struct { //TODO maybe seperate out the internal bits into another
StoragePath string `json:"StoragePath"` //Passed to client (and stored in stormdb) StoragePath string `json:"StoragePath"` //Passed to client (and stored in stormdb)
DateAdded string //Passed to client (and stored in stormdb) DateAdded string //Passed to client (and stored in stormdb)
ETA string `json:"ETA"` //Passed to client ETA string `json:"ETA"` //Passed to client
Label string //Passed to client and stored in stormdb TorrentLabel string //Passed to client and stored in stormdb
SourceType string `json:"SourceType"` //Stores whether the torrent came from a torrent file or a magnet link SourceType string `json:"SourceType"` //Stores whether the torrent came from a torrent file or a magnet link
KnownSwarm []torrent.Peer //Passed to client for Peer Tab KnownSwarm []torrent.Peer //Passed to client for Peer Tab
UploadRatio string //Passed to client, stores the string for uploadratio stored in stormdb UploadRatio string //Passed to client, stores the string for uploadratio stored in stormdb

View File

@@ -40,7 +40,7 @@ func CheckTorrentWatchFolder(c *cron.Cron, db *storm.DB, tclient *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
} }
fullNewFilePath := filepath.Join(config.TFileUploadFolder, file.Name()) fullNewFilePath := filepath.Join(config.TFileUploadFolder, file.Name())
StartTorrent(clientTorrent, torrentLocalStorage, db, config.TorrentConfig.DataDir, "file", file.Name(), config.DefaultMoveFolder) StartTorrent(clientTorrent, torrentLocalStorage, db, config.TorrentConfig.DataDir, "file", file.Name(), config.DefaultMoveFolder, "default")
CopyFile(fullFilePath, fullNewFilePath) CopyFile(fullFilePath, fullNewFilePath)
os.Remove(fullFilePath) //delete the torrent after adding it and copying it over os.Remove(fullFilePath) //delete the torrent after adding it and copying it over
Logger.WithFields(logrus.Fields{"Source Folder": config.TorrentWatchFolder, "Destination Folder": config.TFileUploadFolder, "Torrent": file.Name()}).Info("Added torrent from watch folder, and moved torrent file") Logger.WithFields(logrus.Fields{"Source Folder": config.TorrentWatchFolder, "Destination Folder": config.TFileUploadFolder, "Torrent": file.Name()}).Info("Added torrent from watch folder, and moved torrent file")
@@ -78,7 +78,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, config.TorrentConfig.DataDir, "magnet", "", config.DefaultMoveFolder) //TODO let user specify torrent default storage location and let change on fly StartTorrent(clientTorrent, torrentLocalStorage, db, config.TorrentConfig.DataDir, "magnet", "", config.DefaultMoveFolder, "RSS") //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)
} }

View File

@@ -6,7 +6,6 @@ import (
"path/filepath" "path/filepath"
"runtime" "runtime"
"github.com/anacrolix/torrent"
"github.com/asdine/storm" "github.com/asdine/storm"
Storage "github.com/deranjer/goTorrent/storage" Storage "github.com/deranjer/goTorrent/storage"
pushbullet "github.com/mitsuse/pushbullet-go" pushbullet "github.com/mitsuse/pushbullet-go"
@@ -16,11 +15,11 @@ import (
) )
//MoveAndLeaveSymlink takes the file from the default download dir and moves it to the user specified directory and then leaves a symlink behind. //MoveAndLeaveSymlink takes the file from the default download dir and moves it to the user specified directory and then leaves a symlink behind.
func MoveAndLeaveSymlink(config FullClientSettings, singleTorrent *torrent.Torrent, db *storm.DB) { func MoveAndLeaveSymlink(config FullClientSettings, tHash string, db *storm.DB) {
Logger.WithFields(logrus.Fields{"Torrent Name": singleTorrent.Name()}).Info("Move and Create symlink started for torrent") tStorage := Storage.FetchTorrentFromStorage(db, tHash)
tStorage := Storage.FetchTorrentFromStorage(db, singleTorrent.InfoHash().String()) Logger.WithFields(logrus.Fields{"Torrent Name": tStorage.TorrentFileName}).Info("Move and Create symlink started for torrent")
oldFilePath := filepath.Join(config.TorrentConfig.DataDir, singleTorrent.Name()) oldFilePath := filepath.Join(config.TorrentConfig.DataDir, tStorage.TorrentFileName)
newFilePath := filepath.Join(tStorage.StoragePath, singleTorrent.Name()) newFilePath := filepath.Join(tStorage.StoragePath, tStorage.TorrentFileName)
_, err := os.Stat(tStorage.StoragePath) _, err := os.Stat(tStorage.StoragePath)
if os.IsNotExist(err) { if os.IsNotExist(err) {
err := os.MkdirAll(tStorage.StoragePath, 0755) err := os.MkdirAll(tStorage.StoragePath, 0755)
@@ -40,7 +39,7 @@ func MoveAndLeaveSymlink(config FullClientSettings, singleTorrent *torrent.Torre
os.Mkdir(newFilePath, 0755) os.Mkdir(newFilePath, 0755)
folderCopy.Copy(oldFilePath, newFilePath) //copy the folder to the new location folderCopy.Copy(oldFilePath, newFilePath) //copy the folder to the new location
os.Chmod(newFilePath, 0777) os.Chmod(newFilePath, 0777)
notifyUser(tStorage, config, singleTorrent, db) notifyUser(tStorage, config, db)
return return
} }
srcFile, err := os.Open(oldFilePath) srcFile, err := os.Open(oldFilePath)
@@ -66,7 +65,7 @@ func MoveAndLeaveSymlink(config FullClientSettings, singleTorrent *torrent.Torre
Logger.WithFields(logrus.Fields{"Old File Path": oldFilePath, "New File Path": newFilePath, "error": err}).Error("Windows: Error syncing new file to disk") Logger.WithFields(logrus.Fields{"Old File Path": oldFilePath, "New File Path": newFilePath, "error": err}).Error("Windows: Error syncing new file to disk")
} }
Logger.WithFields(logrus.Fields{"Old File Path": oldFilePath, "New File Path": newFilePath, "bytesWritten": bytesWritten}).Info("Windows Torrent Copy Completed") Logger.WithFields(logrus.Fields{"Old File Path": oldFilePath, "New File Path": newFilePath, "bytesWritten": bytesWritten}).Info("Windows Torrent Copy Completed")
notifyUser(tStorage, config, singleTorrent, db) notifyUser(tStorage, config, db)
} else { } else {
folderCopy.Copy(oldFilePath, newFilePath) folderCopy.Copy(oldFilePath, newFilePath)
os.Chmod(newFilePath, 0777) //changing permissions on the new file to be permissive os.Chmod(newFilePath, 0777) //changing permissions on the new file to be permissive
@@ -76,28 +75,28 @@ func MoveAndLeaveSymlink(config FullClientSettings, singleTorrent *torrent.Torre
Logger.WithFields(logrus.Fields{"Old File Path": oldFilePath, "New File Path": newFilePath, "error": err}).Error("Error creating symlink") Logger.WithFields(logrus.Fields{"Old File Path": oldFilePath, "New File Path": newFilePath, "error": err}).Error("Error creating symlink")
return return
} }
notifyUser(tStorage, config, singleTorrent, db) notifyUser(tStorage, config, db)
Logger.WithFields(logrus.Fields{"Old File Path": oldFilePath, "New File Path": newFilePath}).Info("Moving completed torrent") Logger.WithFields(logrus.Fields{"Old File Path": oldFilePath, "New File Path": newFilePath}).Info("Moving completed torrent")
} }
} }
} }
func notifyUser(tStorage Storage.TorrentLocal, config FullClientSettings, singleTorrent *torrent.Torrent, db *storm.DB) { func notifyUser(tStorage Storage.TorrentLocal, config FullClientSettings, db *storm.DB) {
Logger.WithFields(logrus.Fields{"New File Path": tStorage.StoragePath, "Torrent Name": singleTorrent.Name()}).Info("Attempting to notify user..") Logger.WithFields(logrus.Fields{"New File Path": tStorage.StoragePath, "Torrent Name": tStorage.TorrentFileName}).Info("Attempting to notify user..")
tStorage.TorrentMoved = true tStorage.TorrentMoved = true
Storage.AddTorrentLocalStorage(db, tStorage) //Updating the fact that we moved the torrent Storage.AddTorrentLocalStorage(db, tStorage) //Updating the fact that we moved the torrent
if config.PushBulletToken != "" { if config.PushBulletToken != "" {
pb := pushbullet.New(config.PushBulletToken) pb := pushbullet.New(config.PushBulletToken)
n := requests.NewNote() n := requests.NewNote()
n.Title = singleTorrent.Name() n.Title = tStorage.TorrentFileName
n.Body = "Completed and moved to " + tStorage.StoragePath n.Body = "Completed and moved to " + tStorage.StoragePath
if _, err := pb.PostPushesNote(n); err != nil { if _, err := pb.PostPushesNote(n); err != nil {
Logger.WithFields(logrus.Fields{"Torrent": singleTorrent.Name(), "New File Path": tStorage.StoragePath, "error": err}).Error("Error pushing PushBullet Note") Logger.WithFields(logrus.Fields{"Torrent": tStorage.TorrentFileName, "New File Path": tStorage.StoragePath, "error": err}).Error("Error pushing PushBullet Note")
return return
} }
Logger.WithFields(logrus.Fields{"Torrent": singleTorrent.Name(), "New File Path": tStorage.StoragePath}).Info("Pushbullet note sent") Logger.WithFields(logrus.Fields{"Torrent": tStorage.TorrentFileName, "New File Path": tStorage.StoragePath}).Info("Pushbullet note sent")
} else { } else {
Logger.WithFields(logrus.Fields{"New File Path": tStorage.StoragePath, "Torrent Name": singleTorrent.Name()}).Info("No pushbullet API key set, not notifying") Logger.WithFields(logrus.Fields{"New File Path": tStorage.StoragePath, "Torrent Name": tStorage.TorrentFileName}).Info("No pushbullet API key set, not notifying")
} }
} }

View File

@@ -0,0 +1,46 @@
package engine
import (
"testing"
"github.com/asdine/storm"
Storage "github.com/deranjer/goTorrent/storage"
)
func TestMoveAndLeaveSymlink(t *testing.T) {
type args struct {
config FullClientSettings
tStorage Storage.TorrentLocal
db *storm.DB
}
tests := []struct {
name string
args args
}{
// TODO: Add test cases.
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
MoveAndLeaveSymlink(tt.args.config, tt.args.tStorage, tt.args.db)
})
}
}
func Test_notifyUser(t *testing.T) {
type args struct {
tStorage Storage.TorrentLocal
config FullClientSettings
db *storm.DB
}
tests := []struct {
name string
args args
}{
// TODO: Add test cases.
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
notifyUser(tt.args.tStorage, tt.args.config, tt.args.db)
})
}
}

View File

@@ -84,7 +84,7 @@ func timeOutInfo(clientTorrent *torrent.Torrent, seconds time.Duration) (deleted
}() }()
select { select {
case <-clientTorrent.GotInfo(): //attempting to retrieve info for torrent case <-clientTorrent.GotInfo(): //attempting to retrieve info for torrent
Logger.WithFields(logrus.Fields{"clientTorrentName": clientTorrent.Name()}).Debug("Recieved torrent info for torrent") Logger.WithFields(logrus.Fields{"clientTorrentName": clientTorrent.Name()}).Debug("Received torrent info for torrent")
clientTorrent.DownloadAll() clientTorrent.DownloadAll()
return false return false
case <-timeout: // getting info for torrent has timed out so purging the torrent case <-timeout: // getting info for torrent has timed out so purging the torrent
@@ -123,8 +123,8 @@ func readTorrentFileFromDB(element *Storage.TorrentLocal, tclient *torrent.Clien
} }
//StartTorrent creates the storage.db entry and starts A NEW TORRENT and adds to the running torrent array //StartTorrent 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, dataDir string, torrentType string, torrentFileName string, torrentStoragePath string) { func StartTorrent(clientTorrent *torrent.Torrent, torrentLocalStorage Storage.TorrentLocal, torrentDbStorage *storm.DB, dataDir string, torrentType string, torrentFileName string, torrentStoragePath string, labelValue string) {
timedOut := timeOutInfo(clientTorrent, 45) //seeing if adding the torrrent 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
} }
@@ -139,6 +139,7 @@ func StartTorrent(clientTorrent *torrent.Torrent, torrentLocalStorage Storage.To
} }
torrentLocalStorage.Hash = TempHash.String() // we will store the infohash to add it back later on client restart (if needed) torrentLocalStorage.Hash = TempHash.String() // we will store the infohash to add it back later on client restart (if needed)
torrentLocalStorage.InfoBytes = clientTorrent.Metainfo().InfoBytes torrentLocalStorage.InfoBytes = clientTorrent.Metainfo().InfoBytes
torrentLocalStorage.Label = labelValue
torrentLocalStorage.DateAdded = time.Now().Format("Jan _2 2006") torrentLocalStorage.DateAdded = time.Now().Format("Jan _2 2006")
torrentLocalStorage.StoragePath = torrentStoragePath torrentLocalStorage.StoragePath = torrentStoragePath
torrentLocalStorage.TorrentName = clientTorrent.Name() torrentLocalStorage.TorrentName = clientTorrent.Name()
@@ -190,7 +191,7 @@ func CreateRunningTorrentArray(tclient *torrent.Client, TorrentLocalArray []*Sto
} }
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)
if timeOut == true { // if we did timeout then drop the torrent from the boltdb database if timeOut == true { // if we did timeout then drop the torrent from the bolt.db database
Storage.DelTorrentLocalStorage(db, singleTorrentFromStorage.Hash) //purging torrent from the local database Storage.DelTorrentLocalStorage(db, singleTorrentFromStorage.Hash) //purging torrent from the local database
continue continue
} }
@@ -204,8 +205,8 @@ func CreateRunningTorrentArray(tclient *torrent.Client, TorrentLocalArray []*Sto
//Logger.WithFields(logrus.Fields{"singleTorrent": singleTorrentFromStorage.TorrentName}).Info("Generating infohash") //Logger.WithFields(logrus.Fields{"singleTorrent": singleTorrentFromStorage.TorrentName}).Info("Generating infohash")
TempHash = singleTorrent.InfoHash() TempHash = singleTorrent.InfoHash()
if (singleTorrent.BytesCompleted() == singleTorrent.Length()) && (singleTorrentFromStorage.TorrentMoved == false) { //if we are done downloading and havent moved torrent yet if (singleTorrent.BytesCompleted() == singleTorrent.Length()) && (singleTorrentFromStorage.TorrentMoved == false) { //if we are done downloading and haven't moved torrent yet
MoveAndLeaveSymlink(config, singleTorrent, db) //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 MoveAndLeaveSymlink(config, singleTorrent.InfoHash().String(), db) //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
} }
fullStruct := singleTorrent.Stats() fullStruct := singleTorrent.Stats()
@@ -232,6 +233,7 @@ func CreateRunningTorrentArray(tclient *torrent.Client, TorrentLocalArray []*Sto
fullClientDB.StoragePath = singleTorrentFromStorage.StoragePath fullClientDB.StoragePath = singleTorrentFromStorage.StoragePath
fullClientDB.TorrentName = singleTorrentFromStorage.TorrentName fullClientDB.TorrentName = singleTorrentFromStorage.TorrentName
fullClientDB.DateAdded = singleTorrentFromStorage.DateAdded fullClientDB.DateAdded = singleTorrentFromStorage.DateAdded
fullClientDB.TorrentLabel = singleTorrentFromStorage.Label
fullClientDB.BytesCompleted = singleTorrent.BytesCompleted() fullClientDB.BytesCompleted = singleTorrent.BytesCompleted()
fullClientDB.NumberofFiles = len(singleTorrent.Files()) fullClientDB.NumberofFiles = len(singleTorrent.Files())
@@ -245,7 +247,7 @@ func CreateRunningTorrentArray(tclient *torrent.Client, TorrentLocalArray []*Sto
} }
} }
} }
CalculateTorrentETA(singleTorrent, fullClientDB) //needs to be here since we need the speed calcuated before we can estimate the eta. CalculateTorrentETA(singleTorrent, fullClientDB) //needs to be here since we need the speed calculated before we can estimate the eta.
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
@@ -343,3 +345,19 @@ func CreateTorrentDetailJSON(tclient *torrent.Client, selectedHash string, torre
} }
return TorrentDetailStruct return TorrentDetailStruct
} }
func ChangeStorageLocation(newStorageLocation string, torrentHashes []string, db *storm.DB) {
for _, torrentHash := range torrentHashes {
var selectedTorrent Storage.TorrentLocal
err := db.Find("TorrentLocal", torrentHash, &selectedTorrent)
if err != nil {
Logger.WithFields(logrus.Fields{"torrentHash": torrentHash}).Error("Unable to find torrent in db to update!")
CreateServerPushMessage(ServerPushMessage{MessageType: "serverPushMessage", MessageLevel: "error", Payload: "Failed to change Storage Location"}, Conn)
}
fmt.Printf("%+v\n", selectedTorrent)
db.UpdateField(&selectedTorrent{Hash: torrentHash}, "StoragePath", newStorageLocation)
}
}

View File

@@ -61,6 +61,7 @@ ws.onmessage = function (evt) { //When we recieve a message from the websocket
FileNumber: serverMessage.data[i].NumberofFiles, FileNumber: serverMessage.data[i].NumberofFiles,
PieceNumber: serverMessage.data[i].NumberofPieces, PieceNumber: serverMessage.data[i].NumberofPieces,
MaxConnections: serverMessage.data[i].MaxConnections, MaxConnections: serverMessage.data[i].MaxConnections,
Label: serverMessage.data[i].TorrentLabel,
}) })
} }
var newTitle = '(' + serverMessage.total + ')' + title; //updating the title var newTitle = '(' + serverMessage.total + ')' + title; //updating the title

View File

@@ -64,7 +64,7 @@ class GeneralTab extends React.Component {
<Paper className={classes.paper}>Storage Path: <span className={classes.floatRight}>{this.state.selectedTorrent["StoragePath"]} </span> </Paper> <Paper className={classes.paper}>Storage Path: <span className={classes.floatRight}>{this.state.selectedTorrent["StoragePath"]} </span> </Paper>
<Paper className={classes.paper}>Date Added: <span className={classes.floatRight}> {this.state.selectedTorrent["DateAdded"]} </span> </Paper> <Paper className={classes.paper}>Date Added: <span className={classes.floatRight}> {this.state.selectedTorrent["DateAdded"]} </span> </Paper>
<Paper className={classes.paper}>Source Type: <span className={classes.floatRight}> {this.state.selectedTorrent["SourceType"]} </span> </Paper> <Paper className={classes.paper}>Source Type: <span className={classes.floatRight}> {this.state.selectedTorrent["SourceType"]} </span> </Paper>
<Paper className={classes.paper}>Label: <span className={classes.floatRight}> None </span> </Paper> <Paper className={classes.paper}>Label: <span className={classes.floatRight}> {this.state.selectedTorrent["TorrentLabel"]} </span> </Paper>
<Paper className={classes.paper}>Torrent Hash: <span className={classes.floatRight}> {this.state.selectedTorrent["TorrentHashString"]} </span> </Paper> <Paper className={classes.paper}>Torrent Hash: <span className={classes.floatRight}> {this.state.selectedTorrent["TorrentHashString"]} </span> </Paper>
</Grid> </Grid>
@@ -82,8 +82,6 @@ class GeneralTab extends React.Component {
<Paper className={classes.paper}>Number of Files: <span className={classes.floatRight}>{this.state.selectedTorrent["FileNumber"]} </span> </Paper> <Paper className={classes.paper}>Number of Files: <span className={classes.floatRight}>{this.state.selectedTorrent["FileNumber"]} </span> </Paper>
<Paper className={classes.paper}>Number of Pieces: <span className={classes.floatRight}>{this.state.selectedTorrent["PieceNumber"]} </span> </Paper> <Paper className={classes.paper}>Number of Pieces: <span className={classes.floatRight}>{this.state.selectedTorrent["PieceNumber"]} </span> </Paper>
</Grid> </Grid>
</Grid> </Grid>
</div> </div>

View File

@@ -74,7 +74,6 @@ const inlineStyle = {
); );
} }
}; };

View File

@@ -46,6 +46,7 @@ export default class addTorrentFilePopup extends React.Component {
torrentFileValue: [], torrentFileValue: [],
storageValue: ``, //raw string for possible windows filepath storageValue: ``, //raw string for possible windows filepath
showDrop: true, showDrop: true,
torrentLabel: "",
}; };
handleClickOpen = () => { handleClickOpen = () => {
@@ -68,8 +69,9 @@ export default class addTorrentFilePopup extends React.Component {
let torrentFileMessage = { let torrentFileMessage = {
messageType: "torrentFileSubmit", messageType: "torrentFileSubmit",
messageDetail: this.state.torrentFileName, torrentFileName: this.state.torrentFileName,
messageDetailTwo: this.state.storageValue, torrentStorageValue : this.state.storageValue,
torrentLabelValue: this.state.torrentLabel,
Payload: [base64data], Payload: [base64data],
} }
console.log("Sending magnet link: ", torrentFileMessage); console.log("Sending magnet link: ", torrentFileMessage);
@@ -85,7 +87,9 @@ export default class addTorrentFilePopup extends React.Component {
console.log("File Name", file[0].name) console.log("File Name", file[0].name)
} }
setLabelValue = (event) => {
this.setState({torrentLabel: event.target.value})
}
setStorageValue = (event) => { setStorageValue = (event) => {
this.setState({storageValue: event.target.value}) this.setState({storageValue: event.target.value})
@@ -114,6 +118,7 @@ export default class addTorrentFilePopup extends React.Component {
this.state.torrentFileName this.state.torrentFileName
} }
<TextField id="storagePath" type="text" label="Storage Path" placeholder="Empty will be default torrent storage path" fullWidth onChange={this.setStorageValue} /> <TextField id="storagePath" type="text" label="Storage Path" placeholder="Empty will be default torrent storage path" fullWidth onChange={this.setStorageValue} />
<TextField id="labelValue" type="text" label="Label Value" placeholder="Empty will be no label" fullWidth onChange={this.setLabelValue} />
</DialogContent> </DialogContent>
<DialogActions> <DialogActions>
<Button onClick={this.handleRequestClose} color="primary"> <Button onClick={this.handleRequestClose} color="primary">

View File

@@ -37,6 +37,7 @@ export default class addTorrentPopup extends React.Component {
open: false, open: false,
magnetLinkValue: "", magnetLinkValue: "",
storageValue: ``, storageValue: ``,
torrentLabel: "",
}; };
@@ -53,14 +54,13 @@ export default class addTorrentPopup extends React.Component {
//let magnetLinkSubmit = this.state.textValue; //let magnetLinkSubmit = this.state.textValue;
let magnetLinkMessage = { let magnetLinkMessage = {
messageType: "magnetLinkSubmit", messageType: "magnetLinkSubmit",
messageDetail: this.state.storageValue, storageValue: this.state.storageValue,
torrentLabel: this.state.torrentLabel,
Payload: [this.state.magnetLinkValue] Payload: [this.state.magnetLinkValue]
} }
console.log("Sending magnet link: ", magnetLinkMessage); console.log("Sending magnet link: ", magnetLinkMessage);
ws.send(JSON.stringify(magnetLinkMessage)); ws.send(JSON.stringify(magnetLinkMessage));
this.setState({magnetLinkValue: ""}) this.setState({magnetLinkValue: ""}, {torrentLabel: ""}, {storageValue: ``})
this.setState({storageValue: ``})
console.log("Magnet Link", this.state.magnetLinkValue)
} }
setMagnetLinkValue = (event) => { setMagnetLinkValue = (event) => {
@@ -71,6 +71,10 @@ export default class addTorrentPopup extends React.Component {
this.setState({storageValue: event.target.value}) this.setState({storageValue: event.target.value})
} }
setLabelValue = (event) => {
this.setState({torrentLabel: event.target.value})
}
render() { render() {
const { classes, onRequestClose, handleRequestClose, handleSubmit } = this.props; const { classes, onRequestClose, handleRequestClose, handleSubmit } = this.props;
return ( return (
@@ -96,6 +100,7 @@ export default class addTorrentPopup extends React.Component {
onChange={this.setMagnetLinkValue} onChange={this.setMagnetLinkValue}
/> />
<TextField id="storagePath" type="text" label="Storage Path" placeholder="Empty will be default torrent storage path" fullWidth onChange={this.setStorageValue} /> <TextField id="storagePath" type="text" label="Storage Path" placeholder="Empty will be default torrent storage path" fullWidth onChange={this.setStorageValue} />
<TextField id="labelValue" type="text" label="Label Value" placeholder="Empty will be no label" fullWidth onChange={this.setLabelValue} />
</DialogContent> </DialogContent>
<DialogActions> <DialogActions>
<Button onClick={this.handleRequestClose} color="primary"> <Button onClick={this.handleRequestClose} color="primary">
@@ -109,5 +114,4 @@ export default class addTorrentPopup extends React.Component {
</div> </div>
); );
} }
}; };

View File

@@ -0,0 +1,116 @@
import React from 'react';
import ReactDOM from 'react-dom';
import Button from 'material-ui/Button';
import TextField from 'material-ui/TextField';
import { withStyles } from 'material-ui/styles';
import PropTypes from 'prop-types';
import Dialog, {
DialogActions,
DialogContent,
DialogContentText,
DialogTitle,
} from 'material-ui/Dialog';
import StorageIcon from 'material-ui-icons/Storage';
import ReactTooltip from 'react-tooltip'
import Icon from 'material-ui/Icon';
import IconButton from 'material-ui/IconButton';
//Importing Redux
import {connect} from 'react-redux';
import * as actionTypes from '../store/actions';
const button = {
fontSize: '60px',
paddingRight: '20px',
paddingLeft: '20px',
}
const inlineStyle = {
display: 'inline-block',
backdrop: 'static',
}
class addTorrentPopup extends React.Component {
state = {
open: false,
storageValue: ``,
};
handleClickOpen = () => {
this.setState({ open: true });
};
handleRequestClose = () => {
this.setState({ open: false });
};
handleSubmit = () => {
this.setState({ open: false });
//let magnetLinkSubmit = this.state.textValue;
let changeStorageMessage = {
messageType: "changeStorageValue",
newStorageValue: this.state.storageValue,
Payload: [this.props.selectionHashes]
}
console.log("Sending new Storage Location: ", changeStorageMessage);
ws.send(JSON.stringify(changeStorageMessage));
this.setState({storageValue: ``})
}
setStorageValue = (event) => {
this.setState({storageValue: event.target.value})
}
render() {
const { classes, onRequestClose, handleRequestClose, handleSubmit } = this.props;
return (
<div style={inlineStyle}>
<IconButton onClick={this.handleClickOpen} color="primary" data-tip="Change Storage Location" style={button} centerRipple aria-label="Change Storage Location" >
<ReactTooltip place="top" type="light" effect="float" />
<StorageIcon />
</IconButton>
<Dialog open={this.state.open} onRequestClose={this.handleRequestClose}>
<DialogTitle>Change Storage Value</DialogTitle>
<DialogContent>
<DialogContentText>
Add a new Storage Location for selected Torrents and hit Submit
</DialogContentText>
<TextField
autoFocus
margin="dense"
id="name"
label="Storage Value"
type="text"
placeholder="Enter Storage Value Here"
fullWidth
onChange={this.setStorageValue}
/>
</DialogContent>
<DialogActions>
<Button onClick={this.handleRequestClose} color="primary">
Cancel
</Button>
<Button onClick={this.handleSubmit} color="primary">
Submit
</Button>
</DialogActions>
</Dialog>
</div>
);
}
};
const mapStateToProps = state => {
return {
selectionHashes: state.selectionHashes,
selection: state.selection,
};
}
export default connect(mapStateToProps)(BackendSocket);

22
main.go
View File

@@ -30,7 +30,7 @@ type SingleRSSFeedMessage struct { //TODO had issues with getting this to work w
URL string //the URL of the individual RSS feed URL string //the URL of the individual RSS feed
Name string Name string
TotalTorrents int TotalTorrents int
Torrents []Storage.SingleRSSTorrent //name of the torrentss Torrents []Storage.SingleRSSTorrent //name of the torrents
} }
var ( var (
@@ -168,7 +168,6 @@ func main() {
case "torrentDetailedInfo": case "torrentDetailedInfo":
Logger.WithFields(logrus.Fields{"message": msg}).Debug("Client Requested TorrentListDetail Update") Logger.WithFields(logrus.Fields{"message": msg}).Debug("Client Requested TorrentListDetail Update")
torrentDetailArray := Engine.CreateTorrentDetailJSON(tclient, msg.Payload[0], db) torrentDetailArray := Engine.CreateTorrentDetailJSON(tclient, msg.Payload[0], db)
conn.WriteJSON(torrentDetailArray) conn.WriteJSON(torrentDetailArray)
@@ -177,6 +176,19 @@ func main() {
torrentPeerList := Engine.CreatePeerListArray(tclient, msg.Payload[0]) torrentPeerList := Engine.CreatePeerListArray(tclient, msg.Payload[0])
conn.WriteJSON(torrentPeerList) conn.WriteJSON(torrentPeerList)
case "changeStorageValue":
Logger.WithFields(logrus.Fields{"message": msg}).Debug("Client Requested Storage Location Update")
newStorageLocation := msg.MessageDetail
hashes := msg.Payload
for _, singleHash := range hashes {
singleTorrent := Storage.FetchTorrentFromStorage(db, singleHash)
singleTorrent.StoragePath = newStorageLocation
Storage.UpdateStorageTick(db, singleTorrent) //push torrent to storage
if singleTorrent.TorrentMoved == true { //If torrent has already been moved and I change path then move it again... TODO, does this work with symlinks?
Engine.MoveAndLeaveSymlink(Config, singleHash, db)
}
}
case "settingsFileRequest": case "settingsFileRequest":
Logger.WithFields(logrus.Fields{"message": msg}).Debug("Client Requested Settings File") Logger.WithFields(logrus.Fields{"message": msg}).Debug("Client Requested Settings File")
clientSettingsFile, err := json.Marshal(Config) clientSettingsFile, err := json.Marshal(Config)
@@ -246,6 +258,7 @@ func main() {
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 := msg.MessageDetail storageValue := msg.MessageDetail
labelValue := msg.MessageDetailTwo
if storageValue == "" { if storageValue == "" {
storageValue, err = filepath.Abs(filepath.ToSlash(Config.DefaultMoveFolder)) storageValue, err = filepath.Abs(filepath.ToSlash(Config.DefaultMoveFolder))
if err != nil { if err != nil {
@@ -268,7 +281,7 @@ 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)
Engine.StartTorrent(clientTorrent, torrentLocalStorage, db, Config.TorrentConfig.DataDir, "magnet", "", storageValue) //starting the torrent and creating local DB entry Engine.StartTorrent(clientTorrent, torrentLocalStorage, db, Config.TorrentConfig.DataDir, "magnet", "", storageValue, labelValue) //starting the torrent and creating local DB entry
} }
@@ -282,6 +295,7 @@ func main() {
} }
FileName := msg.MessageDetail FileName := msg.MessageDetail
storageValue := msg.MessageDetailTwo storageValue := msg.MessageDetailTwo
labelValue := msg.MessageDetailThree
if storageValue == "" { if storageValue == "" {
storageValue, err = filepath.Abs(filepath.ToSlash(Config.DefaultMoveFolder)) storageValue, err = filepath.Abs(filepath.ToSlash(Config.DefaultMoveFolder))
if err != nil { if err != nil {
@@ -310,7 +324,7 @@ 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": filePath}).Info("Added torrent") Logger.WithFields(logrus.Fields{"clienttorrent": clientTorrent.Name(), "filename": filePath}).Info("Added torrent")
Engine.StartTorrent(clientTorrent, torrentLocalStorage, db, Config.TorrentConfig.DataDir, "file", filePath, storageValue) Engine.StartTorrent(clientTorrent, torrentLocalStorage, db, Config.TorrentConfig.DataDir, "file", filePath, storageValue, labelValue)
case "stopTorrents": case "stopTorrents":
TorrentListCommands := msg.Payload TorrentListCommands := msg.Payload

View File

@@ -87004,7 +87004,8 @@ var addTorrentPopup = function (_React$Component) {
return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = addTorrentPopup.__proto__ || Object.getPrototypeOf(addTorrentPopup)).call.apply(_ref, [this].concat(args))), _this), _this.state = { return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = addTorrentPopup.__proto__ || Object.getPrototypeOf(addTorrentPopup)).call.apply(_ref, [this].concat(args))), _this), _this.state = {
open: false, open: false,
magnetLinkValue: "", magnetLinkValue: "",
storageValue: '' storageValue: '',
torrentLabel: ""
}, _this.handleClickOpen = function () { }, _this.handleClickOpen = function () {
_this.setState({ open: true }); _this.setState({ open: true });
@@ -87015,7 +87016,8 @@ var addTorrentPopup = function (_React$Component) {
//let magnetLinkSubmit = this.state.textValue; //let magnetLinkSubmit = this.state.textValue;
var magnetLinkMessage = { var magnetLinkMessage = {
messageType: "magnetLinkSubmit", messageType: "magnetLinkSubmit",
messageDetail: _this.state.storageValue, storageValue: _this.state.storageValue,
torrentLabel: _this.state.torrentLabel,
Payload: [_this.state.magnetLinkValue] Payload: [_this.state.magnetLinkValue]
}; };
console.log("Sending magnet link: ", magnetLinkMessage); console.log("Sending magnet link: ", magnetLinkMessage);
@@ -87027,6 +87029,8 @@ var addTorrentPopup = function (_React$Component) {
_this.setState({ magnetLinkValue: event.target.value }); _this.setState({ magnetLinkValue: event.target.value });
}, _this.setStorageValue = function (event) { }, _this.setStorageValue = function (event) {
_this.setState({ storageValue: event.target.value }); _this.setState({ storageValue: event.target.value });
}, _this.setLabelValue = function (event) {
_this.setState({ torrentLabel: event.target.value });
}, _temp), _possibleConstructorReturn(_this, _ret); }, _temp), _possibleConstructorReturn(_this, _ret);
} }
@@ -87074,7 +87078,8 @@ var addTorrentPopup = function (_React$Component) {
fullWidth: true, fullWidth: true,
onChange: this.setMagnetLinkValue onChange: this.setMagnetLinkValue
}), }),
_react2.default.createElement(_TextField2.default, { id: 'storagePath', type: 'text', label: 'Storage Path', placeholder: 'Empty will be default torrent storage path', fullWidth: true, onChange: this.setStorageValue }) _react2.default.createElement(_TextField2.default, { id: 'storagePath', type: 'text', label: 'Storage Path', placeholder: 'Empty will be default torrent storage path', fullWidth: true, onChange: this.setStorageValue }),
_react2.default.createElement(_TextField2.default, { id: 'labelValue', type: 'text', label: 'Label Value', placeholder: 'Empty will be no label', fullWidth: true, onChange: this.setLabelValue })
), ),
_react2.default.createElement( _react2.default.createElement(
_Dialog.DialogActions, _Dialog.DialogActions,
@@ -95273,7 +95278,8 @@ var addTorrentFilePopup = function (_React$Component) {
torrentFileName: "", torrentFileName: "",
torrentFileValue: [], torrentFileValue: [],
storageValue: '', //raw string for possible windows filepath storageValue: '', //raw string for possible windows filepath
showDrop: true showDrop: true,
torrentLabel: ""
}, _this.handleClickOpen = function () { }, _this.handleClickOpen = function () {
_this.setState({ open: true }); _this.setState({ open: true });
}, _this.handleRequestClose = function () { }, _this.handleRequestClose = function () {
@@ -95290,8 +95296,9 @@ var addTorrentFilePopup = function (_React$Component) {
var torrentFileMessage = { var torrentFileMessage = {
messageType: "torrentFileSubmit", messageType: "torrentFileSubmit",
messageDetail: _this.state.torrentFileName, torrentFileName: _this.state.torrentFileName,
messageDetailTwo: _this.state.storageValue, torrentStorageValue: _this.state.storageValue,
torrentLabelValue: _this.state.torrentLabel,
Payload: [base64data] Payload: [base64data]
}; };
console.log("Sending magnet link: ", torrentFileMessage); console.log("Sending magnet link: ", torrentFileMessage);
@@ -95303,6 +95310,8 @@ var addTorrentFilePopup = function (_React$Component) {
_this.setState({ showDrop: false }); _this.setState({ showDrop: false });
_this.setState({ torrentFileValue: file }); _this.setState({ torrentFileValue: file });
console.log("File Name", file[0].name); console.log("File Name", file[0].name);
}, _this.setLabelValue = function (event) {
_this.setState({ torrentLabel: event.target.value });
}, _this.setStorageValue = function (event) { }, _this.setStorageValue = function (event) {
_this.setState({ storageValue: event.target.value }); _this.setState({ storageValue: event.target.value });
}, _temp), _possibleConstructorReturn(_this, _ret); }, _temp), _possibleConstructorReturn(_this, _ret);
@@ -95344,7 +95353,8 @@ var addTorrentFilePopup = function (_React$Component) {
'Upload Torrent Here and Add Storage Path' 'Upload Torrent Here and Add Storage Path'
), ),
this.state.torrentFileName != "" && this.state.torrentFileName, this.state.torrentFileName != "" && this.state.torrentFileName,
_react2.default.createElement(_TextField2.default, { id: 'storagePath', type: 'text', label: 'Storage Path', placeholder: 'Empty will be default torrent storage path', fullWidth: true, onChange: this.setStorageValue }) _react2.default.createElement(_TextField2.default, { id: 'storagePath', type: 'text', label: 'Storage Path', placeholder: 'Empty will be default torrent storage path', fullWidth: true, onChange: this.setStorageValue }),
_react2.default.createElement(_TextField2.default, { id: 'labelValue', type: 'text', label: 'Label Value', placeholder: 'Empty will be no label', fullWidth: true, onChange: this.setLabelValue })
), ),
_react2.default.createElement( _react2.default.createElement(
_Dialog.DialogActions, _Dialog.DialogActions,
@@ -129840,13 +129850,11 @@ var mapStateToProps = function mapStateToProps(state) {
return { return {
selectionHashes: state.selectionHashes, selectionHashes: state.selectionHashes,
fileList: state.fileList fileList: state.fileList
//fileSelectionNames: state.fileSelectionNames,
}; };
}; };
var mapDispatchToProps = function mapDispatchToProps(dispatch) { var mapDispatchToProps = function mapDispatchToProps(dispatch) {
return { return {
//changeFileSelection: (fileSelection) => dispatch({type: actionTypes.CHANGE_FILE_SELECTION, fileSelection}),
sendSelectionHashes: function sendSelectionHashes(selectionHashes) { sendSelectionHashes: function sendSelectionHashes(selectionHashes) {
return dispatch({ type: actionTypes.SELECTION_HASHES, selectionHashes: selectionHashes }); return dispatch({ type: actionTypes.SELECTION_HASHES, selectionHashes: selectionHashes });
} }

View File

@@ -53,10 +53,10 @@ type TorrentLocal struct {
MaxConnections int MaxConnections int
TorrentType string //magnet or .torrent file TorrentType string //magnet or .torrent file
TorrentFileName string TorrentFileName string
TorrentFile []byte //TODO store and reteive torrent file from here TorrentFile []byte
Label string //for labeling torrent files Label string
UploadedBytes int64 UploadedBytes int64
DownloadedBytes int64 //TODO not sure if needed since we should have the file which contains the bytes DownloadedBytes int64
UploadRatio string UploadRatio string
TorrentFilePriority []TorrentFilePriority TorrentFilePriority []TorrentFilePriority
} }