bookManager.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. import localForage from 'localforage';
  2. import path from 'path';
  3. import BookParser from './BookParser';
  4. class BookManager {
  5. async init() {
  6. this.books = {};
  7. const len = await localForage.length();
  8. for (let i = 0; i < len; i++){
  9. const key = await localForage.key(i);
  10. const keySplit = key.split('-');
  11. if (keySplit.length == 2 && keySplit[1] == 'meta') {
  12. let meta = await localForage.getItem(key);
  13. meta.data = await localForage.getItem(keySplit[0]);
  14. this.books[meta.key] = meta;
  15. this.books[meta.url] = meta;
  16. }
  17. }
  18. console.log(this.books);
  19. }
  20. async addBook(newBook, callback) {
  21. if (!this.books)
  22. await this.init();
  23. let meta = {url: newBook.url, path: newBook.path};
  24. meta.key = path.basename(newBook.path);
  25. const result = await this.parseBook(meta, newBook.data, callback);
  26. await localForage.setItem(meta.key, result.data);
  27. await localForage.setItem(`${meta.key}-meta`, meta);
  28. return result;
  29. }
  30. async getBook(meta, callback) {
  31. if (!this.books)
  32. await this.init();
  33. let result = undefined;
  34. if (meta.key)
  35. result = this.books[meta.key];
  36. else
  37. result = this.books[meta.url];
  38. if (result && !result.parsed) {
  39. result = await this.parseBook(result, result.data, callback);
  40. }
  41. return result;
  42. }
  43. async delBook(meta) {
  44. if (!this.books)
  45. await this.init();
  46. let book = undefined;
  47. if (meta.key)
  48. book = this.books[meta.key];
  49. else
  50. book = this.books[meta.url];
  51. if (book) {
  52. await localForage.removeItem(book.key);
  53. await localForage.removeItem(`${book.key}-meta`);
  54. delete this.books[book.key];
  55. delete this.books[book.url];
  56. }
  57. }
  58. async parseBook(meta, data, callback) {
  59. if (!this.books)
  60. await this.init();
  61. const parsed = new BookParser();
  62. const parsedMeta = await parsed.parse(data, callback);
  63. const result = Object.assign({}, meta, parsedMeta, {data, parsed});
  64. this.books[meta.key] = result;
  65. this.books[meta.url] = result;
  66. return result;
  67. }
  68. metaOnly(book) {
  69. let result = Object.assign({}, book);
  70. delete result.data;
  71. delete result.parsed;
  72. return result;
  73. }
  74. }
  75. export default new BookManager();