InpxParser.js 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. const path = require('path');
  2. const crypto = require('crypto');
  3. const ZipReader = require('./ZipReader');
  4. const utils = require('./utils');
  5. const collectionInfo = 'collection.info';
  6. const structureInfo = 'structure.info';
  7. const versionInfo = 'version.info';
  8. const defaultStructure = 'AUTHOR;GENRE;TITLE;SERIES;SERNO;FILE;SIZE;LIBID;DEL;EXT;DATE;LANG;LIBRATE;KEYWORDS';
  9. //'AUTHOR;GENRE;TITLE;SERIES;SERNO;FILE;SIZE;LIBID;DEL;EXT;DATE;INSNO;FOLDER;LANG;LIBRATE;KEYWORDS;'
  10. const defaultRecStruct = {
  11. author: 'S',
  12. genre: 'S',
  13. title: 'S',
  14. series: 'S',
  15. serno: 'N',
  16. file: 'S',
  17. size: 'N',
  18. libid: 'S',
  19. del: 'N',
  20. ext: 'S',
  21. date: 'S',
  22. insno: 'N',
  23. folder: 'S',
  24. lang: 'S',
  25. librate: 'N',
  26. keywords: 'S',
  27. }
  28. class InpxParser {
  29. constructor() {
  30. this.inpxInfo = {};
  31. }
  32. async safeExtractToString(zipReader, fileName) {
  33. let result = '';
  34. try {
  35. result = (await zipReader.extractToBuf(fileName)).toString().trim();
  36. } catch (e) {
  37. //quiet
  38. }
  39. return result;
  40. }
  41. getRecStruct(structure) {
  42. const result = {};
  43. for (const field of structure)
  44. if (utils.hasProp(defaultRecStruct, field))
  45. result[field] = defaultRecStruct[field];
  46. //folder есть всегда
  47. result['folder'] = defaultRecStruct['folder'];
  48. return result;
  49. }
  50. async parse(inpxFile, readFileCallback, parsedCallback) {
  51. if (!readFileCallback)
  52. readFileCallback = async() => {};
  53. if (!parsedCallback)
  54. parsedCallback = async() => {};
  55. const zipReader = new ZipReader();
  56. await zipReader.open(inpxFile);
  57. try {
  58. const info = this.inpxInfo;
  59. //посчитаем inp-файлы
  60. const entries = Object.values(zipReader.entries);
  61. const inpFiles = [];
  62. for (const entry of entries) {
  63. if (!entry.isDirectory && path.extname(entry.name) == '.inp')
  64. inpFiles.push(entry.name);
  65. }
  66. //плюс 3 файла .info
  67. await readFileCallback({totalFiles: inpFiles.length + 3});
  68. let current = 0;
  69. //info
  70. await readFileCallback({fileName: collectionInfo, current: ++current});
  71. info.collection = await this.safeExtractToString(zipReader, collectionInfo);
  72. await readFileCallback({fileName: structureInfo, current: ++current});
  73. info.structure = await this.safeExtractToString(zipReader, structureInfo);
  74. await readFileCallback({fileName: versionInfo, current: ++current});
  75. info.version = await this.safeExtractToString(zipReader, versionInfo);
  76. //структура
  77. if (!info.structure)
  78. info.structure = defaultStructure;
  79. const structure = info.structure.toLowerCase().split(';');
  80. info.recStruct = this.getRecStruct(structure);
  81. //парсим inp-файлы
  82. this.chunk = [];
  83. for (const inpFile of inpFiles) {
  84. await readFileCallback({fileName: inpFile, current: ++current});
  85. await this.parseInp(zipReader, inpFile, structure, parsedCallback);
  86. }
  87. if (this.chunk.length) {
  88. await parsedCallback(this.chunk);
  89. }
  90. } finally {
  91. await zipReader.close();
  92. }
  93. }
  94. async parseInp(zipReader, inpFile, structure, parsedCallback) {
  95. const inpBuf = await zipReader.extractToBuf(inpFile);
  96. const rows = inpBuf.toString().split('\n');
  97. const defaultFolder = `${path.basename(inpFile, '.inp')}.zip`;
  98. const structLen = structure.length;
  99. for (const row of rows) {
  100. let line = row;
  101. if (!line)
  102. continue;
  103. if (line[line.length - 1] == '\x0D')
  104. line = line.substring(0, line.length - 1);
  105. const rec = {};
  106. //уникальный идентификатор записи
  107. const sha256 = crypto.createHash('sha256');
  108. rec._uid = sha256.update(line).digest('base64');
  109. //парсим запись
  110. const parts = line.split('\x04');
  111. const len = (parts.length > structLen ? structLen : parts.length);
  112. for (let i = 0; i < len; i++) {
  113. if (structure[i])
  114. rec[structure[i]] = parts[i];
  115. }
  116. //специальная обработка некоторых полей
  117. if (rec.author) {
  118. rec.author = rec.author.split(':').map(s => s.replace(/,/g, ' ').trim()).filter(s => s).join(',');
  119. }
  120. if (rec.genre) {
  121. rec.genre = rec.genre.split(':').filter(s => s).join(',');
  122. }
  123. if (!rec.folder)
  124. rec.folder = defaultFolder;
  125. rec.serno = parseInt(rec.serno, 10) || 0;
  126. rec.size = parseInt(rec.size, 10) || 0;
  127. rec.del = parseInt(rec.del, 10) || 0;
  128. rec.insno = parseInt(rec.insno, 10) || 0;
  129. rec.librate = parseInt(rec.librate, 10) || 0;
  130. //пушим
  131. this.chunk.push(rec);
  132. if (this.chunk.length >= 10000) {
  133. await parsedCallback(this.chunk);
  134. this.chunk = [];
  135. }
  136. }
  137. }
  138. get info() {
  139. return this.inpxInfo;
  140. }
  141. }
  142. module.exports = InpxParser;