-
Notifications
You must be signed in to change notification settings - Fork 112
/
checkForUpdate.js
107 lines (95 loc) · 2.8 KB
/
checkForUpdate.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
function fetchUpdateInfo(context, callback) {
var fs = context.requireCordovaModule('fs');
var updateInfo = {
releaseDate: 0,
podUpdateDate: 0,
lastCheckDate: 0
};
fs.readFile('platforms/ios/.intercom_update', 'utf8', function (err, data) {
if (!err) {
obj = JSON.parse(data);
updateInfo.podUpdateDate = obj.podUpdateDate;
updateInfo.releaseDate = obj.releaseDate;
updateInfo.lastCheckDate = obj.lastCheckDate;
}
callback(updateInfo);
});
}
function writeUpdateInfo(context, updateInfo, callback) {
var fs = context.requireCordovaModule('fs');
fs.writeFile('platforms/ios/.intercom_update', JSON.stringify(updateInfo), 'utf8', function (err,data) {
callback();
});
}
function updateIntercomIfNeeded(context, updateInfo, callback) {
var exec = context.requireCordovaModule('child_process').exec;
var completion = function() {
writeUpdateInfo(context, updateInfo, function() {
callback();
});
};
if (updateInfo.releaseDate > updateInfo.podUpdateDate) {
console.log("Updating Intercom");
exec('cd platforms/ios && pod update Intercom', function(error, stdout, stderr) {
if (!error) {
console.log(stdout);
updateInfo.podUpdateDate = Date.now();
}
completion();
});
} else {
completion();
}
}
function fetchLatestRelease(context, callback) {
var https = context.requireCordovaModule('https');
var req = https.get({
headers: {
accept: 'application/json',
'User-Agent': 'Intercom-Cordova-Plugin'
},
host: 'api.github.com',
path: '/repos/intercom/intercom-ios/releases/latest'
}, function(response) {
if (response.statusCode != 200) {
callback(null);
return;
}
var body = '';
response.on('data', function(d) {
body += d;
});
response.on('end', function() {
var parsedResponse = JSON.parse(body);
callback(parsedResponse);
});
});
req.on('error', function(e) {
callback(null);
});
}
module.exports = function(context) {
var Q = context.requireCordovaModule('q');
var deferral = new Q.defer();
fetchUpdateInfo(context, function(updateInfo) {
// Check at most once every 48 hours
if (Date.now() - updateInfo.lastCheckDate > 1000 * 60 * 60 * 48) {
fetchLatestRelease(context, function(releaseData) {
updateInfo.lastCheckDate = Date.now();
if (releaseData != null) {
updateInfo.releaseDate = Date.parse(releaseData['published_at']);
updateIntercomIfNeeded(context, updateInfo, function() {
deferral.resolve();
});
} else {
writeUpdateInfo(context, updateInfo, function() {
deferral.resolve();
});
}
});
} else {
deferral.resolve();
}
});
return deferral.promise;
}