CardsStorage.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. import {FsUtils} from "../lib/FsUtils";
  2. export class CardsStorage {
  3. constructor() {
  4. this.data = [];
  5. this._load();
  6. }
  7. static startWrite(data) {
  8. let url;
  9. switch(data.format) {
  10. case "QR":
  11. url = "page/WriteQR";
  12. break;
  13. case "PDF417":
  14. url = "page/WritePDF417";
  15. break;
  16. case "INT2OF5":
  17. url = "page/WriteInt2of5";
  18. break;
  19. default:
  20. url = "page/WriteBarcode";
  21. }
  22. hmFS.SysProSetBool("mmk_c_aw", true);
  23. hmApp.gotoPage({
  24. url,
  25. param: JSON.stringify(data)
  26. });
  27. }
  28. addCard(data, canvas) {
  29. // Maybe card with this value already exists?
  30. for(let i = 0; i < this.data.length; i++) {
  31. const row = this.data[i];
  32. if(row.content === data.content &&
  33. row.format === data.format &&
  34. row.icon === data.icon
  35. ) {
  36. console.log("recover exiting card!");
  37. row.width = canvas.width;
  38. row.height = canvas.height;
  39. this._writeCanvas(canvas, row.filename);
  40. this._write();
  41. return row;
  42. }
  43. }
  44. let fn = `card_${Math.round(Math.random() * 1e8)}.png`;
  45. if(data.forceFilename) fn = data.forceFilename;
  46. this._writeCanvas(canvas, fn);
  47. const newData = {
  48. ...data,
  49. filename: fn,
  50. width: canvas.width,
  51. height: canvas.height,
  52. index: this.data.length
  53. };
  54. if(data.noStore) return newData;
  55. console.log("Register new card");
  56. this.data.push(newData);
  57. this._write();
  58. return newData;
  59. }
  60. _writeCanvas(canvas, fn) {
  61. const buffer = canvas.data.buffer;
  62. const f = FsUtils.open(FsUtils.fullPath(fn), hmFS.O_WRONLY | hmFS.O_CREAT);
  63. hmFS.write(f, buffer, 0, buffer.byteLength);
  64. hmFS.close(f);
  65. }
  66. deleteCard(data) {
  67. const index = data.index;
  68. if(index < 0) return;
  69. try {
  70. const fn = this.data[index].filename;
  71. hmFS.remove(FsUtils.fullPath(fn));
  72. } catch(e) {}
  73. const newData = [];
  74. for(let i = 0; i < this.data.length; i++) {
  75. if(i == index) continue;
  76. newData.push(this.data[i]);
  77. }
  78. this.data = newData;
  79. this._write();
  80. }
  81. _write() {
  82. console.log("dump json", this.data);
  83. FsUtils.writeText("/storage/mmk_cards.json", JSON.stringify(this.data));
  84. }
  85. _load() {
  86. try {
  87. this.data = FsUtils.fetchJSON("/storage/mmk_cards.json");
  88. } catch(e) {}
  89. }
  90. }