def save(self, content, path=None): """ Write a temporary file with .tnj extension and copy it over the original one. .nsf = Ninja Swap File # FIXME: Where to locate addExtension, does not fit here """ new_path = False if path: self.attach_to_path(path) new_path = True save_path = self._file_path if not save_path: raise NinjaNoFileNameException("I am asked to write a " "file but no one told me where") swap_save_path = "%s.nsp" % save_path # If we have a file system watcher, remove the file path # from its watch list until we are done making changes. if self.__watcher is not None: self.__watcher.removePath(save_path) flags = QIODevice.WriteOnly | QIODevice.Truncate f = QFile(swap_save_path) if settings.use_platform_specific_eol(): flags |= QIODevice.Text if not f.open(flags): raise NinjaIOException(f.errorString()) stream = QTextStream(f) encoding = get_file_encoding(content) if encoding: stream.setCodec(encoding) encoded_stream = stream.codec().fromUnicode(content) f.write(encoded_stream) f.flush() f.close() # SIGNAL: Will save (temp, definitive) to warn folder to do something self.willSave.emit(swap_save_path, save_path) self.__mtime = os.path.getmtime(swap_save_path) shutil.move(swap_save_path, save_path) self.reset_state() # If we have a file system watcher, add the saved path back # to its watch list, otherwise create a watcher and start # watching if self.__watcher is not None: if new_path: # FIXME: what? # self.__watcher.removePath(self.__watcher.files()[0]) self.__watcher.addPath(self._file_path) else: self.__watcher.addPath(save_path) else: self.start_watching() return self
def save(self, content, path=None): """ Write a temporary file with .tnj extension and copy it over the original one. .nsf = Ninja Swap File # FIXME: Where to locate addExtension, does not fit here """ new_path = False if path: self.attach_to_path(path) new_path = True save_path = self._file_path if not save_path: raise NinjaNoFileNameException("I am asked to write a " "file but no one told me where") swap_save_path = "%s.nsp" % save_path # If we have a file system watcher, remove the file path # from its watch list until we are done making changes. if self.__watcher is not None: self.__watcher.removePath(save_path) flags = QIODevice.WriteOnly | QIODevice.Truncate f = QFile(swap_save_path) if settings.use_platform_specific_eol(): flags |= QIODevice.Text if not f.open(flags): raise NinjaIOException(f.errorString()) stream = QTextStream(f) encoding = get_file_encoding(content) if encoding: stream.setCodec(encoding) encoded_stream = stream.codec().fromUnicode(content) f.write(encoded_stream) f.flush() f.close() # SIGNAL: Will save (temp, definitive) to warn folder to do something self.willSave.emit(swap_save_path, save_path) self.__mtime = os.path.getmtime(swap_save_path) shutil.move(swap_save_path, save_path) self.reset_state() # If we have a file system watcher, add the saved path back # to its watch list, otherwise create a watcher and start # watching if self.__watcher is not None: if new_path: # self.__watcher.removePath(self.__watcher.files()[0]) self.__watcher.addPath(self._file_path) else: self.__watcher.addPath(save_path) else: self.start_watching() return self
def _fileSave(self): file = QFile(self.file_path) if file.open(QIODevice.WriteOnly | QIODevice.Text): file.write(bytes(self.text(), encoding="utf-8")) file.flush() file.close() self.saveState = True
def save(self, data): f = QFile(self.savePath) f.open(QIODevice.WriteOnly) data = data.readAll() f.write(data) f.flush() f.close() self.downloaded.emit(self.savePath)
def saveWorkspace(self): """ Saves the current workspace as is. Saves the trees and all of the nodes (and node data). Does not save windows or window options, but does save the structure information. """ sel = QFileDialog.getSaveFileName( parent=self, caption="Save Workspace", directory=QDir.homePath(), filter="Linnaeo Workspace (*.lno);;Any (*)") filename = sel[0] if filename: if filename[-4:] != ".lno": filename = str(filename + ".lno") file = QFile(filename) file.open(QIODevice.WriteOnly) out = QDataStream(file) self.mainLogger.debug("Beginning file save") out.writeQVariantHash(self.sequences) out.writeQVariantList(self.titles) out.writeUInt32(self.windex) ##################################### # Sequence View ### self.mainLogger.debug("SEQUENCE TREE") self.mainLogger.debug("Children count: %s" % self.bioModel.invisibleRootItem().rowCount()) out.writeUInt32(self.bioModel.invisibleRootItem().rowCount()) for node in utilities.iterTreeView( self.bioModel.invisibleRootItem()): self.mainLogger.debug("Node: %s" % str(node.text())) node.write(out) out.writeUInt32(node.rowCount()) ##################################### # Alignment View # Does not save any metadata! Only the two sequences # So I can't save window options at the moment. # TODO: Consider adding "window modes" to the node. self.mainLogger.debug("ALIGNMENT TREE") self.mainLogger.debug("Children count: %s" % self.bioModel.invisibleRootItem().rowCount()) out.writeUInt32(self.projectModel.invisibleRootItem().rowCount()) for node in utilities.iterTreeView( self.projectModel.invisibleRootItem()): self.mainLogger.debug("Node: %s" % str(node.text())) node.write(out) out.writeUInt32(node.rowCount()) self.mainLogger.debug("Save complete") file.flush() file.close() del sel, filename, file, out, node return True else: self.mainLogger.debug("No filename chosen; canceling") del sel return False
def _autosave(self): if self._neditable.editor.is_modified: flags = QIODevice.WriteOnly f = QFile(self.filename()) if not f.open(flags): raise IOError(f.errorString()) content = self._neditable.editor.text stream = QTextStream(f) encoded_stream = stream.codec().fromUnicode(content) f.write(encoded_stream) f.flush() f.close()
class StreamHandler(QObject): commandReceived = pyqtSignal(str) def __init__(self, parent = None): QObject.__init__(self, parent) def openInput(self): self.stdin = QFile() self.stdin.open(0, QFile.ReadOnly) def openOutput(self): self.stdout = QFile() self.stdout.open(1, QFile.WriteOnly) def handleInput(self): while self.stdin.isOpen(): command = str(self.stdin.readLine(), "utf8") if not command: break self.commandReceived.emit(command.strip()) # This shouldn't be needed, but QFile can get into a state where # readLine no longer blocks. print("Input stream closed.") @pyqtSlot(QByteArray) def handleOutput(self, data): while self.stdout.isOpen() and data.size() > 0: written = self.stdout.write(data) data = data.right(data.size() - written) @pyqtSlot(str) def handleOutput(self, data): data = QByteArray(bytes(data, "utf8")) while self.stdout.isOpen() and data.size() > 0: written = self.stdout.write(data) self.stdout.flush() data = data.right(data.size() - written)
def tofile(self, path): """Write the bloom filter to file object `f'. Underlying bits are written as machine values. This is much more space efficient than pickling the object.""" # f.write(pack(self.FILE_FMT, self.error_rate, self.num_slices, # self.bits_per_slice, self.capacity, self.count)) # f.write(self.bitarray.bits) f = QFile(path) if f.open(QIODevice.WriteOnly): out = QDataStream(f) out.writeBytes(self.FILE_FMT) out.writeFloat(self.error_rate) out.writeInt(self.num_slices) out.writeInt(self.bits_per_slice) out.writeInt(self.capacity) out.writeInt(self.count) out << self.bitarray f.flush() f.close()
class NSwapFile(QObject): """ In case Ninja-IDE crash, this can be used to recover the lost data. When the user begins to edit an existing file on the disk, this object creates a swap file and activates a timer that will execute a function, that will update that swap file as soon as the timeout ends (by default, is 15 seconds). The swap file is deleted when the original file is saved or closed. When system or Ninja crash, the swap file exists on disk and Ninja will used to recover the lost data. """ canBeRecovered = pyqtSignal() def __init__(self, neditable): QObject.__init__(self) self._neditable = neditable self.__swap_file = QFile() self.__stream = QTextStream() # Activate timer when user typing self.__timer = QTimer() self.__timer.setSingleShot(True) self.__timer.timeout.connect(self._finish_typing) self._neditable.fileLoaded.connect(self._file_loaded) self._neditable.fileSaved.connect(self._file_saved) self.init(tracking=True) def init(self, tracking): if tracking: self._neditable.editor.textChanged.connect(self._start_typing) self._neditable.fileClosing.connect(self._file_closed) else: self._neditable.editor.textChanged.disconnect(self._start_typing) self._neditable.fileClosing.disconnect(self._file_closed) def _file_closed(self): """Editor was closed normally, now remove swap file""" self.__remove() def _file_saved(self): """If file is saved, remove swap file""" # Remove old swap file and set the name for the new swap file self.__remove() self.__update_filename() def __remove(self): """Remove swap file""" if self.__swap_file.fileName() and self.__swap_file.exists(): self.__stream.setDevice(None) self.__swap_file.close() self.__swap_file.remove() def _file_loaded(self): """This slot is executed when a file is loaded on the editor and look for swap file, if exists then can be recover""" self.__update_filename() if self.__swap_file.exists(): # In recovery process can't edit self._neditable.editor.setReadOnly(True) # Ok, can be recover self.canBeRecovered.emit() def __update_filename(self): # First clear filename self.__swap_file.setFileName("") # Get new path filename = self.filename() self.__swap_file.setFileName(filename) def _start_typing(self): # Skip if editor is not modified if not self._neditable.editor.is_modified: return # No swap file, no work if not self.__swap_file.fileName(): return # Create the file if not self.__swap_file.exists(): self.__swap_file.open(QIODevice.WriteOnly) permissions = QFileDevice.ReadOwner | QFileDevice.WriteOwner self.__swap_file.setPermissions(permissions) self.__stream.setDevice(self.__swap_file) if self.__timer.isActive(): self.__timer.stop() # Write swap file to the disk every 10 seconds by default self.__timer.start(settings.SWAP_FILE_INTERVAL * 1000) def _finish_typing(self): if not self.__swap_file.isOpen(): return logger.debug("Now write the swap file...") text = self._neditable.editor.text self.__swap_file.write(text.encode()) self.__swap_file.flush() def filename(self): """Returns the filename for swap file""" path, name = os.path.split( os.path.join(SWAP_PATH, self._neditable.nfile.file_name)) filename = os.path.join(path, "%s.ninja-swap" % name) return filename def recover(self): self._neditable.editor.setReadOnly(False) # Disconnect signals self.init(tracking=False) self.__stream.setDevice(self.__swap_file) if not self.__swap_file.open(QIODevice.ReadOnly): logger.warning("Can't open swap file") return # Ok data = [] append = data.append while not self.__stream.atEnd(): line = self.__stream.readLine() append(line) # Set data in the editor self._neditable.editor.text = "\n".join(data) self._neditable.document.setModified(True) # Close swap file self.__stream.setDevice(None) self.__swap_file.close() # Reconnect signals self.init(tracking=True) def discard(self): self._neditable.editor.setReadOnly(False) # Remove swap file self.__remove()
def ConverttxtToPack(in1, out1, default_ver='3.13', default_type='standard'): dsoIn = QFile(in1) if dsoIn.open(QIODevice.ReadOnly | QIODevice.Text) is False: return dsoOut = QFile(out1) if dsoOut.open(QIODevice.WriteOnly) is False: return totalRecords = 0 while (dsoIn.atEnd() is False): dsoIn.readLine() totalRecords += 1 dsoIn.seek(0) dsoOutStream = QDataStream(dsoOut) dsoOutStream.setVersion(QDataStream.Qt_5_2) readOk = 0 addedHead = False while (dsoIn.atEnd() is False): record = str(dsoIn.readLine(), encoding='utf-8') vp = re.match("^.*ersion\s+([\d\.]+)\s+(\w+)", record) if vp: print(vp.group(1), vp.group(2)) dsoOutStream.writeQString(vp.group(1)) dsoOutStream.writeQString(vp.group(2)) addedHead = True if (record.startswith("//") or record.startswith("#")): totalRecords -= 1 continue # write when could not get label from txt if not addedHead: dsoOutStream.writeQString(default_ver) dsoOutStream.writeQString(default_type) addedHead = True lis = record.split('\t') if 1: id = int(lis[0] if lis[0] != "" else 0) ra = float((lis[1]).strip()) dec = float((lis[2]).strip()) bMag = float(lis[3]) vMag = float(lis[4]) oType = (lis[5]).strip() # mType = (lis[6]).strip() # majorAxisSize = float(lis[7]) minorAxisSize = float(lis[8]) orientationAngle = int(float(lis[9]) if float(lis[9]) != "" else 0) z = float(lis[10]) zErr = float(lis[11]) plx = float(lis[12]) plxErr = float(lis[13]) dist = float(lis[14]) distErr = float(lis[15]) NGC = int(lis[16] if lis[16] != "" else 0) IC = int(lis[17] if lis[17] != "" else 0) M = int(lis[18] if lis[18] != "" else 0) C = int(lis[19] if lis[19] != "" else 0) B = int(lis[20] if lis[20] != "" else 0) Sh2 = int(lis[21] if lis[21] != "" else 0) VdB = int(lis[22] if lis[22] != "" else 0) RCW = int(lis[23] if lis[23] != "" else 0) LDN = int(lis[24] if lis[24] != "" else 0) LBN = int(lis[25] if lis[25] != "" else 0) Cr = int(lis[26] if lis[26] != "" else 0) Mel = int(lis[27] if lis[27] != "" else 0) PGC = int(lis[28] if lis[28] != "" else 0) UGC = int(lis[29] if lis[29] != "" else 0) Ced = (lis[30]).strip() # Arp = int(lis[31] if lis[31] != "" else 0) VV = int(lis[32] if lis[32] != "" else 0) PK = (lis[33]).strip() # PNG = (lis[34]).strip() # SNRG = (lis[35]).strip() # ACO = (lis[36]).strip() # HCG = (lis[37]).strip() # ESO = (lis[38]).strip() # VdBH = (lis[39]).strip() # DWB = int(lis[40] if lis[40] != "" else 0) Tr = int(lis[41] if lis[41] != "" else 0) St = int(lis[42] if lis[42] != "" else 0) Ru = int(lis[43] if lis[43] != "" else 0) VdBHa = int(lis[44] if lis[44] != "" else 0) raRad = float(ra) * math.pi / 180 decRad = float(dec) * math.pi / 180 majorAxisSize /= 60 minorAxisSize /= 60 if (bMag <= 0): bMag = 99 if (vMag <= 0): vMag = 99 if oType.upper() in otypedic: nType = otypedic[oType.upper()] else: nType = 36 readOk += 1 dsoOutStream.writeInt(id) dsoOutStream.writeFloat(raRad) dsoOutStream.writeFloat(decRad) dsoOutStream.writeFloat(bMag) dsoOutStream.writeFloat(vMag) dsoOutStream.writeInt(nType) dsoOutStream.writeQString(mType) dsoOutStream.writeFloat(majorAxisSize) dsoOutStream.writeFloat(minorAxisSize) dsoOutStream.writeInt(orientationAngle) dsoOutStream.writeFloat(z) dsoOutStream.writeFloat(zErr) dsoOutStream.writeFloat(plx) dsoOutStream.writeFloat(plxErr) dsoOutStream.writeFloat(dist) dsoOutStream.writeFloat(distErr) dsoOutStream.writeInt(NGC) dsoOutStream.writeInt(IC) dsoOutStream.writeInt(M) dsoOutStream.writeInt(C) dsoOutStream.writeInt(B) dsoOutStream.writeInt(Sh2) dsoOutStream.writeInt(VdB) dsoOutStream.writeInt(RCW) dsoOutStream.writeInt(LDN) dsoOutStream.writeInt(LBN) dsoOutStream.writeInt(Cr) dsoOutStream.writeInt(Mel) dsoOutStream.writeInt(PGC) dsoOutStream.writeInt(UGC) dsoOutStream.writeQString(Ced) dsoOutStream.writeInt(Arp) dsoOutStream.writeInt(VV) dsoOutStream.writeQString(PK) dsoOutStream.writeQString(PNG) dsoOutStream.writeQString(SNRG) dsoOutStream.writeQString(ACO) dsoOutStream.writeQString(HCG) dsoOutStream.writeQString(ESO) dsoOutStream.writeQString(VdBH) dsoOutStream.writeInt(DWB) dsoOutStream.writeInt(Tr) dsoOutStream.writeInt(St) dsoOutStream.writeInt(Ru) dsoOutStream.writeInt(VdBHa) dsoIn.close() dsoOut.flush() dsoOut.close() return
class CardPDFWriter: RESOLUTION = 300 # 300dpi @staticmethod def mm2pix(args): return [x * (CardPDFWriter.RESOLUTION / 25.4) for x in args] def __init__(self, file_name, card_format, paper_format, separation=[0.8, 0.8]): self.cardFormat = self.mm2pix(card_format) self.paperFormat = self.mm2pix(paper_format) self.separation = self.mm2pix(separation) self.paperFormatMM = paper_format self.file = QFile(str(file_name)) self.file.open(QIODevice.WriteOnly) self.writer = QPdfWriter(self.file) self.writer.setResolution(self.RESOLUTION) self.writer.setPageSizeMM(QSizeF(*self.paperFormatMM)) self.writer.setPageMargins(QMarginsF(0, 0, 0, 0)) self.painter = QPainter(self.writer) self.pen = QPen() self.pen.setWidth(self.mm2pix([1])[0]) self.painter.setPen(self.pen) self.bleeding = [0, 0] self.bleeding[0] = (self.paperFormat[0] % int(self.cardFormat[0] + self.separation[0])) / 2 self.bleeding[1] = (self.paperFormat[1] % int(self.cardFormat[1] + self.separation[1])) / 2 self.cursor = self.bleeding[:] self._setupPage() def _setupPage(self): # self.writer.setPageSizeMM(QSizeF(*self.paperFormatMM)) # self.writer.setPageMargins(QMarginsF(0, 0, 0, 0)) # Horizontal lines pos = self.bleeding[0] - self.separation[0] / 2 while (pos < self.paperFormat[0]): self.painter.drawLine(pos, 0, pos, self.paperFormat[1]) pos += self.cardFormat[0] + self.separation[0] # Vertical lines pos = self.bleeding[1] - self.separation[1] / 2 while (pos < self.paperFormat[1]): self.painter.drawLine(0, pos, self.paperFormat[0], pos) pos += self.cardFormat[1] + self.separation[1] @assert_file_open def addPage(self): self.writer.newPage() self._setupPage() @assert_file_open def addCard(self, card, num_copies): for _ in range(num_copies): if self.cursor[1] > (self.paperFormat[1] - self.bleeding[1] - self.cardFormat[1]): self.cursor = self.bleeding[:] self.addPage() self.painter.drawPixmap(*self.cursor, *self.cardFormat, card) self.cursor[0] += self.cardFormat[0] + self.separation[0] if self.cursor[0] > (self.paperFormat[0] - self.bleeding[0] - self.cardFormat[0]): self.cursor[0] = self.bleeding[0] self.cursor[1] += self.cardFormat[1] + self.separation[1] @assert_file_open def close(self): self.painter.end() self.file.flush() self.file.close() def isOpen(self): return self.file.isOpen()
def ConverttxtToPack(in1,out1): dsoIn = QFile(in1) if dsoIn.open(QIODevice.ReadOnly | QIODevice.Text) is False: return dsoOut=QFile(out1) if dsoOut.open(QIODevice.WriteOnly) is False: return totalRecords = 0 while (dsoIn.atEnd() is False): dsoIn.readLine() totalRecords+=1 dsoIn.seek(0) dsoOutStream = QDataStream(dsoOut) dsoOutStream.setVersion(QDataStream.Qt_5_2) readOk = 0 dsoOutStream.writeQString('3.11') dsoOutStream.writeQString('standard') while (dsoIn.atEnd() is False): record = str(dsoIn.readLine(), encoding='utf-8') vp = re.match("ersion\s+([\d\.]+)\s+(\w+)",record) if (record.startswith("//") or record.startswith("#")): totalRecords-=1 continue lis=record.split('\t') try: # if 1: id = int(lis[0]) ra = float((lis[1]).strip()) dec = float((lis[2]).strip()) bMag = float(lis[3]) vMag = float(lis[4]) oType = (lis[5]).strip() mType = (lis[6]).strip() majorAxisSize = float(lis[7]) minorAxisSize = float(lis[8]) orientationAngle = int(float(lis[9])) z = float(lis[10]) zErr = float(lis[11]) plx = float(lis[12]) plxErr = float(lis[13]) dist = float(lis[14]) distErr = float(lis[15]) NGC = int(lis[16]) IC = int(lis[17]) M = int(lis[18]) C = int(lis[19]) B = int(lis[20]) Sh2 = int(lis[21]) VdB = int(lis[22]) RCW = int(lis[23]) LDN = int(lis[24]) LBN = int(lis[25]) Cr = int(lis[26]) Mel = int(lis[27]) PGC = int(lis[28]) UGC = int(lis[29]) Ced = (lis[30]).strip() Arp = int(lis[31]) VV = int(lis[32]) PK = (lis[33]).strip() PNG = (lis[34]).strip() SNRG = (lis[35]).strip() ACO = (lis[36]).strip() HCG = (lis[37]).strip() ESO = (lis[38]).strip() VdBH = (lis[39]).strip() DWB = int(lis[40]) Tr = int(lis[41]) St = int(lis[42]) Ru = int(lis[43]) VdBHa = int(lis[44]) raRad = float(ra) * math.pi / 180 decRad = float(dec) * math.pi / 180 majorAxisSize /= 60 minorAxisSize /= 60 if (bMag <= 0): bMag = 99 if (vMag <= 0): vMag = 99 if oType.upper() in otypedic: nType = otypedic[oType.upper()] else: nType = 36 readOk += 1 dsoOutStream.writeInt(id) dsoOutStream.writeFloat(ra/180*math.pi) dsoOutStream.writeFloat(dec/180*math.pi) dsoOutStream.writeFloat(bMag) dsoOutStream.writeFloat(vMag) dsoOutStream.writeInt(nType) # dsoOutStream.writeUInt64(nType) dsoOutStream.writeQString(mType) dsoOutStream.writeFloat(majorAxisSize) dsoOutStream.writeFloat(minorAxisSize) dsoOutStream.writeInt(orientationAngle) dsoOutStream.writeFloat(z) dsoOutStream.writeFloat(zErr) dsoOutStream.writeFloat(plx) dsoOutStream.writeFloat(plxErr) dsoOutStream.writeFloat(dist) dsoOutStream.writeFloat(distErr) dsoOutStream.writeInt(NGC) dsoOutStream.writeInt(IC) dsoOutStream.writeInt(M) dsoOutStream.writeInt(C) dsoOutStream.writeInt(B) dsoOutStream.writeInt(Sh2) dsoOutStream.writeInt(VdB) dsoOutStream.writeInt(RCW) dsoOutStream.writeInt(LDN) dsoOutStream.writeInt(LBN) dsoOutStream.writeInt(Cr) dsoOutStream.writeInt(Mel) dsoOutStream.writeInt(PGC) dsoOutStream.writeInt(UGC) dsoOutStream.writeQString(Ced) dsoOutStream.writeInt(Arp) dsoOutStream.writeInt(VV) dsoOutStream.writeQString(PK) dsoOutStream.writeQString(PNG) dsoOutStream.writeQString(SNRG) dsoOutStream.writeQString(ACO) dsoOutStream.writeQString(HCG) dsoOutStream.writeQString(ESO) dsoOutStream.writeQString(VdBH) dsoOutStream.writeInt(DWB) dsoOutStream.writeInt(Tr) dsoOutStream.writeInt(St) dsoOutStream.writeInt(Ru) dsoOutStream.writeInt(VdBHa) except: print(record) continue dsoIn.close() dsoOut.flush() dsoOut.close() return
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 PluginRequestDialog(QDialog,Ui_PluginRequestDialog): """ the plugin install dialog """ def __init__(self,parent=None): QDialog.__init__(self,parent) self.setupUi(self) #center this window screen = QDesktopWidget().screenGeometry() size = self.geometry() self.move((screen.width()-size.width())/2, (screen.height()-size.height())/2) QObject.connect(self.pluginList, SIGNAL("customContextMenuRequested (const QPoint&)"),self.__evt_contextmenu) QObject.connect(self.update,SIGNAL("clicked ()"),self.__evt_update) self.__http = None self.__downloadFile = None self.__baseUrl = "http://localhost/" self.plugin_txt_url.setText("%splugins.txt"%self.__baseUrl) self.__evt_update() def __evt_update(self): self.progressBar.setValue(0) self.download(QUrl(self.plugin_txt_url.text())) def download(self,url): """ download something """ if None == self.__http: self.__http = QHttp() QObject.connect(self.__http, SIGNAL("done(bool)"), self.__downloadFileDone) QObject.connect(self.__http, SIGNAL("dataReadProgress(int, int)"), self.__dataReadProgress) if QUrl(url).scheme() == 'https': connectionMode = QHttp.ConnectionModeHttps else: connectionMode = QHttp.ConnectionModeHttp self.__http.setHost(url.host(),connectionMode,url.port(80)) self.__downloadFile = QFile(tempfile.NamedTemporaryFile().name) self.__http.get(url.path(),self.__downloadFile) def __downloadFileDone(self, error): """ Private method called, after the file has been downloaded from the internet. @param error flag indicating an error condition (boolean) """ if self.__downloadFile.exists(): filename = self.__downloadFile.fileName() #Notice must flush it first self.__downloadFile.flush() if not zipfile.is_zipfile(filename): plugins_info = open(filename).readlines() self.pluginList.clear() for plugin_info in plugins_info: try: plugin_name = plugin_info.split('|')[0] plugin_version = plugin_info.split('|')[1] plugin_instruction = plugin_info.split('|')[2] plugin_author = plugin_info.split('|')[3] itree = QTreeWidgetItem() itree.setText(0,plugin_name) itree.setText(1,plugin_author) itree.setText(2,plugin_version) itree.setText(3,plugin_instruction) self.pluginList.addTopLevelItem(itree) except Exception as e: raise e else: pluginDir = getPrccisePath("pluginsDir", "", "extdir") if sys.platform.startswith("win") else getPrccisePath("pluginsDir", "", "userdir") tmpZip = zipfile.ZipFile(filename) for file in tmpZip.namelist(): tmpZip.extract(file,pluginDir) tmpZip.close() self.result_label.setText("Success install the plugin ") def __dataReadProgress(self, done, total): """ Private slot to show the download progress. @param done number of bytes downloaded so far (integer) @param total total bytes to be downloaded (integer) """ self.progressBar.setMaximum(total) self.progressBar.setValue(done) def __has_this_plugin(self,plugin_name): """ Check if this plugin has installed """ for item in PluginAdapter().new().readInfos(): if item[0]==plugin_name: return item return None def __evt_contextmenu(self,point): """ show the right menu """ item = self.pluginList.currentItem() if item: menu = QMenu(self) action = QAction(QApplication.translate("default","Install plugins..."),self,triggered=lambda:self.__evt_install_plugin(item)) menu.addAction(action) action = QAction(QApplication.translate("default","Uninstall plugins..."),self) menu.addAction(action) menu.exec_(self.mapToGlobal(self.pluginList.mapTo(self,point))) def __evt_install_plugin(self,item): filename = "plugin-%s-%s.zip"%(item.text(0),item.text(2)) if not None == self.__has_this_plugin(item.text(0)): self.download(QUrl("%s%s"%(self.__baseUrl,filename))) else: self.result_label.setText("This plugin '%s' had installed "%item.text(0))
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 OpencvWidget(QLabel): def __init__(self, *args, **kwargs): super(OpencvWidget, self).__init__(*args, **kwargs) self.httpRequestAborted = False self.fps = 24 self.resize(800, 600) if not os.path.exists( "D:/access55/shape_predictor_68_face_landmarks.dat"): self.setText("正在下载数据文件。。。") self.outFile = QFile( "D:/access55/shape_predictor_68_face_landmarks.dat.bz2") if not self.outFile.open(QIODevice.WriteOnly): QMessageBox.critical(self, '错误', '无法写入文件') return self.qnam = QNetworkAccessManager(self) self._reply = self.qnam.get(QNetworkRequest(QUrl(URL))) self._reply.finished.connect(self.httpFinished) self._reply.readyRead.connect(self.httpReadyRead) self._reply.downloadProgress.connect(self.updateDataReadProgress) else: self.startCapture() def httpFinished(self): self.outFile.close() if self.httpRequestAborted or self._reply.error(): self.outFile.remove() self._reply.deleteLater() del self._reply # 下载完成解压文件并加载摄像头 self.setText("正在解压数据。。。") try: bz = BZ2Decompressor() data = bz.decompress( open('D:/access55/shape_predictor_68_face_landmarks.dat.bz2', 'rb').read()) open('D:/access55/shape_predictor_68_face_landmarks.dat', 'wb').write(data) except Exception as e: self.setText('解压失败:' + str(e)) return self.setText('正在开启摄像头。。。') self.startCapture() def httpReadyRead(self): self.outFile.write(self._reply.readAll()) self.outFile.flush() def updateDataReadProgress(self, bytesRead, totalBytes): self.setText('已下载:{} %'.format(round(bytesRead / 64040097 * 100, 2))) def startCapture(self): self.setText("请稍候,正在初始化数据和摄像头。。。") try: # 检测相关 self.detector = dlib.get_frontal_face_detector() self.predictor = dlib.shape_predictor( "D:/access55/shape_predictor_68_face_landmarks.dat") cascade_fn = "D:/access55/lbpcascades/lbpcascade_frontalface.xml" self.cascade = cv2.CascadeClassifier(cascade_fn) if not self.cascade: return QMessageBox.critical(self, "错误", cascade_fn + " 无法找到") self.cap = cv2.VideoCapture(0) if not self.cap or not self.cap.isOpened(): return QMessageBox.critical(self, "错误", "打开摄像头失败") # 开启定时器定时捕获 self.timer = QTimer(self, timeout=self.onCapture) self.timer.start(1000 / self.fps) except Exception as e: QMessageBox.critical(self, "错误", str(e)) def closeEvent(self, event): if hasattr(self, "_reply") and self._reply: self.httpRequestAborted = True self._reply.abort() try: os.unlink( "D:/access55/shape_predictor_68_face_landmarks.dat.bz2") except: pass try: os.unlink("D:/access55/shape_predictor_68_face_landmarks.dat") except: pass if hasattr(self, "timer"): self.timer.stop() self.timer.deleteLater() self.cap.release() del self.predictor, self.detector, self.cascade, self.cap super(OpencvWidget, self).closeEvent(event) self.deleteLater() def onCapture(self): _, frame = self.cap.read() minisize = (int(frame.shape[1] / DOWNSCALE), int(frame.shape[0] / DOWNSCALE)) tmpframe = cv2.resize(frame, minisize) tmpframe = cv2.cvtColor(tmpframe, cv2.COLOR_BGR2GRAY) # 做灰度处理 tmpframe = cv2.equalizeHist(tmpframe) # minNeighbors表示每一个目标至少要被检测到5次 faces = self.cascade.detectMultiScale(tmpframe, minNeighbors=5) del tmpframe if len(faces) < 1: # 没有检测到脸 frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) img = QImage(frame.data, frame.shape[1], frame.shape[0], frame.shape[1] * 3, QImage.Format_RGB888) del frame return self.setPixmap(QPixmap.fromImage(img)) # 特征点检测描绘 for x, y, w, h in faces: x, y, w, h = x * DOWNSCALE, y * DOWNSCALE, w * DOWNSCALE, h * DOWNSCALE # 画脸矩形 cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0)) # 截取的人脸部分 tmpframe = frame[y:y + h, x:x + w] # 进行特征点描绘 rects = self.detector(tmpframe, 1) if len(rects) > 0: landmarks = numpy.matrix( [[p.x, p.y] for p in self.predictor(tmpframe, rects[0]).parts()]) for _, point in enumerate(landmarks): pos = (point[0, 0] + x, point[0, 1] + y) # 在原来画面上画点 cv2.circle(frame, pos, 3, color=(0, 255, 0)) # 转成Qt能显示的 frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) img = QImage(frame.data, frame.shape[1], frame.shape[0], frame.shape[1] * 3, QImage.Format_RGB888) del frame self.setPixmap(QPixmap.fromImage(img))
class PluginRequestDialog(QDialog, Ui_PluginRequestDialog): """ the plugin install dialog """ def __init__(self, parent=None): QDialog.__init__(self, parent) self.setupUi(self) #center this window screen = QDesktopWidget().screenGeometry() size = self.geometry() self.move((screen.width() - size.width()) / 2, (screen.height() - size.height()) / 2) QObject.connect(self.pluginList, SIGNAL("customContextMenuRequested (const QPoint&)"), self.__evt_contextmenu) QObject.connect(self.update, SIGNAL("clicked ()"), self.__evt_update) self.__http = None self.__downloadFile = None self.__baseUrl = "http://localhost/" self.plugin_txt_url.setText("%splugins.txt" % self.__baseUrl) self.__evt_update() def __evt_update(self): self.progressBar.setValue(0) self.download(QUrl(self.plugin_txt_url.text())) def download(self, url): """ download something """ if None == self.__http: self.__http = QHttp() QObject.connect(self.__http, SIGNAL("done(bool)"), self.__downloadFileDone) QObject.connect(self.__http, SIGNAL("dataReadProgress(int, int)"), self.__dataReadProgress) if QUrl(url).scheme() == 'https': connectionMode = QHttp.ConnectionModeHttps else: connectionMode = QHttp.ConnectionModeHttp self.__http.setHost(url.host(), connectionMode, url.port(80)) self.__downloadFile = QFile(tempfile.NamedTemporaryFile().name) self.__http.get(url.path(), self.__downloadFile) def __downloadFileDone(self, error): """ Private method called, after the file has been downloaded from the internet. @param error flag indicating an error condition (boolean) """ if self.__downloadFile.exists(): filename = self.__downloadFile.fileName() #Notice must flush it first self.__downloadFile.flush() if not zipfile.is_zipfile(filename): plugins_info = open(filename).readlines() self.pluginList.clear() for plugin_info in plugins_info: try: plugin_name = plugin_info.split('|')[0] plugin_version = plugin_info.split('|')[1] plugin_instruction = plugin_info.split('|')[2] plugin_author = plugin_info.split('|')[3] itree = QTreeWidgetItem() itree.setText(0, plugin_name) itree.setText(1, plugin_author) itree.setText(2, plugin_version) itree.setText(3, plugin_instruction) self.pluginList.addTopLevelItem(itree) except Exception as e: raise e else: pluginDir = getPrccisePath( "pluginsDir", "", "extdir") if sys.platform.startswith( "win") else getPrccisePath("pluginsDir", "", "userdir") tmpZip = zipfile.ZipFile(filename) for file in tmpZip.namelist(): tmpZip.extract(file, pluginDir) tmpZip.close() self.result_label.setText("Success install the plugin ") def __dataReadProgress(self, done, total): """ Private slot to show the download progress. @param done number of bytes downloaded so far (integer) @param total total bytes to be downloaded (integer) """ self.progressBar.setMaximum(total) self.progressBar.setValue(done) def __has_this_plugin(self, plugin_name): """ Check if this plugin has installed """ for item in PluginAdapter().new().readInfos(): if item[0] == plugin_name: return item return None def __evt_contextmenu(self, point): """ show the right menu """ item = self.pluginList.currentItem() if item: menu = QMenu(self) action = QAction(QApplication.translate("default", "Install plugins..."), self, triggered=lambda: self.__evt_install_plugin(item)) menu.addAction(action) action = QAction( QApplication.translate("default", "Uninstall plugins..."), self) menu.addAction(action) menu.exec_(self.mapToGlobal(self.pluginList.mapTo(self, point))) def __evt_install_plugin(self, item): filename = "plugin-%s-%s.zip" % (item.text(0), item.text(2)) if not None == self.__has_this_plugin(item.text(0)): self.download(QUrl("%s%s" % (self.__baseUrl, filename))) else: self.result_label.setText("This plugin '%s' had installed " % item.text(0))
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"))