bookManager.js 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  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.parsed) {
  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}`, newBook.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.parsed) {
  125. const data = await bmDataStore.getItem(`bmData-${meta.key}`);
  126. result = await this.parseBook(result, data, callback);
  127. this.books[meta.key] = result;
  128. }
  129. return result;
  130. }
  131. async delBook(meta) {
  132. if (!this.books)
  133. await this.init();
  134. await bmMetaStore.removeItem(`bmMeta-${meta.key}`);
  135. await bmDataStore.removeItem(`bmData-${meta.key}`);
  136. delete this.books[meta.key];
  137. delete this.booksCached[meta.key];
  138. await bmCacheStore.setItem('books', this.booksCached);
  139. }
  140. async parseBook(meta, data, callback) {
  141. if (!this.books)
  142. await this.init();
  143. const parsed = new BookParser(this.settings);
  144. const parsedMeta = await parsed.parse(data, callback);
  145. const result = Object.assign({}, meta, parsedMeta, {
  146. length: data.length,
  147. textLength: parsed.textLength,
  148. parsed
  149. });
  150. return result;
  151. }
  152. metaOnly(book) {
  153. let result = Object.assign({}, book);
  154. delete result.data;//можно будет убрать эту строку со временем
  155. delete result.parsed;
  156. return result;
  157. }
  158. keyFromUrl(url) {
  159. return utils.stringToHex(url);
  160. }
  161. async setRecentBook(value, noTouch) {
  162. if (!this.recent)
  163. await this.init();
  164. const result = this.metaOnly(value);
  165. if (!noTouch)
  166. Object.assign(result, {touchTime: Date.now()});
  167. if (result.textLength && !result.bookPos && result.bookPosPercent)
  168. result.bookPos = Math.round(result.bookPosPercent*result.textLength);
  169. this.recent[result.key] = result;
  170. await bmRecentStore.setItem(result.key, result);
  171. //кэшируем, аккуратно
  172. if (!(this.recentLast && this.recentLast.key == result.key)) {
  173. await bmCacheStore.setItem('recent', this.recent);
  174. }
  175. this.recentLast = result;
  176. await bmCacheStore.setItem('recent-last', this.recentLast);
  177. this.recentChanged1 = true;
  178. this.recentChanged2 = true;
  179. return result;
  180. }
  181. async getRecentBook(value) {
  182. if (!this.recent)
  183. await this.init();
  184. return this.recent[value.key];
  185. }
  186. async delRecentBook(value) {
  187. if (!this.recent)
  188. await this.init();
  189. await bmRecentStore.removeItem(value.key);
  190. delete this.recent[value.key];
  191. await bmCacheStore.setItem('recent', this.recent);
  192. this.recentChanged1 = true;
  193. this.recentChanged2 = true;
  194. }
  195. async cleanRecentBooks() {
  196. if (!this.recent)
  197. await this.init();
  198. if (Object.keys(this.recent).length > 1000) {
  199. let min = Date.now();
  200. let found = null;
  201. for (let key in this.recent) {
  202. const book = this.recent[key];
  203. if (book.touchTime < min) {
  204. min = book.touchTime;
  205. found = book;
  206. }
  207. }
  208. if (found) {
  209. await this.delRecentBook(found);
  210. await this.cleanRecentBooks();
  211. }
  212. }
  213. }
  214. mostRecentBook() {
  215. if (!this.recentChanged1 && this.mostRecentCached) {
  216. return this.mostRecentCached;
  217. }
  218. let max = 0;
  219. let result = null;
  220. for (let key in this.recent) {
  221. const book = this.recent[key];
  222. if (book.touchTime > max) {
  223. max = book.touchTime;
  224. result = book;
  225. }
  226. }
  227. this.mostRecentCached = result;
  228. this.recentChanged1 = false;
  229. return result;
  230. }
  231. getSortedRecent() {
  232. if (!this.recentChanged2 && this.sortedRecentCached) {
  233. return this.sortedRecentCached;
  234. }
  235. let result = Object.values(this.recent);
  236. result.sort((a, b) => b.touchTime - a.touchTime);
  237. this.sortedRecentCached = result;
  238. this.recentChanged2 = false;
  239. return result;
  240. }
  241. }
  242. export default new BookManager();