Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed banners expiration #8

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion dist/amp-client.min.js

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion dist/amp-client.standalone.min.js

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@68publishers/amp-client",
"version": "1.6.1",
"version": "1.7.0-beta.6",
"description": "JS Client for 68publishers/amp",
"homepage": "http://www.68publishers.io/",
"main": "index.mjs",
Expand Down
10 changes: 10 additions & 0 deletions src/banner/banner-manager.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -138,4 +138,14 @@ export class BannerManager {

return null;
}

getBannerByPosition(positionCode) {
for (let banner of this.#banners) {
if (banner.position === positionCode) {
return banner;
}
}

return null;
}
}
108 changes: 87 additions & 21 deletions src/banner/closing/closed-banner-store.mjs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { EntryKey } from './closing-entry.mjs';

export class ClosedBannerStore {
#storage;
#key;
Expand Down Expand Up @@ -40,46 +42,101 @@ export class ClosedBannerStore {
return;
}

const currentItems = this.#loadedItems || [];
const newItems = null !== event.newValue && '' !== event.newValue ? event.newValue.split(',') : [];
const diff = newItems.filter(id => !currentItems.includes(id));
const currentItems = this.#loadedItems || {};
const newItems = null !== event.newValue && '' !== event.newValue ? JSON.parse(event.newValue) : {};

const currentKeys = Object.keys(currentItems);
const diffKeys = Object.keys(newItems)
.filter(key => !currentKeys.includes(key))
.map(key => EntryKey.tryParse(key))
.filter(key => null !== key);

this.#loadedItems = newItems;

if (0 < diff.length) {
onExternalChange(diff);
if (0 < diffKeys.length) {
onExternalChange(diffKeys);
}
});
}
}

persist(bannerId, closed) {
close(entries) {
const items = this.#getItems();
const index = items.indexOf(bannerId);
let changed = false;
const now = this.#getNow();
const changedKeys = [];

for (let i in entries) {
const entry = entries[i];

if (false !== entry.expiresAt && entry.expiresAt <= now) {
continue;
}

if (closed && -1 === index) {
items.push(bannerId);
changed = true;
} else if (!closed && -1 !== index) {
items.splice(index, 1);
changed = true;
const key = entry.key.toString();

if (!(key in items) || items[key] !== entry.expiresAt) {
items[key] = entry.expiresAt;
changedKeys.push(key);
}
}

if (!changed) {
if (0 >= changedKeys.length) {
return;
}

if (items.length > this.#maxItems) {
items.splice(items.length - this.#maxItems);
const length = Object.values(items).length;

if (length > this.#maxItems) {
Object.entries(items)
.filter(e => -1 === changedKeys.indexOf(e[0]))
.sort((a, b) => (a[1] || Number.MAX_SAFE_INTEGER) - (b[1] || Number.MAX_SAFE_INTEGER))
.slice(0, length - this.#maxItems)
.forEach(item => {
delete items[item[0]];
})
}

this.#loadedItems = items;
this.#flush();
}

isClosed(bannerId) {
return -1 !== this.#getItems().indexOf(bannerId);
release(keys) {
const items = this.#getItems();
let changed = false;

for (let i in keys) {
const key = keys[i];
const keyNative = key.toString();

if (keyNative in items) {
delete items[keyNative];
changed = true;
}
}

if (!changed) {
return;
}

this.#loadedItems = items;
this.#flush();
}

isClosed(key) {
const items = this.#getItems();
const keyNative = key.toString();

if (!(keyNative in items)) {
return false;
}

if (false === items[keyNative] || items[keyNative] > this.#getNow()) {
return true;
}

setTimeout(() => this.release([key]), 0);

return false;
}

#getItems() {
Expand All @@ -88,14 +145,19 @@ export class ClosedBannerStore {
}

const storedValue = this.#storage.getItem(this.#key);
const listOfItems = null !== storedValue && '' !== storedValue ? storedValue.split(',') : [];
let listOfItems = null !== storedValue && '' !== storedValue ? JSON.parse(storedValue) : {};

if (Array.isArray(listOfItems)) { // back compatibility - flush already persisted item
listOfItems = {};
this.#storage.setItem(this.#key, '{}');
}

return this.#loadedItems = listOfItems;
}

#flush() {
if (null !== this.#loadedItems) {
this.#storage.setItem(this.#key, this.#loadedItems.join(','));
this.#storage.setItem(this.#key, JSON.stringify(this.#loadedItems));
}
}

Expand All @@ -115,4 +177,8 @@ export class ClosedBannerStore {

return storage;
}

#getNow() {
return Math.round((+new Date() / 1000));
}
}
89 changes: 89 additions & 0 deletions src/banner/closing/closing-entry.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
export class ClosingEntry {
constructor({ key, expiresAt }) {
/**
* @type {EntryKey}
*/
this.key = key;

/**
* @type {Number|Boolean} Integer or false
*/
this.expiresAt = expiresAt;
}

static position({ positionCode, closingExpiration }) {
if ('number' !== typeof closingExpiration) {
throw new Error(`Unable to create position entry via factory ClosingEntry::position({ positionCode: ${positionCode}, closingExpiration: ${closingExpiration} }), argument "closingExpiration" must be a number.`);
}

return new ClosingEntry({
key: EntryKey.position(positionCode),
expiresAt: Math.round((+new Date() / 1000) + closingExpiration),
});
}

static banner({ positionCode, bannerId, closingExpiration }) {
return new ClosingEntry({
key: EntryKey.banner(positionCode, bannerId),
expiresAt: 'number' === typeof closingExpiration ? Math.round((+new Date() / 1000) + closingExpiration) : false,
});
}
}

export class EntryKey {
constructor({ value, type, args }) {
this.value = value;
this.type = type;

/**
* @type {{positionCode: {String}, bannerId?: {String}}}
*/
this.args = args;
}

static position(positionCode) {
return new EntryKey({
value: `p:${positionCode}`,
type: 'position',
args: {
positionCode: positionCode,
},
});
}

static banner(positionCode, bannerId) {
return new EntryKey({
value: `b:${positionCode}:${bannerId}`,
type: 'banner',
args: {
positionCode: positionCode,
bannerId: bannerId,
},
});
}

static tryParse(keyNative) {
const parts = keyNative.split(':');

switch (true) {
case 'p' === parts[0] && 2 === parts.length:
return EntryKey.position(parts[1]);
case 'b' === parts[0] && 3 === parts.length:
return EntryKey.banner(parts[1], parts[2]);
}

return null;
}

isPosition() {
return 'position' === this.type;
}

isBanner() {
return 'banner' === this.type;
}

toString() {
return this.value;
}
}
Loading