-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathbackground.js
executable file
·86 lines (81 loc) · 2.39 KB
/
background.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
// Enable page action on Github file pages
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, currentTab) {
if (currentTab.status !== 'complete' || changeInfo.status !== 'complete') {
return;
}
if (isFileURL(currentTab.url)) {
chrome.pageAction.show(tabId);
} else {
chrome.pageAction.hide(tabId);
}
});
// Set listener on page action click
chrome.pageAction.onClicked.addListener(function(tab) {
var url = tab.url;
if (!isFileURL(url)) {
return;
}
var rawURL = getRawURL(url);
chrome.downloads.download({
url: rawURL
}, function(id) {
checkDownload({id: id});
});
});
// Check download and open file if it's downloaded
function checkDownload(query) {
chrome.downloads.search(query, function(dl) {
var currentDownload = dl[0];
var fileName;
var fileSize;
var downloadId;
chrome.downloads.onChanged.addListener(function downloadListener(download) {
// Set downloadId and disable shelf if the sizes are equal (it's our file)
if (download.fileSize && download.fileSize.current && download.fileSize.current == currentDownload.fileSize) {
chrome.downloads.setShelfEnabled(false);
fileSize = download.fileSize.current;
downloadId = download.id;
return;
}
// Set fileName
if (download.filename && download.filename.current) {
fileName = download.filename.current;
return;
}
// Ignore if it's not our download
if (download.id !== downloadId) {
return;
}
// If download is completed, we should enable dl shelf again
// and open the file in Code and return
if (download.state && download.state.current && download.state.current === 'complete') {
chrome.downloads.onChanged.removeListener(downloadListener);
chrome.downloads.setShelfEnabled(true);
openInCode(fileName);
return;
}
});
});
}
// Returns true if current url is a file url in Github
function isFileURL(url) {
regex = /https:\/\/github.com\/.+\/.+\/blob\/.+/;
return regex.test(url);
}
// Returns raw download URL
function getRawURL(url) {
return url.replace('blob', 'raw');
}
function openInCode(file) {
chrome.tabs.query({
currentWindow: true,
active: true
}, function(tabs) {
if (!tabs.length) {
return;
}
chrome.tabs.update(tabs[0].id, {
url: encodeURI('vscode://file' + file)
});
});
}