install.js 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. 'use strict';
  2. const extractZip = require('extract-zip');
  3. const fs = require('fs');
  4. const helper = require('./lib/chromedriver');
  5. const request = require('request');
  6. const mkdirp = require('mkdirp');
  7. const path = require('path');
  8. const del = require('del');
  9. const child_process = require('child_process');
  10. const os = require('os');
  11. const skipDownload = process.env.npm_config_chromedriver_skip_download || process.env.CHROMEDRIVER_SKIP_DOWNLOAD;
  12. if (skipDownload) {
  13. console.log('Found CHROMEDRIVER_SKIP_DOWNLOAD variable, skipping installation.');
  14. process.exit(0);
  15. }
  16. const libPath = path.join(__dirname, 'lib', 'chromedriver');
  17. let cdnUrl = process.env.npm_config_chromedriver_cdnurl || process.env.CHROMEDRIVER_CDNURL || 'https://chromedriver.storage.googleapis.com';
  18. const configuredfilePath = process.env.npm_config_chromedriver_filepath || process.env.CHROMEDRIVER_FILEPATH;
  19. // adapt http://chromedriver.storage.googleapis.com/
  20. cdnUrl = cdnUrl.replace(/\/+$/, '');
  21. let platform = process.platform;
  22. let chromedriver_version = process.env.npm_config_chromedriver_version || process.env.CHROMEDRIVER_VERSION || helper.version;
  23. if (platform === 'linux') {
  24. if (process.arch === 'arm64' || process.arch === 'x64') {
  25. platform += '64';
  26. } else {
  27. console.log('Only Linux 64 bits supported.');
  28. process.exit(1);
  29. }
  30. } else if (platform === 'darwin' || platform === 'freebsd') {
  31. if (process.arch === 'x64') {
  32. // @ts-ignore
  33. platform = 'mac64';
  34. } else {
  35. console.log('Only Mac 64 bits supported.');
  36. process.exit(1);
  37. }
  38. } else if (platform !== 'win32') {
  39. console.log('Unexpected platform or architecture:', process.platform, process.arch);
  40. process.exit(1);
  41. }
  42. const tmpPath = findSuitableTempDirectory();
  43. const chromedriverBinaryFileName = process.platform === 'win32' ? 'chromedriver.exe' : 'chromedriver';
  44. const chromedriverBinaryFilePath = path.resolve(tmpPath, chromedriverBinaryFileName );
  45. let downloadedFile = '';
  46. Promise.resolve().then(function () {
  47. if (chromedriver_version === 'LATEST')
  48. return getLatestVersion(getRequestOptions(cdnUrl + '/LATEST_RELEASE'));
  49. })
  50. .then(verifyIfChromedriverIsAvailableAndHasCorrectVersion)
  51. .then(chromedriverIsAvailable => {
  52. if (chromedriverIsAvailable) return;
  53. console.log('Current existing ChromeDriver binary is unavailable, proceding with download and extraction.');
  54. return downloadFile().then(extractDownload);
  55. })
  56. .then(() => copyIntoPlace(tmpPath, libPath))
  57. .then(fixFilePermissions)
  58. .then(() => console.log('Done. ChromeDriver binary available at', helper.path))
  59. .catch(function (err) {
  60. console.error('ChromeDriver installation failed', err);
  61. process.exit(1);
  62. });
  63. function downloadFile() {
  64. if (configuredfilePath) {
  65. downloadedFile = configuredfilePath;
  66. console.log('Using file: ', downloadedFile);
  67. return Promise.resolve();
  68. } else {
  69. const fileName = `chromedriver_${platform}.zip`;
  70. const tempDownloadedFile = path.resolve(tmpPath, fileName);
  71. downloadedFile = tempDownloadedFile;
  72. const formattedDownloadUrl = `${cdnUrl}/${chromedriver_version}/${fileName}`;
  73. console.log('Downloading from file: ', formattedDownloadUrl);
  74. console.log('Saving to file:', downloadedFile);
  75. return requestBinary(getRequestOptions(formattedDownloadUrl), downloadedFile);
  76. }
  77. }
  78. function verifyIfChromedriverIsAvailableAndHasCorrectVersion() {
  79. if (!fs.existsSync(chromedriverBinaryFilePath))
  80. return false;
  81. const forceDownload = process.env.npm_config_chromedriver_force_download === 'true' || process.env.CHROMEDRIVER_FORCE_DOWNLOAD === 'true';
  82. if (forceDownload)
  83. return false;
  84. console.log('ChromeDriver binary exists. Validating...');
  85. const deferred = new Deferred();
  86. try {
  87. fs.accessSync(chromedriverBinaryFilePath, fs.constants.X_OK);
  88. const cp = child_process.spawn(chromedriverBinaryFilePath, ['--version']);
  89. let str = '';
  90. cp.stdout.on('data', function (data) {
  91. str += data;
  92. });
  93. cp.on('error', function () {
  94. deferred.resolve(false);
  95. });
  96. cp.on('close', function (code) {
  97. if (code !== 0)
  98. return deferred.resolve(false);
  99. const parts = str.split(' ');
  100. if (parts.length < 3)
  101. return deferred.resolve(false);
  102. if (parts[1].startsWith(chromedriver_version)) {
  103. console.log(str);
  104. console.log(`ChromeDriver is already available at '${chromedriverBinaryFilePath}'.`);
  105. return deferred.resolve(true);
  106. }
  107. deferred.resolve(false);
  108. });
  109. }
  110. catch (error) {
  111. deferred.resolve(false);
  112. }
  113. return deferred.promise;
  114. }
  115. function findSuitableTempDirectory() {
  116. const now = Date.now();
  117. const candidateTmpDirs = [
  118. process.env.TMPDIR || process.env.TMP || process.env.npm_config_tmp,
  119. os.tmpdir(),
  120. '/tmp',
  121. path.join(process.cwd(), 'tmp')
  122. ];
  123. for (let i = 0; i < candidateTmpDirs.length; i++) {
  124. if (!candidateTmpDirs[i]) continue;
  125. const candidatePath = path.join(candidateTmpDirs[i], 'chromedriver');
  126. try {
  127. mkdirp.sync(candidatePath, '0777');
  128. const testFile = path.join(candidatePath, now + '.tmp');
  129. fs.writeFileSync(testFile, 'test');
  130. fs.unlinkSync(testFile);
  131. return candidatePath;
  132. } catch (e) {
  133. console.log(candidatePath, 'is not writable:', e.message);
  134. }
  135. }
  136. console.error('Can not find a writable tmp directory, please report issue on https://github.com/giggio/chromedriver/issues/ with as much information as possible.');
  137. process.exit(1);
  138. }
  139. function getRequestOptions(downloadPath) {
  140. const options = {uri: downloadPath, method: 'GET'};
  141. const protocol = options.uri.substring(0, options.uri.indexOf('//'));
  142. const proxyUrl = protocol === 'https:'
  143. ? process.env.npm_config_https_proxy
  144. : (process.env.npm_config_proxy || process.env.npm_config_http_proxy);
  145. if (proxyUrl) {
  146. options.proxy = proxyUrl;
  147. }
  148. options.strictSSL = !!process.env.npm_config_strict_ssl;
  149. // Use certificate authority settings from npm
  150. let ca = process.env.npm_config_ca;
  151. // Parse ca string like npm does
  152. if (ca && ca.match(/^".*"$/)) {
  153. try {
  154. ca = JSON.parse(ca.trim());
  155. } catch (e) {
  156. console.error('Could not parse ca string', process.env.npm_config_ca, e);
  157. }
  158. }
  159. if (!ca && process.env.npm_config_cafile) {
  160. try {
  161. ca = fs.readFileSync(process.env.npm_config_cafile, {encoding: 'utf8'})
  162. .split(/\n(?=-----BEGIN CERTIFICATE-----)/g);
  163. // Comments at the beginning of the file result in the first
  164. // item not containing a certificate - in this case the
  165. // download will fail
  166. if (ca.length > 0 && !/-----BEGIN CERTIFICATE-----/.test(ca[0])) {
  167. ca.shift();
  168. }
  169. } catch (e) {
  170. console.error('Could not read cafile', process.env.npm_config_cafile, e);
  171. }
  172. }
  173. if (ca) {
  174. console.log('Using npmconf ca');
  175. options.agentOptions = {
  176. ca: ca
  177. };
  178. options.ca = ca;
  179. }
  180. // Use specific User-Agent
  181. if (process.env.npm_config_user_agent) {
  182. options.headers = {'User-Agent': process.env.npm_config_user_agent};
  183. }
  184. return options;
  185. }
  186. function getLatestVersion(requestOptions) {
  187. const deferred = new Deferred();
  188. request(requestOptions, function (err, response, data) {
  189. if (err) {
  190. deferred.reject('Error with http(s) request: ' + err);
  191. } else {
  192. chromedriver_version = data.trim();
  193. deferred.resolve(true);
  194. }
  195. });
  196. return deferred.promise;
  197. }
  198. function requestBinary(requestOptions, filePath) {
  199. const deferred = new Deferred();
  200. let count = 0;
  201. let notifiedCount = 0;
  202. const outFile = fs.openSync(filePath, 'w');
  203. const client = request(requestOptions);
  204. client.on('error', function (err) {
  205. deferred.reject('Error with http(s) request: ' + err);
  206. });
  207. client.on('data', function (data) {
  208. fs.writeSync(outFile, data, 0, data.length, null);
  209. count += data.length;
  210. if ((count - notifiedCount) > 800000) {
  211. console.log('Received ' + Math.floor(count / 1024) + 'K...');
  212. notifiedCount = count;
  213. }
  214. });
  215. client.on('end', function () {
  216. console.log('Received ' + Math.floor(count / 1024) + 'K total.');
  217. fs.closeSync(outFile);
  218. deferred.resolve(true);
  219. });
  220. return deferred.promise;
  221. }
  222. function extractDownload() {
  223. if (path.extname(downloadedFile) !== '.zip') {
  224. fs.copyFileSync(downloadedFile, path.resolve(tmpPath, 'chromedriver'));
  225. console.log('Skipping zip extraction - binary file found.');
  226. return Promise.resolve();
  227. }
  228. const deferred = new Deferred();
  229. console.log('Extracting zip contents');
  230. extractZip(path.resolve(downloadedFile), { dir: tmpPath }, function (err) {
  231. if (err) {
  232. deferred.reject('Error extracting archive: ' + err);
  233. } else {
  234. deferred.resolve(true);
  235. }
  236. });
  237. return deferred.promise;
  238. }
  239. function copyIntoPlace(originPath, targetPath) {
  240. return del(targetPath)
  241. .then(function() {
  242. console.log("Copying to target path", targetPath);
  243. fs.mkdirSync(targetPath);
  244. // Look for the extracted directory, so we can rename it.
  245. const files = fs.readdirSync(originPath);
  246. const promises = files.map(function(name) {
  247. const deferred = new Deferred();
  248. const file = path.join(originPath, name);
  249. const reader = fs.createReadStream(file);
  250. const targetFile = path.join(targetPath, name);
  251. const writer = fs.createWriteStream(targetFile);
  252. writer.on("close", function() {
  253. deferred.resolve(true);
  254. });
  255. reader.pipe(writer);
  256. return deferred.promise;
  257. });
  258. return Promise.all(promises);
  259. });
  260. }
  261. function fixFilePermissions() {
  262. // Check that the binary is user-executable and fix it if it isn't (problems with unzip library)
  263. if (process.platform != 'win32') {
  264. const stat = fs.statSync(helper.path);
  265. // 64 == 0100 (no octal literal in strict mode)
  266. if (!(stat.mode & 64)) {
  267. console.log('Fixing file permissions');
  268. fs.chmodSync(helper.path, '755');
  269. }
  270. }
  271. }
  272. function Deferred() {
  273. this.resolve = null;
  274. this.reject = null;
  275. this.promise = new Promise(function (resolve, reject) {
  276. this.resolve = resolve;
  277. this.reject = reject;
  278. }.bind(this));
  279. Object.freeze(this);
  280. }