-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtransatlanticTorrentExpress.py
executable file
Β·287 lines (220 loc) Β· 8.62 KB
/
transatlanticTorrentExpress.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
#!/usr/bin/python3
import os, sys, math
import shutil
from subprocess import check_output, Popen, PIPE
from datetime import timedelta
from time import time
try:
from delugeClient import Deluge
except Exception:
print('Download delugeClient package using: pip3 install delugeClient-kevin')
sys.exit(1)
from logger import logger
from utils import getConfig, readAvgSpeedFromDisk, writeAvgSpeedToDisk, VIDEO_EXTENSIONS
LAST_TRANSFER_SPEED=readAvgSpeedFromDisk()
TRANSFER_SPEED_UNIT="Mb/s"
LAST_FILE_TRANSFER_SPEED=None
def parseFileListResponse(filesString):
if filesString == None:
return []
files = filesString.decode('utf-8').split('\n')
return list(filter(lambda x: len(x) > 0, files)) # remove any empty newline from list
def filesNotShared(remote, local):
c = set(remote.files) - set(local.files)
files = list(c)
if len(files) == 0:
return False
return list(filter(lambda file: not local.findFile(file), files))
class File():
def __init__(self, file, system):
self.name = file
self.system = system
self.size = self.fileSize()
self.sizeInBytes = self.fileSizeInBytes()
def fileSize(self):
filePath = self.system.buildFilePath(self)
cmd = "du -hs '{}'".format(filePath)
if self.system.remote:
cmd = 'ssh {}@{} "{}"'.format(self.system.user, self.system.host, cmd)
diskusageOutput = check_output(cmd, shell=True)
diskusageOutput = diskusageOutput.decode('utf-8').split('\t')
return diskusageOutput[0] + 'B'
def fileSizeInBytes(self, blockSize=1024):
fileSizeBytes = blockSize
try:
if self.size[-2] == 'G':
fileSizeBytes = float(self.size[:-2]) * 1024 * 1024 * 1024
elif self.size[-2] == 'M':
fileSizeBytes = float(self.size[:-2]) * 1024 * 1024
elif self.size[-2] == 'K':
fileSizeBytes = float(self.size[:-2]) * 1024
except:
logger.error('Filesize to float. Filesize:', es={'output': self.size})
return
return fileSizeBytes
@property
def telemetry(self):
return {
'filename': self.name,
'filesize': self.size,
'bytes': self.sizeInBytes
}
def __str__(self):
return str(self.name)
def __repr__(self):
return repr(self.name)
class System():
def __init__(self, path, host=None, user=None):
self.path = path
self.files = []
self.host = host
self.user = user
self.remote = host or user
def getFiles(self):
logger.debug('Getting files from path', es={'path': self.path})
cmd = "ls '{}'".format(self.path)
if self.remote:
cmd = 'ssh {}@{} {}'.format(self.user, self.host, cmd)
contents = check_output(cmd, shell=True)
files = parseFileListResponse(contents)
for file in files:
self.files.append(File(file, self))
logger.debug('Files found', es={'files': self.files})
return self.files
def findFile(self, file):
cmd = "find {} -type f -name '{}'".format(self.path, file.name)
if self.remote:
cmd = 'ssh {}@{} {}'.format(self.user, self.path, cmd)
fileMatch = check_output(cmd, shell=True)
return fileMatch != b''
def buildFilePath(self, file):
return os.path.join(self.path, file.name)
def rsyncFilePath(self, file):
filePath = self.buildFilePath(file)
if not self.remote:
return "'{}'".format(filePath)
return "{}@{}:'{}'".format(self.user, self.host, filePath)
class Transport():
def __init__(self, files, satelliteSystem, localSystem, downloadClient):
self.files = files
self.transferedFiles = []
self.satelliteSystem = satelliteSystem
self.localSystem = localSystem
self.avgTransferSpeed = LAST_TRANSFER_SPEED # in MegaBits / Mb
self.downloadClient = downloadClient
def setTransferSpeed(self, file, elapsedTransferTime):
elapsedTransferTime = math.ceil(elapsedTransferTime)
transferSpeed = math.ceil(file.sizeInBytes / 1000 / 1000 * 8 / elapsedTransferTime)
transferTime = str(timedelta(seconds=elapsedTransferTime))
esData = {
'filename': file.name,
'filesize': file.size,
'bytes': file.sizeInBytes,
'transferTime': transferTime,
'transferSpeed': transferSpeed,
'transferSpeedUnit': TRANSFER_SPEED_UNIT,
'seconds': elapsedTransferTime
}
logger.info('Transfer finished', es=esData)
self.avgTransferSpeed = (transferSpeed + self.avgTransferSpeed) / 2 if self.avgTransferSpeed else transferSpeed
writeAvgSpeedToDisk(self.avgTransferSpeed)
def ensureLocalParentFolder(self, file):
folderName, fileExtension = os.path.splitext(file.name)
if fileExtension not in VIDEO_EXTENSIONS:
return False
try:
folderedLocalPath = os.path.join(self.localSystem.path, folderName)
os.makedirs(folderedLocalPath)
logger.info("Created local parent folder for folder-less file", es=file.telemetry)
return folderName
except FileExistsError:
logger.warning("Error creating local parent folder, already exists", es=file.telemetry)
return folderName
except Exception as error:
msg = str(error)
logger.error("Unexpected error while creating local folder", es={**file.telemetry, 'error': msg})
logger.error(msg)
def estimateFileTransferTime(self, file):
fileSizeInMegabit = file.sizeInBytes / 1000 / 1000 * 8
estimatedTransferTimeInSeconds = math.floor(fileSizeInMegabit / self.avgTransferSpeed)
estimatedTransferTime = str(timedelta(seconds=estimatedTransferTimeInSeconds))
telemetry = {
**file.telemetry,
'seconds': estimatedTransferTimeInSeconds,
'transferTime': estimatedTransferTime,
'transferSpeed': self.avgTransferSpeed,
'transferSpeedUnit': TRANSFER_SPEED_UNIT
}
logger.info('Estimate transfer speed', es=telemetry)
def start(self):
for file in self.files:
try:
localFolder = self.localSystem.path
newParentFolder = self.ensureLocalParentFolder(file)
if newParentFolder:
localFolder = os.path.join(localFolder, newParentFolder)
transferStartTime = time()
logger.info('Transfer starting', es=file.telemetry)
if self.avgTransferSpeed is not None:
self.estimateFileTransferTime(file)
cmd = "rsync -ra {} '{}'".format(self.satelliteSystem.rsyncFilePath(file), localFolder)
rsyncProcess = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
stdout, stderr = rsyncProcess.communicate()
stdout = stdout.decode('utf-8')
stderr = stderr.decode('utf-8')
if stderr:
print(stderr)
logger.error('Rsync error', es={**file.telemetry, 'error':stderr})
continue
if len(stdout):
logger.debug('Rsync output', es={**file.telemetry, 'output': stdout})
elapsedTransferTime = time() - transferStartTime
self.setTransferSpeed(file, elapsedTransferTime)
if self.downloadClient.enabled is True:
self.downloadClient.remove(file)
except Exception as err:
logger.error('Unexpected error when transfering file', es={**file.telemetry, 'error': str(err)})
continue
class DownloadClient():
def __init__(self, enabled=True):
try:
self.enabled = enabled
self.deluge = None
if enabled is True:
self.deluge = Deluge()
except Exception as err:
logger.error("Unexpected error from deluge", es={**file.telemetry, 'error': str(err)})
def remove(self, file):
logger.info('Removing file from deluge', es=file.telemetry)
try:
response = self.deluge.removeByName(file.name, True)
if response is not None:
logger.info('Successfully removed file from deluge', es=file.telemetry)
return
raise Exception('Deluge item not found')
except Exception as err:
logger.error('Unexpected deluge error', es={**file.telemetry, 'error': str(err)})
def main():
config = getConfig()
host = config['SATELLITE']['host']
user = config['SATELLITE']['user']
remotePath = config['SATELLITE']['path']
remove = config['SATELLITE']['remove']
localPath = config['LOCAL']['path']
satelliteSystem = System(remotePath, host, user)
localSystem = System(localPath)
downloadClient = DownloadClient(remove == 'True')
satelliteSystem.getFiles()
localSystem.getFiles()
if len(satelliteSystem.files) == 0:
logger.debug('No remote files found')
return
newFiles = filesNotShared(satelliteSystem, localSystem)
if not newFiles:
logger.debug('No new files found to travel on the great transatlantic express')
return
logger.info('New files found to travel transatlantic express', es={'files': newFiles})
transport = Transport(newFiles, satelliteSystem, localSystem, downloadClient)
transport.start()
if __name__ == '__main__':
main()