def schedule_created(self): scheduleFile = QFile("schedule.txt") if not scheduleFile.open(QIODevice.ReadWrite | QIODevice.Text): return scheduleFile.resize(0) out = QTextStream(scheduleFile) out << self.MedicationNameInput.text( ) << ", " << self.FrequencyInput.text() << " times " << str( self.comboBox_3.currentText( )) << ", for " << self.Duration_Input.text() << " " << str( self.durationDaysWeeks.currentText()) << "\n" if self.prescriptionNumber == 1: prescription = "Prescription 1" out << "Prescription 1" << "\n" elif self.prescriptionNumber == 2: prescription = "Prescription 2" out << "Prescription 2" << "\n" alarm_time = self.time_spin_1.time().toString("hh:mm") alarm_time12 = self.time_spin_1.time().toString("hh:mm AP") out << alarm_time12 schedule.clear('alarm') schedule.every().day.at(alarm_time).do( self.alarmOn, self.prescriptionNumber).tag('alarm') msgBox = QtWidgets.QMessageBox() msgBox.setText("Schedule created for " + prescription) t = threading.Timer(1.0, lambda: self.wait()) #prescription number t.start() msgBox.exec()
def importPrescription(self, info, times, times24): scheduleFile = QFile("schedule.txt") if not scheduleFile.open(QIODevice.ReadWrite | QIODevice.Text): return scheduleFile.resize(0) prescriptionText = re.sub( ' +', ' ', info[1] + ", " + info[2] + " times " + info[3] + ", for " + info[4] + " " + info[5]) self.medication_text.setText(prescriptionText) out = QTextStream(scheduleFile) out << prescriptionText << "\n" if info[0] == 1: self.prescription_label.setText("Prescription 1") out << "Prescription 1" << "\n" if info[0] == 2: self.prescription_label.setText("Prescription 2") out << "Prescription 2" << "\n" time_spins = { 1: self.time_spin_1, 2: self.time_spin_2, 3: self.time_spin_3, 4: self.time_spin_4, 5: self.time_spin_5, } schedule.clear('alarm') for i, alarm_time in enumerate(times): if alarm_time != '': out << times[i] << "\n" time_spins[i + 1].setText(times[i]) schedule.every().day.at(times24[i]).do(self.alarmOn, info[0]).tag('alarm') t = threading.Timer(1.0, lambda: self.wait()) t.start()
class HttpWindow(QDialog): def __init__(self, parent=None): super(HttpWindow, self).__init__(parent) self.url = QUrl() self.qnam = QNetworkAccessManager() self.reply = None self.outFile = None self.httpGetId = 0 self.httpRequestAborted = False self.urlLineEdit = QLineEdit('https://www.qt.io') urlLabel = QLabel("&URL:") urlLabel.setBuddy(self.urlLineEdit) self.statusLabel = QLabel( "Please enter the URL of a file you want to download.") self.statusLabel.setWordWrap(True) self.downloadButton = QPushButton("Download") self.downloadButton.setDefault(True) self.quitButton = QPushButton("Quit") self.quitButton.setAutoDefault(False) buttonBox = QDialogButtonBox() buttonBox.addButton(self.downloadButton, QDialogButtonBox.ActionRole) buttonBox.addButton(self.quitButton, QDialogButtonBox.RejectRole) self.progressDialog = QProgressDialog(self) self.urlLineEdit.textChanged.connect(self.enableDownloadButton) self.qnam.authenticationRequired.connect( self.slotAuthenticationRequired) self.qnam.sslErrors.connect(self.sslErrors) self.progressDialog.canceled.connect(self.cancelDownload) self.downloadButton.clicked.connect(self.downloadFile) self.quitButton.clicked.connect(self.close) topLayout = QHBoxLayout() topLayout.addWidget(urlLabel) topLayout.addWidget(self.urlLineEdit) mainLayout = QVBoxLayout() mainLayout.addLayout(topLayout) mainLayout.addWidget(self.statusLabel) mainLayout.addWidget(buttonBox) self.setLayout(mainLayout) self.setWindowTitle("HTTP") self.urlLineEdit.setFocus() def startRequest(self, url): self.reply = self.qnam.get(QNetworkRequest(url)) self.reply.finished.connect(self.httpFinished) self.reply.readyRead.connect(self.httpReadyRead) self.reply.downloadProgress.connect(self.updateDataReadProgress) def downloadFile(self): self.url = QUrl(self.urlLineEdit.text()) fileInfo = QFileInfo(self.url.path()) fileName = fileInfo.fileName() if not fileName: fileName = 'index.html' if QFile.exists(fileName): ret = QMessageBox.question(self, "HTTP", "There already exists a file called %s in the current " "directory. Overwrite?" % fileName, QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if ret == QMessageBox.No: return QFile.remove(fileName) self.outFile = QFile(fileName) if not self.outFile.open(QIODevice.WriteOnly): QMessageBox.information(self, "HTTP", "Unable to save the file %s: %s." % (fileName, self.outFile.errorString())) self.outFile = None return self.progressDialog.setWindowTitle("HTTP") self.progressDialog.setLabelText("Downloading %s." % fileName) self.downloadButton.setEnabled(False) self.httpRequestAborted = False self.startRequest(self.url) def cancelDownload(self): self.statusLabel.setText("Download canceled.") self.httpRequestAborted = True if self.reply is not None: self.reply.abort() self.downloadButton.setEnabled(True) def httpFinished(self): if self.httpRequestAborted: if self.outFile is not None: self.outFile.close() self.outFile.remove() self.outFile = None self.reply.deleteLater() self.reply = None self.progressDialog.hide() return self.progressDialog.hide() self.outFile.flush() self.outFile.close() redirectionTarget = self.reply.attribute(QNetworkRequest.RedirectionTargetAttribute) if self.reply.error(): self.outFile.remove() QMessageBox.information(self, "HTTP", "Download failed: %s." % self.reply.errorString()) self.downloadButton.setEnabled(True) elif redirectionTarget is not None: newUrl = self.url.resolved(redirectionTarget) ret = QMessageBox.question(self, "HTTP", "Redirect to %s?" % newUrl.toString(), QMessageBox.Yes | QMessageBox.No) if ret == QMessageBox.Yes: self.url = newUrl self.reply.deleteLater() self.reply = None self.outFile.open(QIODevice.WriteOnly) self.outFile.resize(0) self.startRequest(self.url) return else: fileName = QFileInfo(QUrl(self.urlLineEdit.text()).path()).fileName() self.statusLabel.setText("Downloaded %s to %s." % (fileName, QDir.currentPath())) self.downloadButton.setEnabled(True) self.reply.deleteLater() self.reply = None self.outFile = None def httpReadyRead(self): if self.outFile is not None: self.outFile.write(self.reply.readAll()) def updateDataReadProgress(self, bytesRead, totalBytes): if self.httpRequestAborted: return self.progressDialog.setMaximum(totalBytes) self.progressDialog.setValue(bytesRead) def enableDownloadButton(self): self.downloadButton.setEnabled(self.urlLineEdit.text() != '') def slotAuthenticationRequired(self, authenticator): import os from PyQt5 import uic ui = os.path.join(os.path.dirname(__file__), 'authenticationdialog.ui') dlg = uic.loadUi(ui) dlg.adjustSize() dlg.siteDescription.setText("%s at %s" % (authenticator.realm(), self.url.host())) dlg.userEdit.setText(self.url.userName()) dlg.passwordEdit.setText(self.url.password()) if dlg.exec_() == QDialog.Accepted: authenticator.setUser(dlg.userEdit.text()) authenticator.setPassword(dlg.passwordEdit.text()) def sslErrors(self, reply, errors): errorString = ", ".join([str(error.errorString()) for error in errors]) ret = QMessageBox.warning(self, "HTTP Example", "One or more SSL errors has occurred: %s" % errorString, QMessageBox.Ignore | QMessageBox.Abort) if ret == QMessageBox.Ignore: self.reply.ignoreSslErrors()
class CustomListItem(QWidget): def __init__(self, parent=None): super(CustomListItem, self).__init__(parent) self.iconLabel = QLabel() pixmap = QPixmap(":/images/icons/audio.png") self.iconLabel.setPixmap(pixmap) self.nameLabel = QLabel() self.nameLabel.setStyleSheet("font-size:17px; font-weight:bold") self.speedLabel = QLabel() self.speedLabel.setAlignment(Qt.AlignRight | Qt.AlignTrailing | Qt.AlignVCenter) self.speedLabel.setStyleSheet("font-size:13px;") self.statusLabel = QLabel() self.statusLabel.setStyleSheet("font-size:14px; color:green") self.progressBar = QProgressBar() self.progressBar.setFormat("%%p") self.vLayout = QVBoxLayout() self.hLayout = QHBoxLayout() self.hLayout2 = QHBoxLayout() self.hLayout2.addWidget(self.nameLabel) self.hLayout2.addWidget(self.speedLabel) self.vLayout.addLayout(self.hLayout2) self.hLayout3 = QHBoxLayout() self.hLayout3.addWidget(self.statusLabel) self.hLayout3.addWidget(self.progressBar) self.vLayout.addLayout(self.hLayout3) self.hLayout.addWidget(self.iconLabel, 0) self.hLayout.addLayout(self.vLayout, 1) self.setLayout(self.hLayout) self.manager = QNetworkAccessManager(self) self.Time = time.time() self.Value = 0 def startDownload(self, qurl): self.url = qurl fileInfo = QFileInfo(self.url.path()) fileName = fileInfo.fileName() filePath = os.join(QDir.homePath(), fileName) if QFile.exists(filePath): QFile.remove(filePath) self.audioFile = QFile(filePath) self.audioFile.open(QIODevice.WriteOnly) self.nameLabel.setText(fileName) self.statusLabel.setText(self.tr("Downloading...")) self.request = QNetworkRequest(qurl) self.request.setRawHeader("User-Agent", "Domestic Browser 1.0") self.reply = self.manager.get(self.request) self.reply.downloadProgress.connect(self.setProgress) self.reply.readyRead.connect(self.fileReadyRead) self.reply.finished.connect(self.finishDownload) def fileReadyRead(self): self.audioFile.write(self.reply.readAll()) def setProgress(self, value, max): self.progressBar.setMaximum(max) self.progressBar.setValue(value) self.elapsed_time(value, max) self.Time = time.time() self.Value = value def elapsed_time(self, value, max): ptime = time.time() - self.Time length = int(value - self.Value) speed = (length // ptime) // 1024 # KB self.speedLabel.setText("{} kb - {} kb".format(str(speed), max // 1024)) def finishDownload(self): redirectionTarget = self.reply.attribute( QNetworkRequest.RedirectionTargetAttribute) if redirectionTarget is not None: newUrl = self.url.resolved(redirectionTarget) self.reply.deleteLater() self.audioFile.open(QIODevice.WriteOnly) self.audioFile.resize(0) self.startDownload(newUrl) return else: self.audioFile.flush() self.audioFile.close() self.statusLabel.setText(self.tr("Downloaded."))
class updateV2ray(QObject): downloadFinish = pyqtSignal() def __init__(self, v2rayapi=False, url=False, checkDownloadInfo=False, downloadV2raycore=False): super().__init__() self.downloadURL = url self.reply = None self.outFile = None self.fileName = None self.httpRequestAborted = False self.v2rayAPI = v2rayapi self.v2raycoreAPIURL = QUrl( r"""https://api.github.com/repos/v2ray/v2ray-core/releases/latest""" ) Qt.Everyday = 8 self.downloadPath = False self.qnam = QNetworkAccessManager() self.startV2ray = False self.stopV2ray = False self.translate = QCoreApplication.translate self.msgBox = QMessageBox() self.fly = QApplication.desktop().screen().rect().center( ) - self.msgBox.rect().center() self.silentInstall = False self.installOption = "auto" if (self.v2rayAPI and self.downloadURL and checkDownloadInfo): self.getV2raycoreInfoFromGithub() elif (self.v2rayAPI and self.downloadURL and downloadV2raycore): self.downloadV2raycore() else: pass def getv2raycoreAPIURL(self): return self.v2raycoreAPIURL def enableSilentInstall(self): self.silentInstall = True def downloadV2raycore(self, url=False): if (url): self.downloadURL = url fileInfo = QFileInfo(self.downloadURL.path()) self.fileName = fileName = fileInfo.fileName() if not fileName: fileName = "v2ray.zip" if QFile.exists(fileName): QFile.remove(fileName) self.outFile = QFile(fileName) if not self.outFile.open(QIODevice.WriteOnly): if (not self.silentInstall): self.msgBox.information( QDialog().move(self.fly), self.translate("updateV2ray", "Download {}").format(fileName), self.translate("updateV2ray", "Unable to save the file {}: {}.").format( fileName, self.outFile.errorString())) self.outFile = None return self.httpRequestAborted = False if (not self.silentInstall): self.progressDialog = QProgressDialog() self.progressDialog.setLabelText( self.translate("updateV2ray", "v2ray-core is downloading...")) self.progressDialog.canceled.connect(self.cancelDownload) self.startRequest(self.downloadURL) def startRequest(self, url): self.reply = self.qnam.get(QNetworkRequest(url)) self.reply.finished.connect(self.httpFinished) self.reply.readyRead.connect(self.httpReadyRead) if (not self.silentInstall): self.reply.downloadProgress.connect(self.updateDataReadProgress) def httpReadyRead(self): if self.outFile is not None: self.outFile.write(self.reply.readAll()) def updateDataReadProgress(self, bytesRead, totalBytes): if self.httpRequestAborted: return self.progressDialog.setMaximum(totalBytes) self.progressDialog.setValue(bytesRead) def cancelDownload(self): self.httpRequestAborted = True if self.reply is not None: self.reply.abort() if QFile.exists(self.fileName): QFile.remove(self.fileName) def httpFinished(self): if self.httpRequestAborted: if self.outFile is not None: self.outFile.close() self.outFile.remove() del self.outFile self.reply.deleteLater() self.reply = None if not self.silentInstall: self.progressDialog.hide() return if not self.silentInstall: self.progressDialog.hide() self.outFile.flush() self.outFile.close() redirectionTarget = self.reply.attribute( QNetworkRequest.RedirectionTargetAttribute) if self.reply.error(): self.outFile.remove() if not self.silentInstall: self.msgBox.information( QDialog().move(self.fly), self.translate("updateV2ray", "Download"), self.translate("updateV2ray", "Download failed: {}.").format( self.reply.errorString())) self.progressDialog.close() elif redirectionTarget is not None: newUrl = self.downloadURL.resolved(redirectionTarget) self.downloadURL = newUrl self.reply.deleteLater() self.reply = None self.outFile.open(QIODevice.WriteOnly) self.outFile.resize(0) self.startRequest(self.downloadURL) return else: self.reply.deleteLater() self.reply = None self.outFile = None self.downloadFinish.emit() def getV2raycoreInfoFromGithub(self, url=False): if (url): self.downloadURL = url self.reqV2raycore = QNetworkRequest(self.downloadURL) self.qnam.finished.connect(self.handleResponse) self.qnam.get(self.reqV2raycore) def handleResponse(self, reply): """ Read all API from https://api.github.com/repos/v2ray/v2ray-core/releases/latest """ errorCode = reply.error() if (self.v2rayAPI): if errorCode == QNetworkReply.NoError: self.v2rayAPI.setv2raycoreAPI(str(reply.readAll(), "utf-8")) self.createDownloadINFO() else: self.v2rayAPI.setV2raycoreErrorString(reply.errorString()) self.v2rayAPI.setv2raycoreAPI(False) self.v2rayAPI.checkDownloadInfo.emit() def createDownloadINFO(self): api = None try: api = json.loads(self.v2rayAPI.getv2raycoreAPI()) except Exception: api = None if (api): try: # this code for get Latest release Download Files' path for i in api["assets"]: self.v2rayAPI.setdownloadINFO(i["name"], i["browser_download_url"]) self.v2rayAPI.setV2raycoreVersion(api["tag_name"]) except Exception: pass def setautoupdateProxy(self, proxy): self.proxy = QNetworkProxy() protocol = copy.deepcopy(proxy[0]) proxyhostName = copy.deepcopy(proxy[1]) proxyPort = copy.deepcopy(proxy[2]) self.proxy.setType(protocol) self.proxy.setHostName(proxyhostName) self.proxy.setPort(int(proxyPort)) self.proxy.setApplicationProxy(self.proxy) def getcurrentTime(self): currentTime = False if updateV2rayQTime().isMorning(): currentTime = 1 elif updateV2rayQTime().isAfternoon(): currentTime = 2 elif updateV2rayQTime().isEvening(): currentTime = 3 elif updateV2rayQTime().isNight(): currentTime = 4 return currentTime def checkDonwloadinfo(self): self.getV2raycoreInfoFromGithub(self.v2raycoreAPIURL) self.v2rayAPI.checkDownloadInfo.connect( lambda: self.getdownloadPath(self.usingVersion)) def getdownloadPath(self, usingVersion): download = False if (self.v2rayAPI.getv2raycoreAPI()): self.downloadPath = False for file, filePath in self.v2rayAPI.getdownloadINFO().items(): if self.downloadFile == file: self.downloadPath = copy.deepcopy(filePath) break self.latestVersion = copy.deepcopy( self.v2rayAPI.getV2raycoreVersion()) if not usingVersion: download = True elif self.checkNewestfileDownload(usingVersion, self.latestVersion): download = True if (download and self.downloadPath): self.downloadV2rayCoreNow(self.downloadFile, self.downloadPath, self.latestVersion) def downloadV2rayCoreNow(self, downloadFile=False, downloadPath=False, latestVersion=False, bridgetreasureChest=False, bridgeSingal=False): if not downloadPath or not latestVersion or not downloadFile: return False if (bridgetreasureChest): self.bridgetreasureChest = bridgetreasureChest if (bridgeSingal): self.startV2ray = bridgeSingal[0] self.stopV2ray = bridgeSingal[1] self.checkdownloadFileExists(downloadPath) self.downloadV2raycore(QUrl(downloadPath)) self.downloadFinish.connect( lambda: self.installDownloadFile(downloadFile, latestVersion)) def installDownloadFile(self, downloadFile, latestVersion): if self.installOption == "manual": self.msgBox.information( QDialog().move(self.fly), self.translate("updateV2ray", "update"), self.translate( "updateV2ray", "The newest v2ray-core: {} .\nversion: {} was downloaded,\nPlease check." ).format(downloadFile, latestVersion)) elif self.installOption == "auto": if self.unzipdownloadFile( downloadFile, latestVersion) and (not self.silentInstall): self.msgBox.information( QDialog().move(self.fly), self.translate("updateV2ray", "update"), self.translate( "updateV2ray", "The newest v2ray-core: {} .\n version: {} was installed. \nPlease restart V2ray-shell" ).format(downloadFile, latestVersion)) def checkdownloadFileExists(self, downloadPath): if (not downloadPath or not downloadPath): return False filePath = QUrl(downloadPath) fileInfo = QFileInfo(filePath.path()) fileName = fileInfo.fileName() if QFile.exists(fileName): QFile.remove(fileName) return True def unzipdownloadFile(self, downladFile, latestVersion): import zipfile fileInfo = None self.newV2rayPath = None if QFile.exists(downladFile): fileInfo = QFileInfo(QFile(downladFile)) else: return False def checkFilesize(file): v2rayFile = QFile(file.absoluteFilePath()) # check file size need open the file v2rayFile.open(QIODevice.ReadOnly | QIODevice.Text) if v2rayFile.error() == v2rayFile.NoError: if v2rayFile.size() > 600000: v2rayFile.close() return True else: v2rayFile.close() return False if (fileInfo): with zipfile.ZipFile(fileInfo.absoluteFilePath(), "r") as zip_ref: for i in zip_ref.namelist(): absoluteFilePath = fileInfo.absolutePath( ) + QDir.separator() + i if re.search("/v2ray.exe$", absoluteFilePath): # ## windows self.newV2rayPath = None self.newV2rayPath = QFileInfo(QFile(absoluteFilePath)) if self.newV2rayPath and checkFilesize( self.newV2rayPath): break if re.search("/v2ray$", absoluteFilePath): # ## other self.newV2rayPath = None self.newV2rayPath = QFileInfo(QFile(absoluteFilePath)) if self.newV2rayPath and checkFilesize( self.newV2rayPath): break try: zip_ref.extractall(fileInfo.absolutePath()) except PermissionError: return if sys.platform.startswith('win'): pass else: os.chmod(self.newV2rayPath.absoluteFilePath(), 0o755) os.chmod( self.newV2rayPath.absoluteFilePath()[:-5] + "v2ctl", 0o755) if self.newV2rayPath: if (self.stopV2ray): self.stopV2ray.emit() self.bridgetreasureChest.setV2raycoreFilePath( self.newV2rayPath.absoluteFilePath()) self.bridgetreasureChest.setV2raycoreVersion(latestVersion) self.bridgetreasureChest.save.emit() if (self.startV2ray): self.startV2ray.emit() return True else: return False def checkNewestfileDownload(self, usingVersion, latestVersion): if not usingVersion: return True v = re.search("v", str(usingVersion)) if (v): usingVersion = usingVersion[1:].split('.') else: return False del v v = re.search("v", str(latestVersion)) if (v): latestVersion = latestVersion[1:].split('.') else: return False latestMilestone, latestRelease = int(latestVersion[0]), int( latestVersion[1]) usingMilestone, usingRelease = int(usingVersion[0]), int( usingVersion[1]) if (latestMilestone > usingMilestone): return True if ((latestMilestone == usingMilestone) and (latestRelease > usingRelease)): return True return False def partsoftheDay(self): """ Morning : 05:00 to 12:00 (5, 6, 7, 8, 9, 10, 11, 12) Afternoon : 13:00 to 17:00 (13, 14, 15, 16, 17) Evening : 18:00 to 21:00 (18, 19, 20, 21) Night : 22:00 to 04:00 (22, 23, 0, 1, 2, 3, 4) """ return (self.translate("updateV2ray", "Morning"), self.translate("updateV2ray", "Afternoon"), self.translate("updateV2ray", "Evening"), self.translate("updateV2ray", "Night"))