Ejemplo n.º 1
0
    def init(self) -> bool:
        """Create the Connection to the Database.

        For the Moment just SQLite

        Returns:
            Return true is the database successfull initialized.
        """
        self.database = QSqlDatabase.database()

        if self.dbType == "sqlite":
            if not self.database.isValid():
                self.database = QSqlDatabase.addDatabase("QSQLITE")
                if not self.database.isValid():
                    self.log.error("Cannot add database")
                    return False

            self.database_name = self.__get_sqlite_name()
            file = QFile(self.database_name)
            if file.exists():
                # When using the SQLite driver, open() will create the SQLite
                # database if it doesn't exist.
                self.log.info("Try open the existing db : {}".format(
                    self.database_name))
                self.database.setDatabaseName(self.database_name)
            else:
                self.database.setDatabaseName(self.database_name)
                self.log.info("Try create db : {}".format(self.database_name))
                self.prepare_db()

            if not self.database.open():
                self.log.error("Cannot open database")
                QFile.remove(self.database_name)
                return False
        elif self.dbType == "psql":
            self.database = QSqlDatabase.addDatabase("QPSQL")
        elif self.dbType == "odbc":
            self.database = QSqlDatabase.addDatabase("QODBC")

        self.database.setHostName(self.database_hostname)
        self.database.setPort(self.database_port)
        self.database.setUserName(self.database_user_name)
        self.database.setPassword(self.database_password)

        if not self.database.isValid():
            self.log.error("Cannot add database")
            return False

        if not self.database.open():
            self.log.error("Cannot open database")
            return False

        return True
Ejemplo n.º 2
0
def connectToDatabase(logger):
    database = QSqlDatabase.database()
    if not database.isValid():
        database = QSqlDatabase.addDatabase('QSQLITE')
        if not database.isValid():
            logger.error('Cannot add database')

    write_dir = QDir()
    if not write_dir.mkpath('.'):
        logger.error('Failed to create writable directory')

    # Ensure that we have a writable location on all devices.
    filename = '{}/chat-database.sqlite3'.format(write_dir.absolutePath())

    # When using the SQLite driver, open() will create the SQLite database if it doesn't exist.
    database.setDatabaseName(filename)
    if not database.open():
        logger.error('Cannot open database')
        QFile.remove(filename)
Ejemplo n.º 3
0
    def start(self):
        """ Start downloading the file specify by set_source 
        """
        filepath = self.destination.absoluteFilePath(self.source.fileName())

        if QFile(filepath).exists():
            QFile.remove(filepath)

        self._file = QFile(filepath)

        # open the file to write in
        if self._file.open(QIODevice.WriteOnly):
            print("open file", filepath)
            # Create a Qt Request
            request = QNetworkRequest()
            request.setUrl(self.source)
            self.time = QTime.currentTime()
            self.reply = self.net.get(request)

            # Connect reply to different slots
            self.reply.downloadProgress.connect(self.on_update_progress)
            self.reply.finished.connect(self.on_finished)
            self.reply.error.connect(self.on_error)
Ejemplo n.º 4
0
 def deleteAnalysis(filename: str):
     filepath = "%s/%s.json" % (HistoryManager.appDirectory(), filename)
     QFile.remove(filepath)
Ejemplo n.º 5
0
class DownloadDialog(QDialog):
    """Summary
        A dialog to download file and display progression 

    Attributes:
        source (QUrl): url of file to download
        destination (QDir): destination folder of downloaded file 
    """
    def __init__(self, parent=None):
        super().__init__(parent)

        self.file_label = QLabel()
        self.progress = QProgressBar()
        self.info_label = QLabel()
        self.btn_box = QDialogButtonBox(QDialogButtonBox.Ok
                                        | QDialogButtonBox.Cancel)
        self.net = QNetworkAccessManager()

        font = QFont()
        font.setBold(True)
        self.file_label.setFont(font)

        v_layout = QVBoxLayout()
        v_layout.addWidget(self.file_label)
        v_layout.addWidget(self.progress)
        v_layout.addWidget(self.info_label)
        v_layout.addStretch()
        v_layout.addWidget(self.btn_box)

        self.btn_box.accepted.connect(self.close)
        self.btn_box.rejected.connect(self.cancel)
        self.btn_box.button(QDialogButtonBox.Ok).setVisible(False)

        self.setLayout(v_layout)

        self.setFixedSize(450, 150)
        self.setWindowTitle(self.tr("Download file"))

    def set_source(self, url: QUrl):
        """Set file url to download 
        
        Args:
            url (QUrl)
        """
        self.source = url
        self.file_label.setText(self.source.fileName())

    def set_destination(self, directory: QDir):
        """Set folder path where download the file 
        
        Args:
            directory (QDir)
        """
        self.destination = directory

    def start(self):
        """ Start downloading the file specify by set_source 
        """
        filepath = self.destination.absoluteFilePath(self.source.fileName())

        if QFile(filepath).exists():
            QFile.remove(filepath)

        self._file = QFile(filepath)

        # open the file to write in
        if self._file.open(QIODevice.WriteOnly):
            print("open file", filepath)
            # Create a Qt Request
            request = QNetworkRequest()
            request.setUrl(self.source)
            self.time = QTime.currentTime()
            self.reply = self.net.get(request)

            # Connect reply to different slots
            self.reply.downloadProgress.connect(self.on_update_progress)
            self.reply.finished.connect(self.on_finished)
            self.reply.error.connect(self.on_error)

    def cancel(self):
        """Cancel download
        """
        if hasattr(self, "reply"):
            self.reply.abort()
            self._file.remove()
            self.close()

    @Slot(int, int)
    def on_update_progress(self, read, total):
        """This methods is called by self.reply.downloadProgress signal 
        
        Args:
            read (int): Number of bytes readed
            total (int): Total bytes to download
        """
        if read <= 0:
            return

        if self.reply.error() != QNetworkReply.NoError:
            return

        self._file.write(self.reply.readAll())

        # compute speed
        duration = self.time.secsTo(QTime.currentTime()) + 1
        speed = read / duration
        remaining = (total - read) / speed

        h_remaining = QTime(0, 0, 0, 0).addSecs(remaining).toString()
        h_total = self.human_readable_bytes(total)
        h_read = self.human_readable_bytes(read)
        h_speed = self.human_readable_bytes(speed) + "/sec"

        self.info_label.setText(
            f"Time remaining {h_remaining} - {h_read} of {h_total} ({h_speed})"
        )

        # Set progression
        self.progress.setRange(0, total)
        self.progress.setValue(read)

    @Slot()
    def on_finished(self):
        """This methods is called by self.reply.finished signal
        """
        if self.reply.error() == QNetworkReply.NoError:
            self._file.close()
            self.reply.deleteLater()
            self.btn_box.button(QDialogButtonBox.Ok).setVisible(True)

    @Slot(QNetworkReply.NetworkError)
    def on_error(self, err: QNetworkReply.NetworkError):
        """This method is called by self.reply.error signal
        
        Args:
            err (QNetworkReply.NetworkError)
        """
        self.reply.deleteLater()

    def human_readable_bytes(self, num, suffix="B"):
        for unit in ["", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi"]:
            if abs(num) < 1024.0:
                return "%3.1f%s%s" % (num, unit, suffix)
            num /= 1024.0
        return "%.1f%s%s" % (num, "Yi", suffix)
Ejemplo n.º 6
0
    def saveConfig(self):
        # We haven't yet saved each property
        self.savedShowLocationDMS = False
        self.savedLat = False
        self.savedLon = False
        self.savedTZ = False
        self.savedCorrectForSysTZ = False
        self.savedRiseRun = False
        self.savedSetRun = False
        self.savedRunLastEventAtLaunch = False

        # Get the config and temp filenames
        cfgFilename = self.getConfigFilename()
        tmpFilename = self.getConfigTempFilename()

        # Use any original config file to read and a temp file to write
        cfgFile = QFile(cfgFilename)
        tmpFile = QFile(tmpFilename)
        if (cfgFile is not None) and (tmpFile is not None):
            # Open the input
            inStream = None
            if cfgFile.exists():
                debugMessage("Config file found")

                if cfgFile.open(QIODevice.ReadOnly | QIODevice.Text):
                    inStream = QTextStream(cfgFile)

            # Open the output
            if tmpFile.open(QFile.WriteOnly | QFile.Truncate | QIODevice.Text):
                outStream = QTextStream(tmpFile)
            else:
                outStream = None

            if outStream is not None:
                # If we have an input file, read through it re-writing it to
                # the temp file and change any known settings to current values
                if inStream is not None:
                    while not inStream.atEnd():
                        line = inStream.readLine()
                        print("Saving Config line: {}".format(line))
                        self.processOutputConfigLine(outStream, line)

                    # Remove the original config file
                    cfgFile.remove()
                    cfgFile = None
                else:
                    warningMessage("Unable to open file to save "
                                   "configuration: {}".format(tmpFilename),
                                   self.configSrcFrom)

                # Fixup anything we didn't save in the temp file they will
                # only be written based on the third argument being True
                locationFmtCorrect = (self.savedShowLocationDMS is False) and\
                                     (self.getShowLocationDMS() is True)
                self.processOutputConfigLine(outStream,
                                             "showLocationInDMS",
                                             locationFmtCorrect)
                self.processOutputConfigLine(outStream,
                                             "latitude=0",
                                             not self.savedLat)
                self.processOutputConfigLine(outStream,
                                             "longitude=0",
                                             not self.savedLon)
                self.processOutputConfigLine(outStream,
                                             "timezone=0",
                                             not self.savedTZ)

                tzCorrect = (self.savedCorrectForSysTZ is False) and\
                            (self.getCorrectForSysTZ() is True)
                self.processOutputConfigLine(outStream,
                                             "CorrectForSystemTimezone",
                                             tzCorrect)
                self.processOutputConfigLine(outStream,
                                             "sunriserun=abc",
                                             not self.savedRiseRun)
                self.processOutputConfigLine(outStream,
                                             "sunsetrun=abc",
                                             not self.savedSetRun)

                launchRun = (self.savedRunLastEventAtLaunch is False) and\
                            (self.runLastEventAtLaunch is True)
                self.processOutputConfigLine(outStream,
                                             "runlasteventatlaunch",
                                             launchRun)

                # Rename the temp file as the config file
                tmpFile.rename(cfgFilename)
            else:
                warningMessage("Unable to open previous file to save "
                               "configuration: {}".format(cfgFilename),
                               self.configSrcFrom)