bookManager.js 8.8 KB

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