aboutsummaryrefslogtreecommitdiff
path: root/src/modules/requests.js
blob: 94639faad8ac6209fc9d2b665ff402f2a1f6b4b9 (plain)
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
const { app } = require("electron");
const path = require("path");
const fs = require("fs");
const { https, http } = require("follow-redirects");
const lang = require("../lang");

const json = require("./json");

// all requests results are stored in this file
const cachePath = path.join(app.getPath("cache"), "viper-requests.json");
const NORTHSTAR_LATEST_RELEASE_KEY = "nsLatestRelease";
const NORTHSTAR_RELEASE_NOTES_KEY = "nsReleaseNotes";
const VIPER_RELEASE_NOTES_KEY = "vpReleaseNotes";

const user_agent = "viper/" + json(path.join(__dirname, "../../package.json")).version;

function _saveCache(data) {
    fs.writeFileSync(cachePath, JSON.stringify(data));
}

function _getRequestsCache() {
    if (fs.existsSync(cachePath)) {
        return JSON.parse(fs.readFileSync(cachePath, "utf8"));
    } else {
        fs.writeFileSync(cachePath, "{}");
        return {};
    }
}

// Returns latest Northstar version available from GitHub releases. If
// there's no cache result for this request, or if cache exists but is
// old, refreshes cache with new data.
async function getLatestNsVersion() {
    return new Promise((resolve, reject) => {
        let cache = _getRequestsCache();
    
        if (cache[NORTHSTAR_LATEST_RELEASE_KEY] && (Date.now() - cache[NORTHSTAR_LATEST_RELEASE_KEY]["time"]) < 5 * 60 * 1000) {
            resolve( cache[NORTHSTAR_LATEST_RELEASE_KEY]["body"]["tag_name"] );
        } else {
            https.get({
                host: "api.github.com",
                port: 443,
                path: "/repos/R2Northstar/Northstar/releases/latest",
                method: "GET",
                headers: { "User-Agent": user_agent }
            }, 
            
            response => {
                response.setEncoding("utf8");
                let responseData = "";

                response.on("data", data => {
                    responseData += data;
                });

                response.on("end", _ => {                    
                    cache[NORTHSTAR_LATEST_RELEASE_KEY] = {
                        "time": Date.now(),
                        "body": JSON.parse(responseData)
                    };
                    _saveCache(cache);
                    resolve( cache[NORTHSTAR_LATEST_RELEASE_KEY]["body"]["tag_name"] );
                });
            })
            
            .on('error', () => {
                console.error('Failed to get latest Northstar version.');
                resolve( false );
            });
        }
    });
}

// Returns the download link to latest Northstar version. Should always
// be called after getLatestNsVersion, as it refreshes cache data (if
// needed).
function getLatestNsVersionLink() {
    const cache = _getRequestsCache();
    return cache[NORTHSTAR_LATEST_RELEASE_KEY]["body"].assets[0].browser_download_url;
}

// Returns and caches the Northstar release notes
async function getNsReleaseNotes() {
    return new Promise(resolve => {
        let cache = _getRequestsCache();

        if (cache[NORTHSTAR_RELEASE_NOTES_KEY] && (Date.now() - cache[NORTHSTAR_RELEASE_NOTES_KEY]["time"]) < 5 * 60 * 1000) {
            resolve( cache[NORTHSTAR_RELEASE_NOTES_KEY]["body"] );
        } else {
            https.get({
                host: "api.github.com",
                port: 443,
                path: "/repos/R2Northstar/Northstar/releases",
                method: "GET",
                headers: { "User-Agent": user_agent }
            }, 
            
            response => {
                response.setEncoding("utf8");
                let responseData = "";

                response.on("data", data => {
                    responseData += data;
                });

                response.on("end", _ => {                    
                    cache[NORTHSTAR_RELEASE_NOTES_KEY] = {
                        "time": Date.now(),
                        "body": JSON.parse(responseData)
                    };
                    _saveCache(cache);
                    resolve( cache[NORTHSTAR_RELEASE_NOTES_KEY]["body"] );
                });
            })
            
            // When GitHub cannot be reached (when user doesn't have Internet 
            // access for instance), we return latest cache content even if 
            // it's not up-to-date, or display an error message if cache
            // is empty.
            .on('error', () => {
                if ( cache[NORTHSTAR_RELEASE_NOTES_KEY] ) {
                    console.warn("Couldn't fetch Northstar release notes, returning data from cache.");
                    resolve( cache[NORTHSTAR_RELEASE_NOTES_KEY]["body"] );
                } else {
                    console.error("Couldn't fetch Northstar release notes, cache is empty.");
                    resolve( [lang("request.no_ns_release_notes")] );
                }
            });
        }
    });
}

// Returns and caches the Viper release notes
async function getVpReleaseNotes() {
    return new Promise(resolve => {
        let cache = _getRequestsCache();

        if (cache[VIPER_RELEASE_NOTES_KEY] && (Date.now() - cache[VIPER_RELEASE_NOTES_KEY]["time"]) < 5 * 60 * 1000) {
            resolve( cache[VIPER_RELEASE_NOTES_KEY]["body"] );
        } else {
            https.get({
                host: "api.github.com",
                port: 443,
                path: "/repos/0negal/viper/releases",
                method: "GET",
                headers: { "User-Agent": user_agent }
            }, 
            
            response => {
                response.setEncoding("utf8");
                let responseData = "";

                response.on("data", data => {
                    responseData += data;
                });

                response.on("end", _ => {                    
                    cache[VIPER_RELEASE_NOTES_KEY] = {
                        "time": Date.now(),
                        "body": JSON.parse(responseData)
                    };
                    _saveCache(cache);
                    resolve( cache[VIPER_RELEASE_NOTES_KEY]["body"] );
                });
            })

            // When GitHub cannot be reached (when user doesn't have Internet 
            // access for instance), we return latest cache content even if 
            // it's not up-to-date, or display an error message if cache
            // is empty.
            .on('error', () => {
                if ( cache[VIPER_RELEASE_NOTES_KEY] ) {
                    console.warn("Couldn't fetch Viper release notes, returning data from cache.");
                    resolve( cache[VIPER_RELEASE_NOTES_KEY]["body"] );
                } else {
                    console.error("Couldn't fetch Viper release notes, cache is empty.");
                    resolve( [lang("request.no_vp_release_notes")] );
                }
            });
        }
    });
}

module.exports = {
    getLatestNsVersion, 
    getLatestNsVersionLink,
    getNsReleaseNotes,
    getVpReleaseNotes
};