-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathindex_old.js
More file actions
400 lines (370 loc) · 12.9 KB
/
index_old.js
File metadata and controls
400 lines (370 loc) · 12.9 KB
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
/*!
* Main
* Copyright(c) 2009-2017 Marcus Ma
* E-mail:maji1991@sina.com
* GitHub : https://github.com/MarcusMa
* MIT Licensed
*/
'use strict';
/**
* Module dependencies.
*/
const express = require('express');
const exec = require('child_process').exec;
const bodyParser = require('body-parser');
const crypto = require('crypto');
const path = require('path');
const fs = require('fs');
const EventEmitter = require('events');
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
/**
* Custom module dependencies.
*/
const Log = require('./src/utils/Log');
const TAG = "RN_CODE_PUSH_SERVER";
/** event constants */
const EVENT_START_BSDIFF_FILES = "event_start_bsdiff_files";
const EVENT_SINGLE_FILE_BSDIFF_SUCCESS = "event_single_file_bsdiff_success";
const EVENT_SINGLE_FILE_BSDIFF_FAILED = "event_single_file_bsdiff_failed";
const EVENT_START_COMPUTE_HASHCODE = "event_start_compute_hashcode";
const app = express();
const responseJson = {
"success": 1,
"data": null,
"msg": null
};
const DIST_PATH = "./public/dist";
const ORIGINSL_SOURCE_PATH = "./public/original";
const BSDIFF_ROOT_PATH = "./bsdiff-4.3";
const BSDIFF_CMD = BSDIFF_ROOT_PATH + "/bsdiff";
const ServicePort = 8888;
var patchSum = 0;
const dataManager = new BusinessManager();
/** Server Settings */
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json({
limit: '1mb'
}));
app.use(bodyParser.urlencoded({
extended: true
}));
app.get('/testGet', function (req, res) {
Log.i(TAG,req.query);
Log.i(TAG,"call testGet");
res.send("testGet success");
});
app.post('/checkForUpdate', function (req, res) {
Log.i(TAG,"** checkForUpdate ***");
Log.i(TAG,"request body:");
Log.i(TAG,JSON.stringify(req.body));
var reqBody = req.body;
var list = [];
list = reqBody.localBusinessList;
var remoteBuinessList = [];
// 处理传入的参数
if (list instanceof Array) {
list.forEach(function (tmp) {
if (dataManager.getBusinessInfoById(tmp.id)) {
let businessInfo = dataManager.getBusinessInfoById(tmp.id);
let tempData = {
id: tmp.id,
verifyHashCode: ""
};
if (businessInfo && businessInfo.existVersion(tmp.localPackageHashCode)) {
Log.i(TAG,"exitVersion : " + tmp.localPackageHashCode);
tempData.verifyHashCode = tmp.localPackageHashCode;
} else {
Log.i(TAG,"No Such Version " + tmp.localPackageHashCode);
tempData.verifyHashCode = "";
}
// 判断是否有新版本
let latestPatchInfo = businessInfo.getLatestPatchInfo();
if (latestPatchInfo.hashCode == tmp.localPackageHashCode) {
// 无新版本
} else {
tempData.latestPatch = {
hashCode: latestPatchInfo.hashCode,
downloadUrl: latestPatchInfo.getDownloadUrl()
};
}
// 加入返回报文
remoteBuinessList.push(tempData);
}
});
}
// 处理未传入的businessId
dataManager.businessMap.forEach(function (tmp) {
let isExist = false;
if (list instanceof Array) {
for (let j = 0; j < list.length; j++) {
if (list[j].businessId == tmp.id) {
isExist = true;
break;
}
}
}
if (!isExist) {
let tempData = {
id: tmp.id,
verifyHashCode: ""
};
let latestPatchInfo = tmp.getLatestPatchInfo();
tempData.latestPatch = {
hashCode: latestPatchInfo.hashCode,
downloadUrl: latestPatchInfo.getDownloadUrl()
};
remoteBuinessList.push(tempData);
}
});
var resjson = responseJson;
resjson.data = remoteBuinessList;
resjson.msg = " Success ";
res.send(resjson);
});
app.listen(ServicePort, () => {
LogProjectInfo();
Log.i(TAG,'Server Listening at port :' + ServicePort);
Log.i(TAG,".... Data Initilization ....");
var localBusiness = new BusinessInfo("AAF047B7-E816-2AE0-949A-D5FB4CE40245", "myBusiness", "tag1");
dataManager.add(localBusiness);
Log.i(TAG,">>> clear ./dist folder");
var clearDistCmd = "rm -rf " + DIST_PATH;
exec(clearDistCmd, (error, stdout, stderr) => {
if (error) {
Log.i(TAG,`exec error: ${error}`);
return;
}
fs.mkdir(DIST_PATH);
myEmitter.emit(EVENT_START_BSDIFF_FILES);
});
});
/** bsDiff */
myEmitter.on(EVENT_START_BSDIFF_FILES, function () {
Log.i(TAG,">>> start bsdiff patch files");
bsdiffFilesProc(
function () {
myEmitter.emit(EVENT_SINGLE_FILE_BSDIFF_SUCCESS);
},
function () {
myEmitter.emit(EVENT_SINGLE_FILE_BSDIFF_FAILED);
}
);
});
myEmitter.on(EVENT_SINGLE_FILE_BSDIFF_FAILED, function () {
Log.i(TAG,"error happened in bsdiff progress");
});
myEmitter.on(EVENT_SINGLE_FILE_BSDIFF_SUCCESS, function () {
patchSum = patchSum - 1;
if (patchSum <= 0) {
Log.i(TAG,"patch progress complete");
myEmitter.emit(EVENT_START_COMPUTE_HASHCODE);
}
});
/** HashCode */
myEmitter.on(EVENT_START_COMPUTE_HASHCODE, function () {
Log.i(TAG,">>> start compute patch hashcode (sha-256)");
var successCallback = function (filePatch, hashcode) {
let array = filePatch.split('/');
let fileName = array[array.length - 1];
let infos = fileName.split('_');
let busTag = infos[0];
let version = infos[2];
let business = dataManager.getBusinessInfoByTag(busTag);
Log.i(TAG,"businessInfo:" + JSON.stringify(business));
setTimeout(function () {
business.addNewVersion(version, hashcode, filePatch);
Log.i(TAG,"" + JSON.stringify(dataManager));
}, 0);
};
var errorCallback = function () {
Log.i(TAG,`>>>> error in compute hashcode `);
};
var dirs = fs.readdirSync(DIST_PATH);
dirs.forEach(function (tmpDir) {
var distBuinessDir = DIST_PATH + "/" + tmpDir;
if (fs.statSync(distBuinessDir).isDirectory()) {
Log.i(TAG,">>>> Deal Dir: " + distBuinessDir);
var files = fs.readdirSync(distBuinessDir);
files.forEach(function (patchName) {
if (patchName == '.DS_Store' || patchName.substr(patchName.length - 6, 6) != '.patch') {
return;
}
patchSum++;
// start compute hashcode of file
computeFilesHashProc(
distBuinessDir + "/" + patchName,
successCallback,
errorCallback
);
});
}
});
});
/* Main Progress */
function computeFilesHashProc(_filePath, _successCallback, _errorCallback) {
Log.i(TAG,">>>> Compute File: " + _filePath);
let rs = fs.createReadStream(_filePath);
let hash = crypto.createHash('sha256');
rs.on('data', hash.update.bind(hash));
rs.on('end', function () {
let hashcode = hash.digest('hex');
if (hashcode.length <= 0 && typeof _errorCallback === 'function') {
_errorCallback();
} else {
_successCallback(_filePath, hashcode);
}
});
}
function bsdiffFilesProc(_successCallback, _errorCallback) {
var commonPackageFilePath = ORIGINSL_SOURCE_PATH + "/common_min.bundle";
var dirs = fs.readdirSync(ORIGINSL_SOURCE_PATH);
dirs.forEach(function (tmpDir) {
var distBuinessDir = DIST_PATH + "/" + tmpDir;
var originalBuinessDir = ORIGINSL_SOURCE_PATH + "/" + tmpDir;
if (fs.statSync(originalBuinessDir).isDirectory()) {
Log.i(TAG,">>>> Diff With: " + originalBuinessDir);
fs.mkdirSync(distBuinessDir); // make /dist/xxxx dir
var files = fs.readdirSync(originalBuinessDir);
files.forEach(function (completeBundleFile) {
if (completeBundleFile == '.DS_Store') {
return;
}
(function () {
var option = commonPackageFilePath + " " +
originalBuinessDir + "/" + completeBundleFile + " " +
distBuinessDir + "/" + completeBundleFile + ".patch";
var execCmd = BSDIFF_CMD + " " + option;
Log.i(TAG,">>>> " + execCmd);
patchSum++;
exec(execCmd, (error, stdout, stderr) => {
if (error) {
Log.i(TAG,`exec error: ${error}`);
if (typeof _errorCallback === "function") {
_errorCallback();
}
return;
}
Log.i(TAG,">>>> bsdiff success");
if (typeof _successCallback === "function") {
_successCallback();
}
});
})();
});
}
});
}
/**
* Manager & Service
**/
function BusinessManager() {
this.businessMap = [];
}
BusinessManager.prototype.add = function (business) {
if (business instanceof BusinessInfo) {
let isExist = false;
this.businessMap.forEach(function (tmp) {
if (tmp.id === business.id) {
isExist = true;
}
});
if (!isExist) {
Log.i(TAG,">>>> add new Business Id : " + business.id);
this.businessMap.push(business);
}
}
};
BusinessManager.prototype.getBusinessInfoById = function (businessId) {
let ret = null;
if (this.businessMap instanceof Array) {
this.businessMap.forEach(function (tmp) {
Log.i(TAG,"local id" + tmp.id + " search id " + businessId);
if (tmp.id === businessId) {
ret = tmp;
}
});
}
return ret;
};
BusinessManager.prototype.getBusinessInfoByTag = function (businessTag) {
let ret = null;
if (this.businessMap instanceof Array) {
this.businessMap.forEach(function (tmp) {
if (tmp.tag == businessTag) {
ret = tmp;
}
});
}
return ret;
};
/**
* Entity
**/
function BusinessInfo(businessId, businessName, businessTag) {
this.id = businessId;
this.name = businessName;
this.tag = businessTag;
this.versions = [];
}
function PatchVersionInfo(id, patchVersion, patchHashCode, patchFilePath) {
this.businessId = id;
this.version = patchVersion;
this.hashCode = patchHashCode;
this.filePath = patchFilePath;
}
PatchVersionInfo.prototype.getDownloadUrl = function () {
let ret = null;
if (this.filePath) {
ret = this.filePath.substr(9);
}
return ret;
};
BusinessInfo.prototype.existVersion = function (patchHashCode) {
let ret = false;
this.versions.forEach(function (tmp) {
if (tmp.hashCode === patchHashCode) {
ret = true;
}
});
return ret;
};
BusinessInfo.prototype.getLatestPatchInfo = function () {
let ret = null;
let lastVersionIndex = 0;
for (let i = 0; i < this.versions.length; i++) {
if (i > 0) {
if (this.versions[i].version > this.versions[lastVersionIndex].version) {
lastVersionIndex = i;
}
}
}
ret = this.versions[lastVersionIndex];
return ret;
};
BusinessInfo.prototype.addNewVersion = function (patchVersion, patchHashCode, patchFilePath) {
// check the patch version
let isExit = false;
this.versions.forEach(function (tmp) {
if (tmp.version && tmp.version === patchVersion) {
isExit = true;
}
});
if (!isExit) {
Log.i(TAG,">>>> add new business version : " + patchFilePath);
let newPatchVersionInfo = new PatchVersionInfo(this.businessId, patchVersion, patchHashCode, patchFilePath);
this.versions.push(newPatchVersionInfo);
}
};
function LogProjectInfo() {
Log.i(TAG,"##################################################################################");
Log.i(TAG,'# Author : Marcus Ma');
Log.i(TAG,'# E-mail : maji1991@sina.com');
Log.i(TAG,"# GitHub : https://github.com/MarcusMa")
Log.i(TAG,"##################################################################################");
Log.i(TAG,"# Demo Server for React Native Hot Code Push");
Log.i(TAG,"# See: https://github.com/MarcusMa/simple-react-native-hot-code-push-server");
Log.i(TAG,"# For Client Demo, please");
Log.i(TAG,"# See: https://github.com/MarcusMa/simple-react-native-hot-code-push");
Log.i(TAG,"##################################################################################");
}