|
| 1 | +/* |
| 2 | + * GNU AGPL-3.0 License |
| 3 | + * |
| 4 | + * Copyright (c) 2021 - present core.ai . All rights reserved. |
| 5 | + * Original work Copyright (c) 2016 - 2021 Adobe Systems Incorporated. All rights reserved. |
| 6 | + * |
| 7 | + * This program is free software: you can redistribute it and/or modify it |
| 8 | + * under the terms of the GNU Affero General Public License as published by |
| 9 | + * the Free Software Foundation, either version 3 of the License, or |
| 10 | + * (at your option) any later version. |
| 11 | + * |
| 12 | + * This program is distributed in the hope that it will be useful, but WITHOUT |
| 13 | + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or |
| 14 | + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License |
| 15 | + * for more details. |
| 16 | + * |
| 17 | + * You should have received a copy of the GNU Affero General Public License |
| 18 | + * along with this program. If not, see https://opensource.org/licenses/AGPL-3.0. |
| 19 | + * |
| 20 | + */ |
| 21 | + |
| 22 | +/*global path, logger, jsPromise*/ |
| 23 | + |
| 24 | +define(function (require, exports, module) { |
| 25 | + const NativeApp = brackets.getModule("utils/NativeApp"), |
| 26 | + FileSystem = brackets.getModule("filesystem/FileSystem"), |
| 27 | + ProjectManager = brackets.getModule("project/ProjectManager"), |
| 28 | + FileSystemError = brackets.getModule("filesystem/FileSystemError"), |
| 29 | + FileUtils = brackets.getModule("file/FileUtils"), |
| 30 | + DocumentManager = brackets.getModule("document/DocumentManager"); |
| 31 | + |
| 32 | + const BACKUP_INTERVAL_MS = 3000; // todo change to 20 secs |
| 33 | + // todo large number of tracked files performance issues? |
| 34 | + const sessionRestoreDir = FileSystem.getDirectoryForPath( |
| 35 | + path.normalize(NativeApp.getApplicationSupportDirectory() + "/sessionRestore")); |
| 36 | + |
| 37 | + let trackingProjectRoot = null, |
| 38 | + trackingRestoreRoot = null, |
| 39 | + trackedProjectFilesMap = {}, |
| 40 | + trackedFilesChangeTimestamps = {}; |
| 41 | + |
| 42 | + function simpleHash(str) { |
| 43 | + let hash = 0; |
| 44 | + for (let i = 0; i < str.length; i++) { |
| 45 | + let char = str.charCodeAt(i); |
| 46 | + // eslint-disable-next-line no-bitwise |
| 47 | + hash = ((hash << 5) - hash) + char; |
| 48 | + // eslint-disable-next-line no-bitwise |
| 49 | + hash = hash & hash; // Convert to 32bit integer |
| 50 | + } |
| 51 | + return Math.abs(hash) + ""; |
| 52 | + } |
| 53 | + |
| 54 | + function createDir(dir) { |
| 55 | + return new Promise((resolve, reject)=>{ |
| 56 | + dir.create(function (err) { |
| 57 | + if (err && err !== FileSystemError.ALREADY_EXISTS) { |
| 58 | + console.error("Error creating project crash restore folder " + dir.fullPath, err); |
| 59 | + reject(err); |
| 60 | + } |
| 61 | + resolve(); |
| 62 | + }); |
| 63 | + }); |
| 64 | + } |
| 65 | + |
| 66 | + function silentlyRemoveFile(path) { |
| 67 | + return new Promise((resolve)=>{ |
| 68 | + FileSystem.getFileForPath(path).unlink((err)=>{ |
| 69 | + if(err) { |
| 70 | + console.error(err); |
| 71 | + } |
| 72 | + resolve(); |
| 73 | + }); |
| 74 | + }); |
| 75 | + } |
| 76 | + |
| 77 | + function setupProjectRestoreRoot(projectPath) { |
| 78 | + const baseName = path.basename(projectPath); |
| 79 | + let restoreRootPath = path.normalize(`${sessionRestoreDir.fullPath}/${baseName}_${simpleHash(projectPath)}`); |
| 80 | + trackingRestoreRoot = FileSystem.getDirectoryForPath(restoreRootPath); |
| 81 | + createDir(trackingRestoreRoot); |
| 82 | + } |
| 83 | + |
| 84 | + function getRestoreFilePath(projectFilePath) { |
| 85 | + if(ProjectManager.isWithinProject(projectFilePath)) { |
| 86 | + return path.normalize( |
| 87 | + `${trackingRestoreRoot.fullPath}/${ProjectManager.getProjectRelativePath(projectFilePath)}`); |
| 88 | + } |
| 89 | + return null; |
| 90 | + } |
| 91 | + |
| 92 | + // try not to use this |
| 93 | + function getProjectFilePath(restoreFilePath) { |
| 94 | + if(!restoreFilePath.startsWith(trackingRestoreRoot.fullPath)){ |
| 95 | + return null; |
| 96 | + } |
| 97 | + // Eg. trackingRestoreRoot = "/fs/app/sessionRestore/default project_1944444020/" |
| 98 | + // and restoreProjectRelativePath = "/fs/app/sessionRestore/default project_1944444020/default project/a.html" |
| 99 | + let restoreProjectRelativePath = restoreFilePath.replace(trackingRestoreRoot.fullPath, ""); |
| 100 | + // Eg. default project/a.html |
| 101 | + let restoreProjectName = restoreProjectRelativePath.split("/")[0], // Eg. default project |
| 102 | + trackingProjectName = path.basename(trackingProjectRoot.fullPath); // default project |
| 103 | + if(trackingProjectName !== restoreProjectName){ |
| 104 | + return null; |
| 105 | + } |
| 106 | + let filePathInProject = restoreProjectRelativePath.replace(`${restoreProjectName}/`, ""); // a.html |
| 107 | + return path.normalize(`${trackingProjectRoot.fullPath}/${filePathInProject}`); |
| 108 | + } |
| 109 | + |
| 110 | + function projectOpened(_event, projectRoot) { |
| 111 | + trackingProjectRoot = projectRoot; |
| 112 | + setupProjectRestoreRoot(trackingProjectRoot.fullPath); |
| 113 | + } |
| 114 | + |
| 115 | + async function writeFileIgnoreFailure(filePath, contents) { |
| 116 | + try { |
| 117 | + let parentDir = FileSystem.getDirectoryForPath(path.dirname(filePath)); |
| 118 | + await createDir(parentDir); |
| 119 | + let file = FileSystem.getFileForPath(filePath); |
| 120 | + await jsPromise(FileUtils.writeText(file, contents, true)); |
| 121 | + } catch (e) { |
| 122 | + console.error(e); |
| 123 | + logger.reportError(e); // todo too many error reports prevent every 20 secs |
| 124 | + } |
| 125 | + } |
| 126 | + |
| 127 | + async function backupChangedDocs(changedDocs) { |
| 128 | + for(let doc of changedDocs){ |
| 129 | + let restorePath = getRestoreFilePath(doc.file.fullPath); |
| 130 | + await writeFileIgnoreFailure(restorePath, doc.getText()); |
| 131 | + trackedFilesChangeTimestamps[doc.file.fullPath] = doc.lastChangeTimestamp; |
| 132 | + trackedProjectFilesMap[doc.file.fullPath] = restorePath; |
| 133 | + } |
| 134 | + } |
| 135 | + |
| 136 | + async function cleanupUntrackedFiles(docPathsToTrack) { |
| 137 | + let allTrackingPaths = Object.keys(trackedProjectFilesMap); |
| 138 | + for(let trackedPath of allTrackingPaths){ |
| 139 | + if(!docPathsToTrack[trackedPath]){ |
| 140 | + const restoreFile = trackedProjectFilesMap[trackedPath]; |
| 141 | + await silentlyRemoveFile(restoreFile); |
| 142 | + delete trackedProjectFilesMap[trackedPath]; |
| 143 | + delete trackedFilesChangeTimestamps[trackedPath]; |
| 144 | + } |
| 145 | + } |
| 146 | + } |
| 147 | + |
| 148 | + let backupInProgress = false; |
| 149 | + async function changeScanner() { |
| 150 | + if(backupInProgress || trackingProjectRoot.fullPath === "/"){ |
| 151 | + // trackingProjectRoot can be "/" if debug>open virtual file system menu is clicked. Don't track root fs |
| 152 | + return; |
| 153 | + } |
| 154 | + backupInProgress = true; |
| 155 | + try{ |
| 156 | + // do backup |
| 157 | + const openDocs = DocumentManager.getAllOpenDocuments(); |
| 158 | + let changedDocs = [], docPathsToTrack = {}; |
| 159 | + for(let doc of openDocs){ |
| 160 | + if(doc && doc.isDirty){ |
| 161 | + docPathsToTrack[doc.file.fullPath] = true; |
| 162 | + const lastTrackedTimestamp = trackedFilesChangeTimestamps[doc.file.fullPath]; |
| 163 | + if(!lastTrackedTimestamp || lastTrackedTimestamp !== doc.lastChangeTimestamp){ |
| 164 | + // Already backed up, only need to consider it again if its contents changed |
| 165 | + changedDocs.push(doc); |
| 166 | + } |
| 167 | + } |
| 168 | + } |
| 169 | + await backupChangedDocs(changedDocs); |
| 170 | + await cleanupUntrackedFiles(docPathsToTrack); |
| 171 | + } catch (e) { |
| 172 | + console.error(e); |
| 173 | + logger.reportError(e); |
| 174 | + } |
| 175 | + backupInProgress = false; |
| 176 | + } |
| 177 | + |
| 178 | + function documentChanged(_event, doc) { |
| 179 | + let restorePath = getRestoreFilePath(doc.file.fullPath); |
| 180 | + let originalPath = getProjectFilePath(restorePath); |
| 181 | + //debugger; |
| 182 | + } |
| 183 | + |
| 184 | + function documentDirtyFlagChanged(_event, doc) { |
| 185 | + //debugger; |
| 186 | + } |
| 187 | + |
| 188 | + function init() { |
| 189 | + ProjectManager.on(ProjectManager.EVENT_AFTER_PROJECT_OPEN, projectOpened); |
| 190 | + DocumentManager.on(DocumentManager.EVENT_DOCUMENT_CHANGE, documentChanged); |
| 191 | + DocumentManager.on(DocumentManager.EVENT_DIRTY_FLAG_CHANGED, documentDirtyFlagChanged); |
| 192 | + createDir(sessionRestoreDir); |
| 193 | + if(!window.testEnvironment){ |
| 194 | + setInterval(changeScanner, BACKUP_INTERVAL_MS); |
| 195 | + } |
| 196 | + } |
| 197 | + |
| 198 | + exports.init = init; |
| 199 | +}); |
0 commit comments