예제 #1
0
    def exportPrintJobHistoryData(self, exportType):

        if exportType == "CSV":
            allJobsModels = self._databaseManager.loadAllPrintJobs()

            return Response(
                CSVExportImporter.transform2CSV(allJobsModels),
                mimetype='text/csv',
                headers={
                    'Content-Disposition':
                    'attachment; filename=OctoprintPrintJobHistory.csv'
                })  # TODO add timestamp

        else:
            if (exportType == "legacyPrintHistory"):
                return self.exportPrintHistoryData()

            print("BOOOMM not supported type")
        pass
	def exportPrintJobHistoryData(self, exportType):

		if exportType == "CSV":
			allJobsModels = self._databaseManager.loadAllPrintJobs()
			# allJobsDict = self._convertPrintJobHistoryEntitiesToDict(allJobsEntities)
			# allJobsDict = TransformPrintJob2JSON.transformAllPrintJobModels(allJobsModels)

			# csvContent = Transform2CSV.transform2CSV(allJobsDict)
			# csvContent = CSVExportImporter.transform2CSV(allJobsDict)
			# response = flask.make_response(csvContent)

			# response.headers["Content-type"] = "text/csv"
			# response.headers["Content-Disposition"] = "attachment; filename=OctoprintPrintJobHistory.csv" # TODO add timestamp
			# return response

			return Response(CSVExportImporter.transform2CSV(allJobsModels),
							mimetype='text/csv',
							headers={'Content-Disposition': 'attachment; filename=OctoprintPrintJobHistory.csv'}) # TODO add timestamp

		else:
			print("BOOOMM not supported type")

		pass
	def get_sampleCSV(self):

		allJobsModels = list()

		printModel = self._createSamplePrintModel()
		allJobsModels.append(printModel)

		# allJobsModels = self._databaseManager.loadAllPrintJobs()
		# allJobsDict = TransformPrintJob2JSON.transformAllPrintJobModels(allJobsModels)
		# csvContent = Transform2CSV.transform2CSV(allJobsDict)
		# csvContent = CSVExportImporter.transform2CSV(allJobsModels)

		#filename = "PrintJobHistory-SAMPLE.csv"

		# response = flask.make_response(CSVExportImporter.transform2CSV(allJobsModels))
		# response.headers["Content-type"] = "text/csv"
		# response.headers[
		# 	"Content-Disposition"] = "attachment; filename=PrintJobHistory-SAMPLE.csv"  # TODO add timestamp
		#
		# return response

		return Response(CSVExportImporter.transform2CSV(allJobsModels),
						mimetype='text/csv',
						headers={'Content-Disposition': 'attachment; filename=PrintJobHistory-SAMPLE.csv'})
    def exportPrintHistoryData(self):

        allJobsModels = list()

        history_db_path = self.get_plugin_data_folder(
        ) + "/../printhistory/history.db"

        conn = sqlite3.connect(history_db_path)
        cur = conn.cursor()
        cur.execute("SELECT * FROM print_history ORDER BY timestamp")

        for row in cur.fetchall():
            printJob = PrintJobModel()
            filamentModel = FilamentModel()
            isFilamentValuesPresent = False
            for i, value in enumerate(row):
                # id, fileName, note, spool, filamentVolume (float), filamentLength (float), printTime (float), success (int), timestamp (float), user (unicode), parameters (json-string)
                fieldName = cur.description[i][0]
                if (fieldName == "fileName"):
                    printJob.fileName = value
                    continue
                if (fieldName == "note"):
                    printJob.noteText = value
                    continue
                if (fieldName == "spool"):
                    isFilamentValuesPresent = True
                    filamentModel.spoolName = value
                    continue
                if (fieldName == "filamentVolume"):
                    # isFilamentValuesPresent = True
                    # filamentModel.spoolName = value
                    continue  # just ignore
                if (fieldName == "filamentLength"):
                    isFilamentValuesPresent = True
                    filamentModel.usedLength = value
                    filamentModel.calculatedLength = value
                    continue
                if (fieldName == "printTime"):
                    printJob.duration = int(value)
                    continue
                if (fieldName == "success"):
                    if (value == 1):
                        printJob.printStatusResult = "success"
                    else:
                        printJob.printStatusResult = "failed"
                    continue
                if (fieldName == "timestamp"):
                    startPrintDataTime = datetime.fromtimestamp(value)
                    printJob.printStartDateTime = startPrintDataTime
                    continue
                if (fieldName == "user"):
                    printJob.userName = value
                    continue

                if (fieldName == "parameters"):
                    continue  # just ignore
                pass

            if (isFilamentValuesPresent == True):
                printJob.addFilamentModel(filamentModel)

            # Calculate endtime
            endDateTime = printJob.printStartDateTime + timedelta(
                seconds=printJob.duration)
            printJob.printEndDateTime = endDateTime

            allJobsModels.append(printJob)
        # history_dict = [dict(
        # 						(cur.description[i][0], value) \
        # 					 for i, value in enumerate(row)
        # 					) for row in cur.fetchall()]

        conn.close()

        return Response(CSVExportImporter.transform2CSV(allJobsModels),
                        mimetype='text/csv',
                        headers={
                            'Content-Disposition':
                            'attachment; filename=PrintHistory.csv'
                        })
    def _processCSVUploadAsync(self, path, importCSVMode, databaseManager,
                               cameraManager, backupFolder,
                               sendCSVUploadStatusToClient, logger):
        errorCollection = list()

        # - parsing
        # - backup
        # - append or replace

        def updateParsingStatus(lineNumber):
            # importStatus, currenLineNumber, backupFilePath, backupSnapshotFilePath, successMessages, errorCollection
            sendCSVUploadStatusToClient("running", lineNumber, "", "", "",
                                        errorCollection)

        resultOfPrintJobs = CSVExportImporter.parseCSV(path,
                                                       updateParsingStatus,
                                                       errorCollection, logger)

        if (len(errorCollection) != 0):
            successMessage = "Some error(s) occurs during parsing! No jobs imported!"
            sendCSVUploadStatusToClient("finished", "", "", "", successMessage,
                                        errorCollection)
            return

        importModeText = "append"
        backupDatabaseFilePath = None
        backupSnapshotFilePath = None
        if (len(resultOfPrintJobs) > 0):
            # we could import some jobs

            # - backup
            backupDatabaseFilePath = databaseManager.backupDatabaseFile(
                backupFolder)
            backupSnapshotFilePath = cameraManager.backupAllSnapshots(
                backupFolder)

            # - import mode append/replace
            if (SettingsKeys.KEY_IMPORTCSV_MODE_REPLACE == importCSVMode):
                # delete old database and init a clean database
                databaseManager.reCreateDatabase()
                cameraManager.reCreateSnapshotFolder()

                importModeText = "fully replaced"

            # - insert all printjobs in database
            currentPrintJobNumber = 0
            for printJob in resultOfPrintJobs:
                currentPrintJobNumber = currentPrintJobNumber + 1
                updateParsingStatus(currentPrintJobNumber)
                databaseManager.insertPrintJob(printJob)
                # print(printJob)
            pass
        else:
            errorCollection.append("Nothing to import!")

        successMessage = ""
        if (len(errorCollection) == 0):
            successMessage = "All data is successful " + importModeText + " with '" + str(
                len(resultOfPrintJobs)) + "' print jobs."
        else:
            successMessage = "Some error(s) occurs! Maybe you need to manually rollback the database!"

        sendCSVUploadStatusToClient("finished", "", backupDatabaseFilePath,
                                    backupSnapshotFilePath, successMessage,
                                    errorCollection)
        pass