Skip to content

Instantly share code, notes, and snippets.

@berkSahin
Created September 16, 2015 01:55
Show Gist options
  • Select an option

  • Save berkSahin/1fc30597c26820706090 to your computer and use it in GitHub Desktop.

Select an option

Save berkSahin/1fc30597c26820706090 to your computer and use it in GitHub Desktop.
from PySide import QtCore, QtGui
import os, requests, threading, time, StringIO
from requests_toolbelt import MultipartEncoder, MultipartEncoderMonitor
from threading import Thread
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(480, 232)
self.path = os.path.dirname(os.path.abspath(__file__))
self.chunk_size = 8192
self.progress_bar = QtGui.QProgressBar(Form)
self.progress_bar.setGeometry(QtCore.QRect(10, 50, 461, 23))
self.progress_bar.setProperty("value", 0)
self.progress_bar.setAlignment(QtCore.Qt.AlignCenter)
self.progress_bar.setTextVisible(True)
self.progress_bar.setInvertedAppearance(False)
self.progress_bar.setTextDirection(QtGui.QProgressBar.TopToBottom)
self.progress_bar.setObjectName("progress_bar")
self.download_button = QtGui.QPushButton(Form)
self.download_button.setGeometry(QtCore.QRect(400, 10, 75, 31))
self.download_button.setObjectName("download_button")
self.download_url = QtGui.QLineEdit(Form)
self.download_url.setGeometry(QtCore.QRect(10, 10, 381, 31))
self.download_url.setAlignment(QtCore.Qt.AlignCenter)
self.download_url.setObjectName("download_url")
self.download_url.setText("http://localhost/qwe.zip")
self.file_url = self.download_url.text()
self.download_info = QtGui.QLabel(Form)
self.download_info.setGeometry(QtCore.QRect(90, 80, 291, 20))
self.download_info.setText("")
self.download_info.setObjectName("download_info")
self.download_info.setAlignment(QtCore.Qt.AlignHCenter)
self.upload_path = QtGui.QLineEdit(Form)
self.upload_path.setGeometry(QtCore.QRect(10, 120, 301, 31))
self.upload_path.setAlignment(QtCore.Qt.AlignCenter)
self.upload_path.setObjectName("upload_path")
self.browse_button = QtGui.QPushButton(Form)
self.browse_button.setGeometry(QtCore.QRect(320, 120, 75, 31))
self.browse_button.setObjectName("browse_button")
self.upload_button = QtGui.QPushButton(Form)
self.upload_button.setGeometry(QtCore.QRect(400, 120, 75, 31))
self.upload_button.setObjectName("upload_button")
self.upload_info = QtGui.QLabel(Form)
self.upload_info.setGeometry(QtCore.QRect(10, 200, 461, 20))
self.upload_info.setLayoutDirection(QtCore.Qt.LeftToRight)
self.upload_info.setText("")
self.upload_info.setAlignment(QtCore.Qt.AlignCenter)
self.upload_info.setObjectName("upload_info")
self.progress_bar_2 = QtGui.QProgressBar(Form)
self.progress_bar_2.setGeometry(QtCore.QRect(10, 170, 461, 23))
self.progress_bar_2.setProperty("value", 0)
self.progress_bar_2.setAlignment(QtCore.Qt.AlignCenter)
self.progress_bar_2.setTextVisible(True)
self.progress_bar_2.setInvertedAppearance(False)
self.progress_bar_2.setTextDirection(QtGui.QProgressBar.TopToBottom)
self.progress_bar_2.setObjectName("progress_bar_2")
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
self.download_button.clicked.connect(lambda: self.__DownloadFileThread__())
self.upload_button.clicked.connect(lambda: self.__UploadFileThread__())
self.browse_button.clicked.connect(lambda: self.__OpenFileName__())
def retranslateUi(self, Form):
Form.setWindowTitle(QtGui.QApplication.translate("Form", "Form", None, QtGui.QApplication.UnicodeUTF8))
self.download_button.setText(QtGui.QApplication.translate("Form", "Download", None, QtGui.QApplication.UnicodeUTF8))
self.browse_button.setText(QtGui.QApplication.translate("Form", "Browse", None, QtGui.QApplication.UnicodeUTF8))
self.upload_button.setText(QtGui.QApplication.translate("Form", "Upload", None, QtGui.QApplication.UnicodeUTF8))
def __CheckInternet__(self):
try:
r = requests.get('http://www.google.com/', timeout=1)
return True
except requests.ConnectionError:
return False
def __FileExist__(self, file_name):
return os.path.exists(self.path + '/' + file_name)
def __CalculateSpeed__(self):
while 1:
self.speed = self.chunk_buffer/1024
self.chunk_buffer = 0
threading._sleep(1)
def __CalculateSpeedUpload__(self):
while 1:
self.upload_speed = self.chunk_buffer_upload/1024
self.chunk_buffer_upload = 0
threading._sleep(1)
def __DownloadFileThread__(self):
download_file_thread = Thread(target=self.__DownloadFile__)
download_file_thread.setDaemon(True)
download_file_thread.start()
def __UploadFileThread__(self):
upload_file_thread = Thread(target=self.__UploadFile__)
upload_file_thread.setDaemon(True)
upload_file_thread.start()
def __UploadFileCallBack(self,monitor):
# Your callback function
self.chunk_buffer_upload += 8192
percent = (monitor.bytes_read*100)/self.upload_total_size
if self.progress_bar_2.value() != percent:
self.progress_bar_2.setValue(percent)
self.upload_info.setText(str(monitor.bytes_read/1024)+ "KB Downloaded -- "+str(self.upload_speed)+" kbps")
if self.progress_bar_2.value() == 100:
self.upload_info.setText("Upload complate.")
def __OpenFileName__(self):
fileName, filtr = QtGui.QFileDialog.getOpenFileName(None,
"Select File",
"",
"All Files (*)", "", 0)
if fileName:
self.upload_info.setText(fileName)
self.upload_path.setText(fileName)
asd = fileName.split('/')[-2]
print str(fileName)
def __UploadFile__(self):
if self.__CheckInternet__():
if self.upload_path.text()!= "":
self.chunk_buffer_upload = 0
f = open(os.path.join(os.path.dirname(__file__), 'qwe.zip'), 'r')
self.upload_total_size=os.fstat(f.fileno()).st_size
f.close()
calculate_upload_speed_thread = Thread(target=self.__CalculateSpeedUpload__)
calculate_upload_speed_thread.setDaemon(True)
calculate_upload_speed_thread.start()
e = MultipartEncoder(
fields={'file': ('qwe.zip', open(str(self.upload_path.text()), 'rb'), 'text/plain')}
)
m = MultipartEncoderMonitor(e, self.__UploadFileCallBack)
r = requests.post('http://httpbin.org/post', data=m,
headers={'Content-Type': m.content_type})
else:
self.upload_info.setText("Please select file")
else:
self.upload_info.setText("No internet connection available.")
def __DownloadFile__(self):
if self.__CheckInternet__():
self.file_url = self.download_url.text()
self.local_filename = self.file_url.split('/')[-1]
self.chunk_buffer = 0
calculate_speed_thread = Thread(target=self.__CalculateSpeed__)
calculate_speed_thread.setDaemon(True)
calculate_speed_thread.start()
if self.local_filename == '':
self.download_info.setText("URL entered is incorrect!")
else:
self.r = requests.get(self.file_url, stream=True)
if not self.__FileExist__(self.local_filename):
if self.r.status_code == 200:
self.totalSize = int(self.r.headers['content-length']) / 1024
self.open_file = os.getcwd()
print os.path.dirname(__file__)
with open(os.path.join(os.path.dirname(__file__), self.local_filename), 'wb') as f:
for chunk in self.r.iter_content(chunk_size=self.chunk_size):
if chunk:
f.write(chunk)
self.chunk_buffer += self.chunk_size
f.flush()
self.percent = ((((os.fstat(f.fileno()).st_size)/1024)*100)/self.totalSize)
if self.progress_bar.value() != self.percent:
self.progress_bar.setValue(self.percent)
self.download_info.setText(str((os.fstat(f.fileno()).st_size)/1024)+ "KB Downloaded -- "+str(self.speed)+" kbps")
else:
self.download_info.setText("Connection Lost.")
break
if self.progress_bar.value() == 100:
self.download_info.setText("Download complate.")
return self.local_filename
else:
self.download_info.setText("Exists URL!")
else:
f = open(os.path.join(os.path.dirname(__file__), self.local_filename), 'r')
if int(self.r.headers['content-length']) == int(os.fstat(f.fileno()).st_size):
f.close()
self.download_info.setText("File already downloaded!")
else:
chunk_size = int(os.fstat(f.fileno()).st_size)/8192
resume_header = {'Range': 'bytes=%d-' % (chunk_size*8192) }
r = requests.get(self.file_url, headers=resume_header ,stream=True)
totalSize = int(r.headers['content-length']) / 1024
downloaded = (int(os.fstat(f.fileno()).st_size)/1024)
read_byte = 0
self.percent = (int(os.fstat(f.fileno()).st_size)/1024*100) / ((int(os.fstat(f.fileno()).st_size)/1024)+totalSize)
self.progress_bar.setValue(self.percent)
with open(os.path.join(os.path.dirname(__file__), self.local_filename), 'ab') as f:
for chunk in r.iter_content(chunk_size=self.chunk_size):
if chunk: # filter out keep-alive new chunks
f.write(chunk)
self.chunk_buffer += self.chunk_size
f.flush()
read_byte += self.chunk_size/1024
self.percent = (int(os.fstat(f.fileno()).st_size)/1024*100) / (downloaded+totalSize)
if self.progress_bar.value() != self.percent:
self.progress_bar.setValue(self.percent)
self.download_info.setText(str((os.fstat(f.fileno()).st_size)/1024)+ "KB Downloaded -- "+str(self.speed)+" kbps")
if totalSize-read_byte == 0:
break
if self.progress_bar.value() == 100:
self.download_info.setText("Download complate.")
return self.local_filename
else:
self.download_info.setText("No internet connection available.")
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
Form = QtGui.QWidget()
ui = Ui_Form()
ui.setupUi(Form)
Form.show()
sys.exit(app.exec_())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment