bookManager.js 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. import localForage from 'localforage';
  2. import * as utils from '../../../share/utils';
  3. import BookParser from './BookParser';
  4. const maxDataSize = 500*1024*1024;//chars, not bytes
  5. const bmMetaStore = localForage.createInstance({
  6. name: 'bmMetaStore'
  7. });
  8. const bmDataStore = localForage.createInstance({
  9. name: 'bmDataStore'
  10. });
  11. const bmRecentStore = localForage.createInstance({
  12. name: 'bmRecentStore'
  13. });
  14. const bmCacheStore = localForage.createInstance({
  15. name: 'bmCacheStore'
  16. });
  17. class BookManager {
  18. async init(settings) {
  19. this.settings = settings;
  20. this.booksCached = await bmCacheStore.getItem('books');
  21. if (!this.booksCached)
  22. this.booksCached = {};
  23. this.recent = await bmCacheStore.getItem('recent');
  24. this.recentLast = await bmCacheStore.getItem('recent-last');
  25. if (this.recentLast)
  26. this.recent[this.recentLast.key] = this.recentLast;
  27. this.books = Object.assign({}, this.booksCached);
  28. this.recentChanged1 = true;
  29. this.recentChanged2 = true;
  30. if (!this.books || !this.recent) {
  31. this.books = {};
  32. this.recent = {};
  33. await this.loadMeta(true);
  34. } else {
  35. this.loadMeta(false);
  36. }
  37. }
  38. //долгая загрузка из хранилища
  39. //bmMetaStore и bmRecentStore в будущем можно будет убрать
  40. //bmCacheStore достаточно
  41. async loadMeta(immediate) {
  42. if (!immediate)
  43. await utils.sleep(2000);
  44. let len = await bmMetaStore.length();
  45. for (let i = 0; i < len; i++) {
  46. const key = await bmMetaStore.key(i);
  47. const keySplit = key.split('-');
  48. if (keySplit.length == 2 && keySplit[0] == 'bmMeta') {
  49. let meta = await bmMetaStore.getItem(key);
  50. const oldBook = this.books[meta.key];
  51. this.books[meta.key] = meta;
  52. if (oldBook && oldBook.data && oldBook.parsed) {
  53. this.books[meta.key].data = oldBook.data;
  54. this.books[meta.key].parsed = oldBook.parsed;
  55. }
  56. }
  57. }
  58. len = await bmRecentStore.length();
  59. for (let i = 0; i < len; i++) {
  60. const key = await bmRecentStore.key(i);
  61. let r = await bmRecentStore.getItem(key);
  62. this.recent[r.key] = r;
  63. }
  64. await this.cleanBooks();
  65. await this.cleanRecentBooks();
  66. this.booksCached = {};
  67. for (const key in this.books) {
  68. this.booksCached[key] = this.metaOnly(this.books[key]);
  69. }
  70. await bmCacheStore.setItem('books', this.booksCached);
  71. await bmCacheStore.setItem('recent', this.recent);
  72. }
  73. async cleanBooks() {
  74. while (1) {// eslint-disable-line no-constant-condition
  75. let size = 0;
  76. let min = Date.now();
  77. let toDel = null;
  78. for (let key in this.books) {
  79. let book = this.books[key];
  80. size += (book.length ? book.length : 0);
  81. if (book.addTime < min) {
  82. toDel = book;
  83. min = book.addTime;
  84. }
  85. }
  86. if (size > maxDataSize && toDel) {
  87. await this.delBook(toDel);
  88. } else {
  89. break;
  90. }
  91. }
  92. }
  93. async addBook(newBook, callback) {
  94. if (!this.books)
  95. await this.init();
  96. let meta = {url: newBook.url, path: newBook.path};
  97. meta.key = this.keyFromUrl(meta.url);
  98. meta.addTime = Date.now();
  99. const result = await this.parseBook(meta, newBook.data, callback);
  100. this.books[meta.key] = result;
  101. this.booksCached[meta.key] = this.metaOnly(result);
  102. await bmMetaStore.setItem(`bmMeta-${meta.key}`, this.metaOnly(result));
  103. await bmDataStore.setItem(`bmData-${meta.key}`, result.data);
  104. await bmCacheStore.setItem('books', this.booksCached);
  105. return result;
  106. }
  107. hasBookParsed(meta) {
  108. if (!this.books)
  109. return false;
  110. if (!meta.url)
  111. return false;
  112. if (!meta.key)
  113. meta.key = this.keyFromUrl(meta.url);
  114. let book = this.books[meta.key];
  115. return !!(book && book.parsed);
  116. }
  117. async getBook(meta, callback) {
  118. if (!this.books)
  119. await this.init();
  120. let result = undefined;
  121. if (!meta.key)
  122. meta.key = this.keyFromUrl(meta.url);
  123. result = this.books[meta.key];
  124. if (result && !result.data) {
  125. result.data = await bmDataStore.getItem(`bmData-${meta.key}`);
  126. this.books[meta.key] = result;
  127. }
  128. if (result && !result.parsed) {
  129. result = await this.parseBook(result, result.data, callback);
  130. this.books[meta.key] = result;
  131. }
  132. return result;
  133. }
  134. async delBook(meta) {
  135. if (!this.books)
  136. await this.init();
  137. await bmMetaStore.removeItem(`bmMeta-${meta.key}`);
  138. await bmDataStore.removeItem(`bmData-${meta.key}`);
  139. delete this.books[meta.key];
  140. delete this.booksCached[meta.key];
  141. await bmCacheStore.setItem('books', this.booksCached);
  142. }
  143. async parseBook(meta, data, callback) {
  144. if (!this.books)
  145. await this.init();
  146. const parsed = new BookParser(this.settings);
  147. const parsedMeta = await parsed.parse(data, callback);
  148. const result = Object.assign({}, meta, parsedMeta, {
  149. length: data.length,
  150. textLength: parsed.textLength,
  151. data,
  152. parsed
  153. });
  154. return result;
  155. }
  156. metaOnly(book) {
  157. let result = Object.assign({}, book);
  158. delete result.data;
  159. delete result.parsed;
  160. return result;
  161. }
  162. keyFromUrl(url) {
  163. return utils.stringToHex(url);
  164. }
  165. async setRecentBook(value, noTouch) {
  166. if (!this.recent)
  167. await this.init();
  168. const result = this.metaOnly(value);
  169. if (!noTouch)
  170. Object.assign(result, {touchTime: Date.now()});
  171. if (result.textLength && !result.bookPos && result.bookPosPercent)
  172. result.bookPos = Math.round(result.bookPosPercent*result.textLength);
  173. this.recent[result.key] = result;
  174. await bmRecentStore.setItem(result.key, result);
  175. //кэшируем, аккуратно
  176. if (!(this.recentLast && this.recentLast.key == result.key)) {
  177. await bmCacheStore.setItem('recent', this.recent);
  178. }
  179. this.recentLast = result;
  180. await bmCacheStore.setItem('recent-last', this.recentLast);
  181. this.recentChanged1 = true;
  182. this.recentChanged2 = true;
  183. return result;
  184. }
  185. async getRecentBook(value) {
  186. if (!this.recent)
  187. await this.init();
  188. return this.recent[value.key];
  189. }
  190. async delRecentBook(value) {
  191. if (!this.recent)
  192. await this.init();
  193. await bmRecentStore.removeItem(value.key);
  194. delete this.recent[value.key];
  195. await bmCacheStore.setItem('recent', this.recent);
  196. this.recentChanged1 = true;
  197. this.recentChanged2 = true;
  198. }
  199. async cleanRecentBooks() {
  200. if (!this.recent)
  201. await this.init();
  202. if (Object.keys(this.recent).length > 1000) {
  203. let min = Date.now();
  204. let found = null;
  205. for (let key in this.recent) {
  206. const book = this.recent[key];
  207. if (book.touchTime < min) {
  208. min = book.touchTime;
  209. found = book;
  210. }
  211. }
  212. if (found) {
  213. await this.delRecentBook(found);
  214. await this.cleanRecentBooks();
  215. }
  216. }
  217. }
  218. mostRecentBook() {
  219. if (!this.recentChanged1 && this.mostRecentCached) {
  220. return this.mostRecentCached;
  221. }
  222. let max = 0;
  223. let result = null;
  224. for (let key in this.recent) {
  225. const book = this.recent[key];
  226. if (book.touchTime > max) {
  227. max = book.touchTime;
  228. result = book;
  229. }
  230. }
  231. this.mostRecentCached = result;
  232. this.recentChanged1 = false;
  233. return result;
  234. }
  235. getSortedRecent() {
  236. if (!this.recentChanged2 && this.sortedRecentCached) {
  237. return this.sortedRecentCached;
  238. }
  239. let result = Object.values(this.recent);
  240. result.sort((a, b) => b.touchTime - a.touchTime);
  241. this.sortedRecentCached = result;
  242. this.recentChanged2 = false;
  243. return result;
  244. }
  245. }
  246. export default new BookManager();