-
-
Notifications
You must be signed in to change notification settings - Fork 67
/
bookmarks.js
86 lines (78 loc) · 2.78 KB
/
bookmarks.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
let mas_bookmarks = {};
function initSecurityScopedBookmarks() {
if (process.mas) {
try {
mas_bookmarks = fs.readFileSync(path.join(global.eApp.getPath('userData'), "mas_bookmarks.json"), "utf8");
} catch(error) {
mas_bookmarks = "{}";
}
try {
mas_bookmarks = JSON.parse(mas_bookmarks);
} catch(e) {
mas_bookmarks = {};
}
}
}
function addToSecurityScopedBookmarks(filepath, bookmark) {
if (bookmark && bookmark.length > 0) {
mas_bookmarks[filepath] = {"bookmark": bookmark};
try {
fs.writeFileSync(path.join(global.eApp.getPath('userData'), "mas_bookmarks.json"), JSON.stringify(mas_bookmarks, null, 2));
} catch(e) {
console.error(e);
}
}
}
// Provide path, returns bookmark
function matchSecurityScopedBookmark(filepath) {
const matching_bookmarks = Object.keys(mas_bookmarks).filter(function(a) {
return filepath.startsWith(a) && (filepath.length === a.length || ["/","\\"].indexOf(filepath.substring(a.length,a.length+1)) > -1);
});
if (matching_bookmarks.length > 0) {
const longest_matching_bookmark = matching_bookmarks.reduce(function(a, b) {return a.length > b.length ? a : b;});
return mas_bookmarks[longest_matching_bookmark].bookmark;
} else {
return null;
}
}
// Provide path, accesses and then returns bookmark
function matchAndAccessSecurityScopedBookmark(filepath) {
const bookmark = matchSecurityScopedBookmark(filepath);
accessSecurityScopedBookmark(bookmark);
return bookmark;
}
let in_use_mas_bookmarks = {};
// Accesses bookmark
function accessSecurityScopedBookmark(bookmark) {
if (!bookmark) return;
if (in_use_mas_bookmarks[bookmark]) {
in_use_mas_bookmarks[bookmark].count++;
} else {
const stopAccessing = global.eApp.startAccessingSecurityScopedResource(bookmark);
in_use_mas_bookmarks[bookmark] = {
count: 1,
stopAccessing: stopAccessing
};
}
}
// Release bookmark
function releaseSecurityScopedBookmark(bookmark) {
if (!bookmark) return;
if (in_use_mas_bookmarks[bookmark]) {
in_use_mas_bookmarks[bookmark].count--;
if (in_use_mas_bookmarks[bookmark].count === 0) {
in_use_mas_bookmarks[bookmark].stopAccessing();
delete in_use_mas_bookmarks[bookmark];
}
} else {
throw new Error("Attempting to release security scoped bookmark that wasn't accessed");
}
}
module.exports = {
init: initSecurityScopedBookmarks,
add: addToSecurityScopedBookmarks,
match: matchSecurityScopedBookmark,
matchAndAccess: matchAndAccessSecurityScopedBookmark,
access: accessSecurityScopedBookmark,
release: releaseSecurityScopedBookmark
}