downloadController.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. let OSS = require('ali-oss');
  2. let fs = require('fs');
  3. let path = require('path');
  4. var archiver = require('archiver');
  5. let request = require("request");
  6. let http = require('http');
  7. let compressPercent = 0;
  8. let taskCodeQueue = [];
  9. let taskDownloaderQueue = {};
  10. let pathConfig = {
  11. ossPrefix: 'http://4dkankan.oss-cn-shenzhen.aliyuncs.com/', // oss前缀
  12. // serverPrefix: 'http://192.168.0.208:8887/', // 服务器前缀
  13. serverPrefix: 'https://www.4dage.com/download_scene/controller/', // 服务器前缀
  14. localDataName: 'localData',
  15. layer: './', // 层级
  16. rootFold: 'tmpData', // 根目录文件夹
  17. staticPath: [ // 静态数据路径
  18. 'static'
  19. ],
  20. paths: [ // images/data路径
  21. 'images/images',
  22. 'data/data',
  23. 'voice/voice',
  24. 'video/video'
  25. ],
  26. editPaths:[
  27. 'images/images',
  28. 'data/data',
  29. 'voice/voice'
  30. ],
  31. filters: [],
  32. dynamicPath: [ // 一些使用api加载的数据, 提前写入json中
  33. 'https://www.4dkankan.com/api/scene/getInfo'
  34. ],
  35. downloadUrlServer:'https://www.4dkankan.com/'
  36. }
  37. function getEditDataUrl(num,cb = ()=>{}) {
  38. let URL = `https://www.4dkankan.com/api/scene/getEditDataUrl?num=${num}`
  39. let data = ''
  40. request(URL,(error, response, body)=>{
  41. if (!error) {
  42. let temp = JSON.parse(body)
  43. if (temp.code==0) {
  44. data=temp.data
  45. cb(data)
  46. }
  47. }
  48. })
  49. }
  50. function downloader() {
  51. this.objArr = [];
  52. this.completeFolds = 0; // 记录已经递归完成的目录, completeFolds == foldNum, 表示所有目录递归完成
  53. this.fileNum = 0; // 需要下载的文件总数
  54. this.completeFileNum = 0; // 已经下载完成的文件总数
  55. this.threadNum = 10; // 同时并发的线程总数
  56. this.curActiveThread = 0;
  57. this.sta = 0;
  58. this.downloadProcess = 0; // 下载进度
  59. this.zipProcess = 0; // 压缩进度
  60. this.sceneCode = ''; // 场景码
  61. this.sceneCodeArr = [] // 场景码数据
  62. this.snCode = '' //sn码
  63. this.isTiles = true; // 是否下载tiles
  64. this.sceneInfo = ''; // 场景的其他json数据
  65. this.downloadResponse = null;
  66. this.timer = null; // 定时器
  67. this.dirPath = path.join(__dirname, pathConfig.rootFold);
  68. this.foldNum = pathConfig.paths.length + pathConfig.staticPath.length; // 记录目录的总数, 用于判断是否目录是否递归完成
  69. this.client = new OSS({ // 配置阿里云oss
  70. region: 'oss-cn-shenzhen',
  71. accessKeyId: 'LTAIUrvuHqj8pvry',
  72. accessKeySecret: 'JLOVl0k8Ke0aaM8nLMMiUAZ3EiiqI4',
  73. bucket: '4dkankan',
  74. })
  75. }
  76. /**
  77. * 创建文件夹
  78. * @param data 文件路径
  79. */
  80. downloader.prototype.createRootFold = function (data) {
  81. if (!fs.existsSync(this.dirPath)) {
  82. fs.mkdirSync(this.dirPath);
  83. } else {
  84. // console.log('文件夹已存在');
  85. }
  86. this.dirPath = path.join(this.dirPath, '/' + data);
  87. // 创建文件夹目录
  88. if (!fs.existsSync(this.dirPath)) {
  89. fs.mkdirSync(this.dirPath);
  90. } else {
  91. // console.log('文件夹已存在');
  92. }
  93. console.log('-------dirPath---------',this.dirPath)
  94. }
  95. /**
  96. * 递归列举编辑页面需要下载的文件, 记录文件夹以及所有文件的总数
  97. */
  98. downloader.prototype.listEditDir = async function (editUrl) {
  99. let that = this;
  100. editUrl.forEach(item=>{
  101. let dirArr = item.split('/')
  102. let objName = dirArr.pop()
  103. let tmpDir = '';
  104. let childDirPath;
  105. dirArr.forEach((sub) => { // 对于路径中的每一个层级, 都创建对应的文件夹
  106. tmpDir += '/' + sub;
  107. childDirPath = path.join(this.dirPath, '/' + tmpDir); // 子路径
  108. if (!fs.existsSync(childDirPath)) {
  109. fs.mkdirSync(childDirPath);
  110. // console.log('创建文件夹成功: ' + childDirPath);
  111. } else {
  112. // console.log('文件夹已存在');
  113. }
  114. });
  115. let downloadURL = pathConfig.downloadUrlServer + item; // 记录每个文件需要下载的url
  116. if (objName === '') { // 过滤非法文件, 因为阿里云有时候会把文件夹当作文件返回,
  117. return;
  118. }
  119. let writeURL = path.join(childDirPath, objName); // 下载完成后, 应当写入的路径
  120. let tack = { // 创建下载任务
  121. downloadURL: downloadURL,
  122. writeURL: writeURL
  123. }
  124. that.objArr.push(tack);
  125. // this.completeFolds++;
  126. // this.timer = setInterval(this.download.bind(this), 16); // 开始下载
  127. })
  128. }
  129. /**
  130. * 递归列举所有需要下载的文件, 记录文件夹以及所有文件的总数
  131. */
  132. downloader.prototype.listDir = async function (dir, prefixDir) {
  133. let that = this;
  134. let filters = pathConfig.filters
  135. if (!that.isTiles) {
  136. filters.push('tiles')
  137. }
  138. for (let i = 0; i < filters.length; i++) { // 有些文件夹不需要下载, 则进行过滤
  139. let filter = filters[i];
  140. if (dir.indexOf(filter) > 0) {
  141. console.log('过滤的路径' + dir);
  142. that.completeFolds++;
  143. if (that.completeFolds === that.foldNum) { // 已经列举完成的文件夹数目等于需要下载的文件夹总数
  144. that.fileNum = that.objArr.length;
  145. that.timer = setInterval(that.download, 16); // 开始下载
  146. }
  147. return;
  148. }
  149. }
  150. dirArr = `${prefixDir}${dir}`.split('/'); // 分割其目录层级
  151. let tmpDir = '';
  152. let childDirPath;
  153. dirArr.forEach((item) => { // 对于路径中的每一个层级, 都创建对应的文件夹
  154. tmpDir += '/' + item;
  155. childDirPath = path.join(this.dirPath, '/' + tmpDir); // 子路径
  156. if (!fs.existsSync(childDirPath)) {
  157. fs.mkdirSync(childDirPath);
  158. // console.log('创建文件夹成功: ' + childDirPath);
  159. } else {
  160. // console.log('文件夹已存在');
  161. }
  162. });
  163. // 列举当前文件夹中的所有文件, 最多1000个
  164. let result = await this.client.list({
  165. prefix: dir,
  166. delimiter: '/',
  167. 'max-keys': 1000 // 最大限制1000
  168. });
  169. // result.objects就是当前文件夹下的所有文件
  170. result.objects && result.objects.forEach(async function (obj) {
  171. let downloadURL = pathConfig.ossPrefix + obj.name; // 记录每个文件需要下载的url
  172. let arr = obj.name.split('/');
  173. let objName = arr[arr.length - 1]; // 获取文件名, 上面的obj.name除了文件名, 还包含了文件所属的路径
  174. if (objName === '') { // 过滤非法文件, 因为阿里云有时候会把文件夹当作文件返回,
  175. return;
  176. }
  177. let writeURL = path.join(childDirPath, objName); // 下载完成后, 应当写入的路径
  178. let tack = { // 创建下载任务
  179. downloadURL: downloadURL,
  180. writeURL: writeURL
  181. }
  182. that.objArr.push(tack); // 下载任务入列
  183. });
  184. if (result.prefixes) { // 如果当前目录还有子目录存在, 则继续递归
  185. this.foldNum--; // 移除当前目录, 因为当前目录还不是最深层级
  186. let that = this;
  187. result.prefixes.forEach(function (subDir) {
  188. that.foldNum++; // 记录当前目录的子目录
  189. that.listDir(subDir, prefixDir);
  190. });
  191. } else { // 当前目录已经递归完成
  192. this.completeFolds++;
  193. console.log(this.completeFolds + ' ' + this.foldNum)
  194. if (this.completeFolds === this.foldNum) { // 已经列举完成的文件夹数目等于需要下载的文件夹总数
  195. // console.log(this.objArr)
  196. this.fileNum = this.objArr.length; // 记录需要下载的文件总数
  197. this.timer = setInterval(this.download.bind(this), 16); // 开始下载
  198. }
  199. }
  200. }
  201. downloader.prototype.download = function () {
  202. if (this.objArr.length === 0) { // 所有文件已经下载完成, 清楚定时器
  203. clearInterval(this.timer);
  204. this.timer = null;
  205. return;
  206. }
  207. if (this.curActiveThread <= this.threadNum) { // 当前活跃的线程数<总线程数, 则继续创建创建下载队列, 控制并发
  208. let task = this.objArr.shift(); // 取队列中的第一个任务
  209. let stream = fs.createWriteStream(task.writeURL); // 根据任务中的写入路径创建流
  210. let readStream = request(task.downloadURL).on('error', function () { // 通过下载路径去请求文件
  211. console.log("文件[" + task.downloadURL + "]下载出错 ");
  212. }).pipe(stream);
  213. let that = this;
  214. readStream.on('finish', function () { // 当前流下载完成, 释放线程
  215. that.curActiveThread--;
  216. })
  217. stream.on('finish', function () { // 文件写入完毕
  218. that.completeFileNum++; // 已经下载完成的文件数+1
  219. that.downloadProcess = that.completeFileNum / that.fileNum * 100; // 计算下载进度
  220. if (that.completeFileNum === that.fileNum) { // 所有的oss文件已下载完
  221. let sceneCode = that.sceneCode; // 记录场景码
  222. let sceneCodeArr = that.sceneCodeArr; // 记录场景码数组
  223. let snCode = that.snCode
  224. let sceneCodePath = path.join(__dirname, `tmpData/${snCode}/code.txt`);
  225. fs.writeFileSync(sceneCodePath , '')
  226. sceneCodeArr.forEach((item,idx)=>{
  227. // sceneData.json的写入路径, sceneData.json记录的是场景中的其他信息, 如场景描述、场景密码等可配置信息
  228. let sceneJsonPath = path.join(__dirname, `tmpData/${snCode}/static/images/images${item.sceneCode}/sceneData.json`);
  229. // code.txt的写入路径, 其记录的是场景码, 本地浏览器需要读取该文件
  230. fs.writeFileSync(sceneJsonPath, item.sceneInfo, function (err) { // 写入sceneInfo.json
  231. if (err) {
  232. return console.log(`写入文件出错: ${err}`);
  233. }
  234. })
  235. fs.writeFileSync(sceneCodePath , item.sceneCode+(idx===sceneCodeArr.length-1?'':','),{flag:'a'}, function (err,code) { // 将场景码写入
  236. console.log('-----code-----',code)
  237. })
  238. })
  239. console.log('开始压缩' + that.sceneCode)
  240. // let zipStream = fs.createWriteStream(`${__dirname}/tmpData/${that.sceneCode}/` + `/localData.zip`);
  241. let zipStream = fs.createWriteStream(`${__dirname}/tmpData/zip/` + `/${snCode}.zip`); // 创建压缩包
  242. pathConfig.localDataName = snCode;
  243. let archive = archiver('zip', {
  244. zlib: {
  245. level: 9 // 压缩等级
  246. }
  247. });
  248. zipStream.on('close', function () {
  249. let respData = 'archiver has been finalized and the output file descriptor has closed.';
  250. console.log(archive.pointer() + ' total bytes');
  251. console.log('文件压缩已写入完成');
  252. // 重置两个进度
  253. downloadPercent = 0;
  254. compressPercent = 0;
  255. });
  256. // 计算压缩进度
  257. archive.on('progress', function (process) {
  258. compressPercent = that.zipProcess = process.fs.processedBytes / process.fs.totalBytes * 100;
  259. })
  260. archive.on('error', function (err) {
  261. console.log(err);
  262. })
  263. archive.pipe(zipStream);
  264. archive.directory(`${__dirname}/tmpData/${snCode}/`, false); // 将已经下载完成的全部内容放入至压缩流中
  265. archive.directory(`${__dirname}/static/page`, false); // 追加html文件
  266. archive.directory(`${__dirname}/browser/`, false); // 将浏览器放入压缩流中
  267. archive.finalize();
  268. }
  269. })
  270. this.curActiveThread++; // 激活的线程数+1
  271. }
  272. }
  273. downloader.prototype.execute = function (data) {
  274. // let arr = ['t-updScXn','t-J3VGU9J']
  275. this.createRootFold(this.snCode);
  276. this.sceneCodeArr.forEach(item => {
  277. getEditDataUrl(item.sceneCode, (res)=>{
  278. this.listEditDir(res);
  279. pathConfig.paths.forEach(path => {
  280. this.listDir(path + item.sceneCode, `static/`);
  281. })
  282. pathConfig.staticPath.forEach(path => {
  283. this.listDir(path, '');
  284. })
  285. })
  286. })
  287. }
  288. /**
  289. * 起始函数
  290. * @param {*} response 响应
  291. * @param {*} data 前端传过来的数据
  292. */
  293. function start(response, data) {
  294. let sceneCode = data.sceneCode;
  295. let sceneCodeArr = data.sceneCodeArr
  296. let snCode = data.snCode
  297. let respData;
  298. // 如果已经存在压缩包, 则直接返回压缩包的路径给浏览器进行下载
  299. if (fs.existsSync(`${__dirname}/${pathConfig.rootFold}/${snCode}/${pathConfig.localDataName}.zip`)) {
  300. respData = {
  301. sta: 1003, // 1003 文件已存在
  302. data: {
  303. percent: 100,
  304. url: `${pathConfig.serverPrefix}${pathConfig.rootFold}/${snCode}/${pathConfig.localDataName}.zip`
  305. },
  306. msg: '文件已存在, 直接返回url'
  307. };
  308. // console.log('文件已存在, 直接返回url');
  309. } else {
  310. respData = {
  311. sta: 1002, // 1002
  312. data: {
  313. percent: 0
  314. },
  315. msg: '已加入任务队列'
  316. };
  317. taskCodeQueue.push(snCode);
  318. taskDownloaderQueue[snCode] = new downloader(); // 对于每个前端发来的下载请求, 创建一个downloader实例
  319. // taskDownloaderQueue[snCode].sceneCode = data.sceneCode;
  320. taskDownloaderQueue[snCode].sceneCodeArr = sceneCodeArr;
  321. taskDownloaderQueue[snCode].snCode = snCode;
  322. // taskDownloaderQueue[snCode].sceneCode = data.sceneCode;
  323. taskDownloaderQueue[snCode].isTiles = data.isTiles;
  324. // taskDownloaderQueue[snCode].sceneInfo = data.sceneInfo; // sceneInfo就是场景中其他的可配置信息, 用于写入sceneData.json中
  325. }
  326. let json = JSON.stringify(respData)
  327. response.send(json);
  328. }
  329. /**
  330. * 查询下载进度
  331. * @param {*} response 响应
  332. * @param {*} data 前端传过来的数据
  333. */
  334. function downloadProcess(response, data) {
  335. let snCode = data.snCode;
  336. let downloader = taskDownloaderQueue[snCode];
  337. if (!downloader) return;
  338. if (downloader.downloadProcess < 100) { // 文件正在下载中
  339. let respData = {
  340. sta: 1000, // 状态码 1000-文件正在下载 1001-文件正在压缩
  341. data: {
  342. percent: downloader.downloadProcess
  343. },
  344. msg: '文件下载中'
  345. };
  346. let json = JSON.stringify(respData)
  347. response.send(json);
  348. } else { // 文件正在压缩中
  349. let respData = {
  350. sta: 1001, // 状态码 1000-文件正在下载 1001-文件正在压缩
  351. data: {
  352. percent: downloader.zipProcess
  353. },
  354. msg: '文件压缩中'
  355. };
  356. if (downloader.zipProcess === 100) {
  357. respData.data.url = `${pathConfig.serverPrefix}${pathConfig.rootFold}/zip/${pathConfig.localDataName}.zip`
  358. }
  359. let json = JSON.stringify(respData)
  360. response.send(json);
  361. }
  362. }
  363. (function () {
  364. // 服务器的downloader队列, 每隔1s处理一个前端的下载请求, 避免服务器压力过大
  365. setInterval(function () {
  366. let taskCode = taskCodeQueue.shift();
  367. if (taskCode) {
  368. taskDownloaderQueue[taskCode].execute(taskCode);
  369. }
  370. }, 1000)
  371. })()
  372. exports.start = start;
  373. exports.downloadProcess = downloadProcess;