@internetarchive/ia-book-actions 0.0.28 → 0.0.29-alpha1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/demo/index.html CHANGED
@@ -94,6 +94,12 @@
94
94
  canBrowseAndBorrow,
95
95
  } from '../src/assets/data/lending-get-status-service.js';
96
96
  import { ModalConfig } from '@internetarchive/modal-manager';
97
+ import { LocalCache } from '@internetarchive/local-cache';
98
+
99
+ const localCache = new LocalCache({
100
+ namespace: '1HourLoanStorage',
101
+ defaultTTL: 1 * 60, // 1 minute
102
+ });
97
103
 
98
104
  const userid = '@neeraj-archive';
99
105
  const identifier = 'naturalhistoryof00unse_4111';
@@ -121,8 +127,32 @@
121
127
  iaBookActions.lendingBarPostInit = lendingBarPostInit;
122
128
  iaBookActions.tokenDelay = 2000; // 2 seconds
123
129
  iaBookActions.returnUrl = 'https://openlibrary.org';
130
+ // iaBookActions.localCache = localCache;
131
+ iaBookActions.autoRenewTimeConfig = {
132
+ totalTime: 60, // 60 second = 1 min
133
+ autoRenewCheckerAtLast: 10, // totalTime - 10th minute
134
+ autoRenewVisitedInLast: 15, // within last 15 second/minute
135
+ };
124
136
 
125
137
  let lendingStatus1 = iaBookActions.lendingStatus;
138
+ let secondsLeftOnLoan = 60;
139
+
140
+ document.querySelector('#flip-page').addEventListener('click', async (e) => {
141
+ try {
142
+ // set pageFlipTime time in localStorage
143
+ await localCache.set({
144
+ key: `${identifier}-pageFlipTime`,
145
+ value: new Date(), // current time
146
+ })
147
+
148
+ // dispatch event to say book page has flipped
149
+ document.querySelector("ia-book-actions").dispatchEvent(
150
+ new CustomEvent("bookPageFlip", {
151
+ detail: { bookPageChange: true },
152
+ })
153
+ );
154
+ } catch (error) {}
155
+ });
126
156
 
127
157
  document.querySelectorAll('.titleBar input[type=checkbox]').forEach((item) => {
128
158
  item.addEventListener('click', (e) => {
@@ -134,6 +164,21 @@
134
164
  });
135
165
  });
136
166
 
167
+ document.querySelectorAll('.autoRenew input[type=checkbox]').forEach((item) => {
168
+ item.addEventListener('click', (e) => {
169
+ if (e.target.checked) {
170
+ iaBookActions.autoRenew = true;
171
+ iaBookActions.resetTimerCountdown = true;
172
+ lendingStatus1.secondsLeftOnLoan = secondsLeftOnLoan;
173
+ } else {
174
+ iaBookActions.autoRenew = false;
175
+ }
176
+
177
+ let lending = {...defaultLendingStatus, ...lendingStatus1};
178
+ iaBookActions.lendingStatus = lending;
179
+ });
180
+ });
181
+
137
182
  document.querySelectorAll('.errorEnable input[type=checkbox]').forEach((item) => {
138
183
  if (window.location.href.indexOf('?error=true') !== -1) {
139
184
  item.checked = true;
@@ -187,12 +232,23 @@
187
232
  });
188
233
 
189
234
  document.querySelectorAll('.availableToBrowse input[type=radio]').forEach((item) => {
190
- item.addEventListener('click', (e) => {
235
+ item.addEventListener('click', async (e) => {
191
236
  if (e.target.value === 'user_has_browsed') {
192
237
  lendingStatus1.user_has_browsed = true;
193
238
  lendingStatus1.available_to_browse = false;
194
- lendingStatus1.secondsLeftOnLoan = 10;
239
+ lendingStatus1.secondsLeftOnLoan = secondsLeftOnLoan;
195
240
  lendingStatus1.browsingExpired = false;
241
+
242
+ try {
243
+ // set a value
244
+ await localCache.set({
245
+ key: `${identifier}-loanTime`,
246
+ value: new Date(), // current time
247
+ })
248
+
249
+ await localCache.delete(`${identifier}-pageFlipTime`);
250
+ } catch (error) {}
251
+
196
252
  } else if(e.target.value === 'browsingExpired') {
197
253
  lendingStatus1.user_has_browsed = true;
198
254
  lendingStatus1.available_to_browse = false;
@@ -272,6 +328,10 @@
272
328
  <table class="initial">
273
329
  <tr colspan='5'>
274
330
  <td class="errorEnable"><label><input type="checkbox" name="errorEnable" value="errorEnable" />Do you want to see error response?</label></td>
331
+ <td class="autoRenew"><label><input type="checkbox" name="autoRenew" value="autoRenew" />Do you want to auto-renew 1 hour</label></td>
332
+ </tr>
333
+ <tr>
334
+ <td><button id="flip-page">Flip page</button></td>
275
335
  </tr>
276
336
  <tr>
277
337
  <td class="userState">
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@internetarchive/ia-book-actions",
3
- "version": "0.0.28",
3
+ "version": "0.0.29-alpha1",
4
4
  "description": "Bookreader actions for borrowable book",
5
5
  "author": "Internet Archive",
6
6
  "license": "AGPL-3.0-only",
@@ -11,8 +11,8 @@
11
11
  },
12
12
  "scripts": {
13
13
  "start": "web-dev-server",
14
- "lint": "eslint --ext .js,.html . --ignore-path .gitignore && prettier \"**/*.js\" --check --ignore-path .gitignore",
15
- "format": "eslint --ext .js,.html . --fix --ignore-path .gitignore && prettier \"**/*.js\" --write --ignore-path .gitignore",
14
+ "lint": "eslint --ext .js",
15
+ "format": "eslint --ext .js,",
16
16
  "test": "yarn run lint && yarn test:fast",
17
17
  "test:fast": "web-test-runner --coverage --playwright --browsers chromium firefox webkit",
18
18
  "test:watch": "web-test-runner --watch --playwright --browsers chromium firefox webkit"
@@ -54,7 +54,6 @@
54
54
  },
55
55
  "husky": {
56
56
  "hooks": {
57
- "pre-commit": "lint-staged"
58
57
  }
59
58
  },
60
59
  "lint-staged": {
@@ -0,0 +1,58 @@
1
+ import { css } from 'lit';
2
+
3
+ export default timerCountDownStyle = css`
4
+ :host {
5
+ right: 5px;
6
+ font-size: 14px;
7
+ position: absolute;
8
+ }
9
+ #countdown1 {
10
+ position: relative;
11
+ margin: auto;
12
+ margin-top: 100px;
13
+ height: 40px;
14
+ width: 40px;
15
+ text-align: center;
16
+ }
17
+
18
+ #countdown-number {
19
+ color: white;
20
+ display: inline-block;
21
+ line-height: 40px;
22
+ margin-right: 12px;
23
+ }
24
+
25
+ svg {
26
+ position: absolute;
27
+ top: 0;
28
+ right: 0;
29
+ width: 40px;
30
+ height: 40px;
31
+ transform: rotateY(-180deg) rotateZ(-90deg);
32
+ }
33
+
34
+ svg circle {
35
+ stroke-dasharray: 113px;
36
+ stroke-dashoffset: 0px;
37
+ stroke-linecap: round;
38
+ stroke-width: 3px;
39
+ stroke: white;
40
+ fill: none;
41
+ animation: countdown 60s linear infinite forwards;
42
+ }
43
+
44
+ @keyframes countdown {
45
+ from {
46
+ stroke-dashoffset: 0px;
47
+ }
48
+ to {
49
+ stroke-dashoffset: 113px;
50
+ }
51
+ }
52
+ .hidden {
53
+ display: none;
54
+ }
55
+ .visible {
56
+ display: inline-block;
57
+ }
58
+ `;
@@ -28,6 +28,7 @@ export class CollapsibleActionGroup extends ActionsHandler {
28
28
  dropdownArrow: { type: String },
29
29
  disabled: { type: Boolean },
30
30
  returnUrl: { type: String },
31
+ browseAgainNow: { type: Boolean },
31
32
  };
32
33
  }
33
34
 
@@ -47,6 +48,7 @@ export class CollapsibleActionGroup extends ActionsHandler {
47
48
  this.loaderIcon = 'https://archive.org/upload/images/tree/loading.gif';
48
49
  this.disabled = false;
49
50
  this.returnUrl = '';
51
+ this.browseAgainNow = false;
50
52
  }
51
53
 
52
54
  updated(changed) {
@@ -56,6 +58,16 @@ export class CollapsibleActionGroup extends ActionsHandler {
56
58
  ) {
57
59
  this.resetActions();
58
60
  }
61
+
62
+ if (this.browseAgainNow === true) {
63
+ this.dispatchEvent(
64
+ new CustomEvent('autoBrowseBook', {
65
+ detail: {
66
+ event: { 'autoRenewed1Hour': 'browseBook' },
67
+ },
68
+ })
69
+ );
70
+ }
59
71
  }
60
72
 
61
73
  /**
@@ -55,7 +55,7 @@ export class InfoIcon extends LitElement {
55
55
  .more-info-icon.mobile {
56
56
  position: absolute;
57
57
  top: 4px;
58
- right: 10px;
58
+ right: 55px;
59
59
  margin-top: 15px;
60
60
  }
61
61
  .hidden {
@@ -0,0 +1,127 @@
1
+ import { html, css, LitElement } from 'lit';
2
+
3
+ export default class TimerCountdown extends LitElement {
4
+ static get properties() {
5
+ return {
6
+ time: { type: Number },
7
+ autoRenewCheckerAtLast: { type: Number },
8
+ resetTimerCountdown: { type: Boolean },
9
+ };
10
+ }
11
+
12
+ constructor() {
13
+ super();
14
+ this.time = 60;
15
+ this.autoRenewCheckerAtLast = 0;
16
+ this.timerInterval = undefined;
17
+ this.resetTimerCountdown = false;
18
+ }
19
+
20
+ disconnectedCallback() {
21
+ clearInterval(this.timerInterval)
22
+ }
23
+
24
+ firstUpdated() {
25
+ this.timerCountdown();
26
+ }
27
+
28
+ updated(changed) {
29
+ if (changed.has('resetTimerCountdown')) {
30
+ clearInterval(this.timerInterval);
31
+ this.timerCountdown()
32
+ }
33
+ }
34
+
35
+ timerCountdown() {
36
+ this.timerInterval = setInterval(() => {
37
+ this.time -= 1;
38
+
39
+ // execute 50th minute check
40
+ if (this.time === this.autoRenewCheckerAtLast) {
41
+ this.dispatchEvent(
42
+ new CustomEvent('autoReturnWarning', {
43
+ detail: {
44
+ remainingT: this.time
45
+ },
46
+ bubbles: true,
47
+ composed: true,
48
+ })
49
+ );
50
+ }
51
+
52
+ if (this.time === 0) clearInterval(this.timerInterval);
53
+
54
+ }, 1000);
55
+ }
56
+
57
+
58
+ render() {
59
+ return html`<div id="countdown">
60
+ <div id="countdown-number">${this.time}</div>
61
+ <svg>
62
+ <circle r="18" cx="20" cy="20"></circle>
63
+ </svg>
64
+ </div>`
65
+ }
66
+
67
+ static get styles() {
68
+ return css`
69
+ :host {
70
+ right: 5px;
71
+ font-size: 14px;
72
+ position: absolute;
73
+ }
74
+ #countdown1 {
75
+ position: relative;
76
+ margin: auto;
77
+ margin-top: 100px;
78
+ height: 40px;
79
+ width: 40px;
80
+ text-align: center;
81
+ }
82
+
83
+ #countdown-number {
84
+ color: white;
85
+ display: inline-block;
86
+ line-height: 40px;
87
+ margin-right: 12px;
88
+ }
89
+
90
+ svg {
91
+ position: absolute;
92
+ top: 0;
93
+ right: 0;
94
+ width: 40px;
95
+ height: 40px;
96
+ transform: rotateY(-180deg) rotateZ(-90deg);
97
+ }
98
+
99
+ svg circle {
100
+ stroke-dasharray: 113px;
101
+ stroke-dashoffset: 0px;
102
+ stroke-linecap: round;
103
+ stroke-width: 3px;
104
+ stroke: white;
105
+ fill: none;
106
+ animation: countdown 60s linear infinite forwards;
107
+ }
108
+
109
+ @keyframes countdown {
110
+ from {
111
+ stroke-dashoffset: 0px;
112
+ }
113
+ to {
114
+ stroke-dashoffset: 113px;
115
+ }
116
+ }
117
+ .hidden {
118
+ display: none;
119
+ }
120
+ .visible {
121
+ display: inline-block;
122
+ }
123
+ `;
124
+ }
125
+ }
126
+
127
+ window.customElements.define('timer-countdown', TimerCountdown);
@@ -0,0 +1,60 @@
1
+ import { html, css, LitElement, nothing } from 'lit';
2
+
3
+ export class ToastMessage extends LitElement {
4
+ static get properties() {
5
+ return {
6
+ texts: { type: String },
7
+ dismisOnClick: { type: Function },
8
+ hideToast: { type: Boolean },
9
+ };
10
+ }
11
+
12
+ constructor() {
13
+ super();
14
+ this.texts = '';
15
+ this.textClass = '';
16
+ this.hideToast = false;
17
+ }
18
+
19
+ render() {
20
+ return !this.hideToast
21
+ ? html`
22
+ <span class="toast-message ${this.textClass}">${this.texts}</span>
23
+ `
24
+ : nothing;
25
+ }
26
+
27
+ static get styles() {
28
+ const heightFromTop = css`var(--messageHeightFromTop, 15%)`;
29
+
30
+ return css`
31
+ :host {
32
+ display: inline-block;
33
+ }
34
+ .toast-message {
35
+ z-index: 2;
36
+ position: absolute;
37
+ top: ${heightFromTop};
38
+ font-size: 1.4rem;
39
+ color: #fff;
40
+ left: 50%;
41
+ right: 50%;
42
+ background: #333;
43
+ border: 1px solid #fff;
44
+ border-radius: 5px;
45
+ box-shadow: 1px 1px 2px;
46
+ padding: 10px;
47
+ width: fit-content;
48
+ transform: translate(-50%, -50%);
49
+ }
50
+ .hidden {
51
+ display: none;
52
+ }
53
+ .visible {
54
+ display: inline-block;
55
+ }
56
+ `;
57
+ }
58
+ }
59
+
60
+ window.customElements.define('toast-message', ToastMessage);
@@ -1,5 +1,6 @@
1
1
  import { LitElement } from 'lit';
2
2
 
3
+ import { LocalCache } from '@internetarchive/local-cache';
3
4
  import { URLHelper } from '../../config/url-helper.js';
4
5
  import ActionsHandlerService from './actions-handler-service.js';
5
6
  import * as Cookies from '../doc-cookies.js';
@@ -17,8 +18,14 @@ export default class ActionsHandler extends LitElement {
17
18
  super();
18
19
  this.identifier = '';
19
20
  this.ajaxTimeout = 6000;
20
- this.bindEvents();
21
21
  this.returnUrl = '';
22
+
23
+ this.localCache = new LocalCache({
24
+ namespace: '1HourLoanStorage',
25
+ defaultTTL: 1 * 30, // 0.5 minute
26
+ });
27
+
28
+ this.bindEvents();
22
29
  }
23
30
 
24
31
  sendEvent(eventCategory, eventAction) {
@@ -29,7 +36,9 @@ export default class ActionsHandler extends LitElement {
29
36
  );
30
37
  }
31
38
 
32
- bindEvents() {
39
+ async bindEvents() {
40
+ // console.log(await this.localCache.get('loanTime'));
41
+
33
42
  this.addEventListener('browseBook', ({ detail }) => {
34
43
  this.handleBrowseIt();
35
44
  this.setConsecutiveLoanCounts();
@@ -44,6 +53,14 @@ export default class ActionsHandler extends LitElement {
44
53
  this.sendEvent(category, action);
45
54
  });
46
55
 
56
+ this.addEventListener('autoBrowseBook', ({ detail }) => {
57
+ console.log('book has be renewed for you. thank you!!!');
58
+ this.handleAutoBrowseIt();
59
+ // this.setConsecutiveLoanCounts();
60
+ const { category, action } = detail.event;
61
+ this.sendEvent(category, action);
62
+ });
63
+
47
64
  this.addEventListener('returnNow', ({ detail }) => {
48
65
  this.handleReturnIt();
49
66
  const { category, action } = detail.event;
@@ -98,6 +115,7 @@ export default class ActionsHandler extends LitElement {
98
115
  handleBrowseIt() {
99
116
  const action = 'browse_book';
100
117
  this.dispatchToggleActionGroup();
118
+ this.setBrowseTimeSession()
101
119
 
102
120
  ActionsHandlerService({
103
121
  action,
@@ -111,6 +129,21 @@ export default class ActionsHandler extends LitElement {
111
129
  });
112
130
  }
113
131
 
132
+ handleAutoBrowseIt() {
133
+ const action = 'auto_browse';
134
+ this.setBrowseTimeSession()
135
+
136
+ ActionsHandlerService({
137
+ action,
138
+ identifier: this.identifier,
139
+ success: () => {},
140
+ error: data => {
141
+ this.dispatchActionError(action, data);
142
+ },
143
+ });
144
+ }
145
+
146
+
114
147
  handleReturnIt() {
115
148
  const action = 'return_loan';
116
149
  this.dispatchToggleActionGroup();
@@ -280,4 +313,16 @@ export default class ActionsHandler extends LitElement {
280
313
  '.archive.org'
281
314
  );
282
315
  }
316
+
317
+ async setBrowseTimeSession() {
318
+ try {
319
+ // set a value
320
+ await this.localCache.set({
321
+ key: `${this.identifier}-loanTime`,
322
+ value: new Date(), // current time
323
+ })
324
+
325
+ await this.localCache.delete(`${this.identifier}-pageFlipTime`);
326
+ } catch (error) {}
327
+ }
283
328
  }
@@ -0,0 +1,134 @@
1
+ import { nothing } from 'lit';
2
+
3
+ import ActionsHandlerService from './actions-handler/actions-handler-service.js';
4
+ import * as Cookies from './doc-cookies.js';
5
+
6
+ /**
7
+ * This class is used to create loan token for borrowed books
8
+ *
9
+ * ActionsHandlerService is a function being used to execute
10
+ */
11
+ export class OneHourAutoRenew {
12
+ constructor(pageClick, identifier, localCache, autoRenewTimeConfig) {
13
+ this.pageClick = pageClick;
14
+ this.identifier = identifier;
15
+ this.localCache = localCache;
16
+ this.autoRenewTimeConfig = autoRenewTimeConfig; // callback function to be called after loan token is created
17
+
18
+ this.autoReturnMessage = 'This book will be automatically returned in 15 seconds unless you turn a page.';
19
+ this.autoRenewMessage = 'This book has been renewed for another hour.';
20
+
21
+
22
+ this.resultRes = {
23
+ toastTexts: '',
24
+ hideToast: true,
25
+ };
26
+
27
+ return this.dd();
28
+ }
29
+
30
+ async dd() {
31
+ try {
32
+ const currentDate = new Date();
33
+
34
+ const {
35
+ totalTime, // 60
36
+ autoRenewCheckerAtLast, // 50
37
+ autoRenewVisitedInLast, // 15
38
+ } = this.autoRenewTimeConfig;
39
+
40
+ const loanTime = await this.localCache.get(`${this.identifier}-loanTime`);
41
+ const lastPageFlipTime = await this.localCache.get(`${this.identifier}-pageFlipTime`);
42
+
43
+ const lastFlipTimeFrame = await this.changeTime(
44
+ currentDate,
45
+ autoRenewVisitedInLast,
46
+ 'sub'
47
+ ); // 15 seconds
48
+
49
+ console.log(lastPageFlipTime, lastFlipTimeFrame)
50
+
51
+ // if page is not flipped in last 15 minutes,
52
+ // instantaly renew it if user viewed new page in last 10 minutes
53
+ if (this.pageClick === true) {
54
+ const lastTimeFrame = await this.changeTime(
55
+ loanTime,
56
+ totalTime - autoRenewCheckerAtLast,
57
+ 'add'
58
+ ); // 50 seconds
59
+ console.log('page flipped!')
60
+
61
+ if (currentDate >= lastTimeFrame) {
62
+ console.log('1 YES NOW BORROW IT AGAIN NOW!');
63
+ this.toastTexts = this.autoRenewMessage;
64
+ this.hideToast = false;
65
+ }
66
+
67
+ return nothing // early return
68
+ }
69
+
70
+ console.log(lastPageFlipTime, lastFlipTimeFrame)
71
+ if (lastPageFlipTime === undefined) { // not viewed
72
+ console.log('2 DON\'T BORROW IT!');
73
+ this.resultRes.toastTexts = this.autoReturnMessage;
74
+ this.resultRes.hideToast = false;
75
+ } else if (lastPageFlipTime >= lastFlipTimeFrame) { // viewed in last time frame
76
+ console.log('3 YES BORROW IT AGAIN!');
77
+ this.resultRes.toastTexts = this.autoRenewMessage;
78
+ this.resultRes.hideToast = false;
79
+ this.toastTexts = this.autoRenewMessage;
80
+ // this.browseAgainNow = true;
81
+ this.hideToast = false;
82
+ // await this.browseHasRenew();
83
+ } else if (lastPageFlipTime <= lastFlipTimeFrame) { // viewed but not in last time frame
84
+ console.log('4 DON\'T BORROW IT!');
85
+ this.resultRes.toastTexts = this.autoReturnMessage;
86
+ this.resultRes.hideToast = false;
87
+ }
88
+
89
+ // console.log(this.resultRes)
90
+ return this.resultRes;
91
+
92
+ } catch (error) {
93
+ console.log(error)
94
+ }
95
+ }
96
+
97
+ async changeTime(date, minutes, op) {
98
+ if (date === undefined) return undefined;
99
+
100
+ if (op === 'sub') {
101
+ return new Date(date.getTime() - minutes * 1000);
102
+ }
103
+
104
+ return new Date(date.getTime() + minutes * 1000);
105
+ }
106
+
107
+ sendEvent(eventCategory, eventAction) {
108
+ window?.archive_analytics?.send_event(
109
+ eventCategory,
110
+ eventAction,
111
+ `identifier=${this.identifier}`
112
+ );
113
+ }
114
+
115
+ async handleAutoRenew() {
116
+ const action = 'renew_loan';
117
+ ActionsHandlerService({
118
+ identifier: this.identifier,
119
+ action,
120
+ error: data => {
121
+ window?.Sentry?.captureMessage(
122
+ 'handleAutoRenew error',
123
+ JSON.stringify(data)
124
+ );
125
+ // this.errorCallback({ detail: { action, data } });
126
+ // send LendingServiceError to GA
127
+ this.sendEvent('handleAutoRenew', action);
128
+ },
129
+ success: () => {
130
+ return 'success';
131
+ },
132
+ });
133
+ }
134
+ }
@@ -1,17 +1,21 @@
1
1
  /* eslint-disable camelcase */
2
- import { html, css, LitElement } from 'lit';
2
+ import { html, css, LitElement, nothing } from 'lit';
3
3
 
4
4
  import { SharedResizeObserver } from '@internetarchive/shared-resize-observer';
5
5
  import { ModalConfig } from '@internetarchive/modal-manager';
6
+ import { LocalCache } from '@internetarchive/local-cache';
6
7
 
7
8
  import './components/collapsible-action-group.js';
8
9
  import './components/book-title-bar.js';
9
10
  import './components/text-group.js';
10
11
  import './components/info-icon.js';
12
+ import './components/timer-countdown.js';
13
+ import './components/toast-message.js';
11
14
 
12
15
  import { GetLendingActions } from './core/services/get-lending-actions.js';
13
16
  import { mobileContainerWidth } from './core/config/constants.js';
14
17
  import { LoanTokenPoller } from './core/services/loan-token-poller.js';
18
+ import { OneHourAutoRenew } from './core/services/one-hour-auto-renew.js';
15
19
 
16
20
  export const events = {
17
21
  browseExpired: 'IABookReader:BrowsingHasExpired',
@@ -32,10 +36,17 @@ export default class IABookActions extends LitElement {
32
36
  attribute: false,
33
37
  },
34
38
  barType: { type: String },
39
+ autoRenew: { type: Boolean },
35
40
  sharedObserver: { attribute: false },
36
41
  disableActionGroup: { type: Boolean },
37
42
  modal: { Object },
38
43
  tokenDelay: { type: Number },
44
+ toastTexts: { type: String },
45
+ remainingTime: { type: Number },
46
+ resetTimerCountdown: { type: Boolean },
47
+ localCache: { type: Object },
48
+ autoRenewTimeConfig: { type: Object },
49
+ browseAgainNow: { type: Boolean },
39
50
  };
40
51
  }
41
52
 
@@ -50,10 +61,16 @@ export default class IABookActions extends LitElement {
50
61
  this.bwbPurchaseUrl = '';
51
62
  this.lendingBarPostInit = () => {};
52
63
  this.barType = 'action'; // 'title'|'action'
64
+ this.autoRenew = false;
53
65
  this.sharedObserver = undefined;
54
66
  this.disableActionGroup = false;
55
67
  this.modal = undefined;
56
68
  this.tokenDelay = 120000; // 2 minutes
69
+ this.localCache = new LocalCache({
70
+ namespace: '1HourLoanStorage',
71
+ defaultTTL: 1 * 60, // 1 minute
72
+ }),
73
+ this.autoRenewTimeConfig = {},
57
74
 
58
75
  // private props
59
76
  this.primaryActions = [];
@@ -63,6 +80,44 @@ export default class IABookActions extends LitElement {
63
80
  this.lendingOptions = {};
64
81
  this.borrowType = ''; // (browsed|borrowed)
65
82
  this.consecutiveLoanCounts = 1; // consecutive loan count
83
+ this.browseAgainNow = false;
84
+ this.browserTimer = undefined;
85
+
86
+ // show toast-message for auto return message
87
+ this.hideToast = true;
88
+ this.autoReturnMessage = 'This book will be automatically returned in 15 seconds unless you turn a page.';
89
+ this.autoRenewMessage = 'This book has been renewed for another hour.';
90
+
91
+ // dispatched this event from timer-countdown
92
+ this.addEventListener('autoReturnWarning', event => {
93
+ // const dd = this.autoRenew1 = new OneHourAutoRenew(
94
+ // event.detail.bookPageChange,
95
+ // this.identifier,
96
+ // this.localCache,
97
+ // this.autoRenewTimeConfig,
98
+ // );
99
+ // this.toastTexts = dd.resultRes.toastTexts;
100
+ // this.hideToast = dd.resultRes.hideToast;
101
+ this.handleBookAutoRenew(event);
102
+ });
103
+
104
+ // dispatched this event from bookreader side
105
+ this.addEventListener('bookPageFlip', event => {
106
+ // console.log(e)
107
+ // const dd = this.autoRenew1 = new OneHourAutoRenew(
108
+ // event.detail.bookPageChange,
109
+ // this.identifier,
110
+ // this.localCache,
111
+ // this.autoRenewTimeConfig,
112
+ // );
113
+ // this.toastTexts = dd.resultRes.toastTexts;
114
+ // this.hideToast = dd.resultRes.hideToast;
115
+ // console.log(dd.resultRes)
116
+ this.handleBookAutoRenew(event);
117
+ // this.browseAgainNow = true;
118
+ });
119
+
120
+ this.resetTimerCountdown = false;
66
121
  }
67
122
 
68
123
  disconnectedCallback() {
@@ -84,33 +139,136 @@ export default class IABookActions extends LitElement {
84
139
  this.update();
85
140
  }
86
141
 
142
+ if (changed.has('autoRenew')) {
143
+ this.resetTimerCountdown = true;
144
+ }
87
145
  if (changed.has('sharedObserver')) {
88
146
  this.disconnectResizeObserver();
89
147
  this.setupResizeObserver();
90
148
  }
91
149
  }
92
150
 
93
- browseHasExpired() {
151
+ async browseHasExpired() {
94
152
  const currStatus = { ...this.lendingStatus, browsingExpired: true };
95
153
  this.lendingStatus = currStatus;
154
+
155
+ // remove respected key:value
156
+ await this.localCache.delete(`${this.identifier}-loanTime`);
157
+ await this.localCache.delete(`${this.identifier}-pageFlipTime`);
158
+
159
+ // show message after browsed book is expired.
160
+ this.toastTexts = 'This book has been automatically returned due to inactivity.';
161
+ }
162
+
163
+ async browseHasRenew() {
164
+ const currStatus = {
165
+ ...this.lendingStatus,
166
+ user_has_browsed: true,
167
+ browsingExpired: false,
168
+ secondsLeftOnLoan: 61
169
+ };
170
+ this.lendingStatus = currStatus;
171
+
172
+ this.startBrowseTimer();
96
173
  }
97
174
 
98
175
  startBrowseTimer() {
176
+ clearTimeout(this.browserTimer);
99
177
  const {
100
178
  browsingExpired,
101
179
  user_has_browsed,
102
180
  secondsLeftOnLoan,
103
181
  } = this.lendingStatus;
182
+ console.log(this.lendingStatus);
104
183
  if (!user_has_browsed || browsingExpired) {
184
+ console.log('attempted renew');
105
185
  return;
106
186
  }
107
187
 
188
+ // expired book and show browse again button
108
189
  const timeLeft = secondsLeftOnLoan * 1000;
109
- setTimeout(() => {
190
+ this.browserTimer = setTimeout(() => {
110
191
  this.browseHasExpired();
111
192
  }, timeLeft);
112
193
  }
113
194
 
195
+ async handleBookAutoRenew(event) {
196
+ try {
197
+ const bookPageChange = event.detail.bookPageChange;
198
+ const currentDate = new Date();
199
+
200
+ const {
201
+ totalTime, // 60
202
+ autoRenewCheckerAtLast, // 50
203
+ autoRenewVisitedInLast, // 15
204
+ } = this.autoRenewTimeConfig;
205
+
206
+ const loanTime = await this.localCache.get(`${this.identifier}-loanTime`);
207
+ const lastPageFlipTime = await this.localCache.get(`${this.identifier}-pageFlipTime`);
208
+
209
+ const lastFlipTimeFrame = await this.changeTime(
210
+ currentDate,
211
+ autoRenewVisitedInLast,
212
+ 'sub'
213
+ ); // 15 seconds
214
+
215
+ console.log(lastPageFlipTime, lastFlipTimeFrame)
216
+
217
+ // if page is not flipped in last 15 minutes,
218
+ // instantaly renew it if user viewed new page in last 10 minutes
219
+ if (bookPageChange === true) {
220
+ const lastTimeFrame = await this.changeTime(
221
+ loanTime,
222
+ totalTime - autoRenewCheckerAtLast,
223
+ 'add'
224
+ ); // 50 seconds
225
+ console.log('page flipped!')
226
+
227
+ if (currentDate >= lastTimeFrame) {
228
+ console.log('1 YES NOW BORROW IT AGAIN NOW!');
229
+ this.toastTexts = this.autoRenewMessage;
230
+ this.browseAgainNow = true;
231
+ this.hideToast = false;
232
+ await this.browseHasRenew();
233
+ }
234
+
235
+ return nothing // early return
236
+ }
237
+
238
+ console.log(lastPageFlipTime, lastFlipTimeFrame)
239
+ if (lastPageFlipTime === undefined) { // not viewed
240
+ console.log('2 DON\'T BORROW IT!');
241
+ this.toastTexts = this.autoReturnMessage;
242
+ this.hideToast = false;
243
+ } else if (lastPageFlipTime >= lastFlipTimeFrame) { // viewed in last time frame
244
+ console.log('3 YES BORROW IT AGAIN!');
245
+ this.toastTexts = this.autoRenewMessage;
246
+ this.browseAgainNow = true;
247
+ this.hideToast = false;
248
+ await this.browseHasRenew();
249
+ } else if (lastPageFlipTime <= lastFlipTimeFrame) { // viewed but not in last time frame
250
+ console.log('4 DON\'T BORROW IT!');
251
+ this.toastTexts = this.autoReturnMessage;
252
+ this.hideToast = false;
253
+ } else {
254
+ this.browseAgainNow = true;
255
+ console.log('5 YES NOW BORROW IT AGAIN NOW!');
256
+ }
257
+ } catch (error) {
258
+ console.log(error)
259
+ }
260
+ }
261
+
262
+ async changeTime(date, minutes, op) {
263
+ if (date === undefined) return undefined;
264
+
265
+ if (op === 'sub') {
266
+ return new Date(date.getTime() - minutes * 1000);
267
+ }
268
+
269
+ return new Date(date.getTime() + minutes * 1000);
270
+ }
271
+
114
272
  /** SharedObserver resize handler */
115
273
  handleResize(entry) {
116
274
  // if you are observing multiple targets,
@@ -164,6 +322,7 @@ export default class IABookActions extends LitElement {
164
322
  });
165
323
 
166
324
  this.borrowType = actions.borrowType;
325
+ this.remainingTime = this.lendingStatus.secondsLeftOnLoan;
167
326
 
168
327
  const hasExpired =
169
328
  'browsingExpired' in this.lendingStatus &&
@@ -216,6 +375,26 @@ export default class IABookActions extends LitElement {
216
375
  ></book-title-bar>`;
217
376
  }
218
377
 
378
+ get timerCountdownTemplate() {
379
+ return this.borrowType === 'browsed'
380
+ ? html`<timer-countdown
381
+ time=${Number(this.remainingTime)}
382
+ .autoRenewCheckerAtLast=${this.autoRenewTimeConfig.autoRenewCheckerAtLast}
383
+ ?resetTimerCountdown=${this.resetTimerCountdown}
384
+ ></timer-countdown>`
385
+ : nothing;
386
+ }
387
+
388
+ get toastMessageTemplate() {
389
+ return html`
390
+ <toast-message
391
+ .texts=${this.toastTexts}
392
+ .dismisOnClick="1"
393
+ ?hideToast=${this.hideToast}
394
+ ></toast-message>
395
+ `;
396
+ }
397
+
219
398
  get bookActionBar() {
220
399
  return html`
221
400
  <collapsible-action-group
@@ -227,13 +406,16 @@ export default class IABookActions extends LitElement {
227
406
  .width=${this.width}
228
407
  .borrowType=${this.borrowType}
229
408
  .returnUrl=${this.returnUrl}
409
+ .autoRenew=${this.autoRenew}
230
410
  ?hasAdminAccess=${this.hasAdminAccess}
231
411
  ?disabled=${this.disableActionGroup}
412
+ ?browseAgainNow=${this.browseAgainNow}
232
413
  @lendingActionError=${this.handleLendingActionError}
233
414
  @toggleActionGroup=${this.handleToggleActionGroup}
234
415
  >
235
416
  </collapsible-action-group>
236
417
  ${this.textGroupTemplate} ${this.infoIconTemplate}
418
+ ${this.timerCountdownTemplate} ${this.toastMessageTemplate}
237
419
  `;
238
420
  }
239
421
 
@@ -401,6 +583,10 @@ export default class IABookActions extends LitElement {
401
583
  justify-content: center;
402
584
  flex-wrap: wrap;
403
585
  }
586
+
587
+ toast-message {
588
+ --messageHeightFromTop: 18%;
589
+ }
404
590
  `;
405
591
  }
406
592
  }
@@ -1,146 +0,0 @@
1
- <!doctype html>
2
- <html lang="en-GB">
3
-
4
- <head>
5
- <meta charset="utf-8">
6
- <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
7
- <style>
8
- html {
9
- font-size: 10px;
10
- /* This is to match petabox's base font size */
11
- }
12
- body {
13
- margin: 0;
14
- text-align: center;
15
- font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
16
- }
17
- #demo {
18
- height: 50px;
19
- }
20
- ia-book-actions {
21
- --white: #fff;
22
- --black: #000;
23
- --primaryBGColor: var(--black);
24
- --secondaryBGColor: #222;
25
- --tertiaryBGColor: #333;
26
- --primaryTextColor: var(--white);
27
- --primaryCTAFill: #194880;
28
- --primaryCTABorder: #c5d1df;
29
- --secondaryCTAFill: #333;
30
- --secondaryCTABorder: #999;
31
- --secondaryCTAFillRGB: 51, 51, 51;
32
- --primaryErrorCTAFill: #e51c26;
33
- --primaryErrorCTABorder: #f8c6c8;
34
- --primaryCTAFillRGB: 25, 72, 128;
35
- --primaryErrorCTAFillRGB: 229, 28, 38;
36
- --primaryDisableCTAFill: #767676;
37
- }
38
-
39
- fieldset {
40
- width: fit-content;
41
- margin-top: 50px;
42
- }
43
- fieldset legend {
44
- text-align: left;
45
- font-size: 12px;
46
- }
47
- td {
48
- color: white;
49
- font-size: 14px;
50
- border-radius: 5%;
51
- display: table-cell;
52
- text-align: initial;
53
- margin: 5px 0;
54
- width: max-content;
55
- display: block;
56
- }
57
- label {
58
- padding: 10px;
59
- display: block;
60
- cursor: pointer;
61
- margin: 2px;
62
- background: #4e545a;
63
- border-radius: 10px;
64
- }
65
- input[type="radio"], input[type="checkbox"] {
66
- margin-top: 0;
67
- vertical-align: middle;
68
- }
69
-
70
- .initial td {
71
- float: left;
72
- margin: 2px;
73
- }
74
-
75
- body.modal-manager-open {
76
- overflow: hidden;
77
- }
78
-
79
- modal-manager[mode='closed'] {
80
- display: none;
81
- }
82
- </style>
83
- </head>
84
-
85
- <body>
86
- <ia-bookreader class="focus-on-child-only" signedin="" fullscreen="">
87
- <div slot="header">
88
- <ia-book-actions></ia-book-actions>
89
- </div>
90
- <div slot="main">
91
- <div id="BookReader"></div>
92
- </div>
93
- </ia-bookreader>
94
-
95
-
96
- <script type="module">
97
- /* eslint-disable */
98
- import '@internetarchive/bookreader';
99
- import '@internetarchive/bookreader/BookReader/jquery-1.10.1.js';
100
- import '@internetarchive/bookreader/BookReader/BookReader.js';
101
- import '../src/ia-book-actions.js';
102
- import {
103
- defaultLendingStatus,
104
- canBrowseAndBorrow,
105
- } from '../src/assets/data/lending-get-status-service.js';
106
- import { ModalConfig } from '@internetarchive/modal-manager';
107
-
108
- const userid = '@neeraj-archive';
109
- const identifier = 'naturalhistoryof00unse_4111';
110
- let bwbPurchaseUrl = 'https://www.betterworldbooks.com/product/detail/cambridge-ancient-hist-v04-0521044863';
111
-
112
- let iaBookActions = document.querySelector('ia-book-actions');
113
-
114
- // for debugging
115
- window.iaBookActions = iaBookActions;
116
-
117
- const modalConfig = new ModalConfig();
118
- modalConfig.headerColor = '#d9534f';
119
-
120
- let lendingBarPostInit = function lendingBarPostInit() {
121
- setTimeout(function() {
122
- console.log('executed', 'br.init()');
123
- }, 100);
124
- }
125
-
126
- // set defaultLendingStatus for unavailable (without borrowables) book
127
- iaBookActions.userid = userid;
128
- iaBookActions.identifier = identifier;
129
- iaBookActions.bookTitle = 'Contemporary Black biography. Volume 39 : profiles from the interContemporary Black biography. Volume 39';
130
- iaBookActions.lendingStatus = canBrowseAndBorrow;
131
- iaBookActions.bwbPurchaseUrl = '';
132
- iaBookActions.modalConfig = modalConfig;
133
- iaBookActions.lendingBarPostInit = lendingBarPostInit;
134
- iaBookActions.tokenDelay = 2000; // 2 seconds
135
- iaBookActions.returnUrl = 'https://openlibrary.org';
136
-
137
- let lendingStatus1 = iaBookActions.lendingStatus;
138
-
139
- const manifest = await fetch('https://ia801302.us.archive.org/BookReader/BookReaderJSIA.php?id=goody&itemPath=/29/items/goody&server=ia801302.us.archive.org&format=jsonp&subPrefix=goody&requestUri=/details/goody/mode/1up%3Fview%3Dtheater%26ui%3Dembed%26wrapper%3Dfalse');
140
-
141
- console.log('manifest ****', manifest).then(res => res.json());
142
- </script>
143
-
144
- </div>
145
- </body>
146
- </html>