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

Fix Pilulka.{cz,sk} widget #2079

Open
wants to merge 1 commit into
base: trunk
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
4 changes: 3 additions & 1 deletion extension/helpers.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ export function cleanUnitPrice(s, quantity) {
return quantity * (unitPrice / 1000).toFixed(2);
}

// populated by calling registerShop
export const shops = new Map();

export function registerShop(shop, ...names) {
Expand Down Expand Up @@ -66,5 +67,6 @@ export function isElementVisible(el) {

export {
cleanPriceText,
cleanUnitPriceText
cleanUnitPriceText,
getLdJsonByType
} from "@hlidac-shopu/lib/parse.mjs";
48 changes: 40 additions & 8 deletions extension/shops/pilulka.mjs
Original file line number Diff line number Diff line change
@@ -1,24 +1,56 @@
import { cleanPrice, registerShop } from "../helpers.mjs";
import { AsyncShop } from "./shop.mjs";
import { cleanPrice, registerShop, getLdJsonByType } from "../helpers.mjs";
import { StatefulShop } from "./shop.mjs";

export class Pilulka extends StatefulShop {

export class Pilulka extends AsyncShop {
get injectionPoint() {
return ["afterend", ".service-detail__basket-box"];
}

get waitForSelector() {
return ".service-detail__basket-box";
// detailSelector is used during scheduleRendering for initial widget render,
// but we wanna skip that and only render when shouldRender is called from MutationObserver
// Note that removing detailSelector would trigger an error so we return dummy value
get detailSelector() {
return "nonsense-value-to-never-render-during-initial-scheduleRendering";
}

shouldRender(mutations) {
// rating box is loaded last
// = safest time to render widget without worrying about it being removed
const needle = mutations.find(mutation =>
Array.from(mutation.addedNodes).find(node =>
node.querySelector?.(".service-detail__main__right__inner .rating--box")
)
)
// console.log(`shouldRender: ${needle ? '✅' : '🔴'}`);
return !!needle;
}

shouldCleanup(mutations) {
const needle = mutations.find(mutation =>
Array.from(mutation.removedNodes).find(node =>
node.getAttribute?.("componentname") === "catalog.product"
)
)
// console.log(`shouldCleanup: ${needle ? '✅' : '🔴'}`);
return !!needle;
}


async scrape() {
const data = JSON.parse(document.querySelector("script[type='application/ld+json']").textContent);
const product = data.find(x => x["@type"] === "Product");
// Give Nuxt 100ms to replace the json-ld script tag with correct data,
// otherwise it could contain old product when using SPA navigation
await new Promise(resolve => setTimeout(resolve, 100));
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please, wait for the observed change of element. Don't introduce arbitrary race conditions.

const product = getLdJsonByType(document, "Product");

const title = product?.name;
const domTitle = document.querySelector("h1").innerText
if (title !== domTitle) console.error("Pilulka.cz - scrape: title mismatch", { title, domTitle });
const itemId = document.querySelector("[componentname='catalog.product']").id;
const currentPrice = product?.offers?.price;
const originalPrice = cleanPrice(`.price-before, .superPrice__old__price`);
const imageUrl = product?.image?.[0];

console.log("Hlídačshopů.cz - scrape", { title, itemId, currentPrice, originalPrice, imageUrl });
return { itemId, title, currentPrice, originalPrice, imageUrl };
}
}
Expand Down
2 changes: 1 addition & 1 deletion extension/shops/shop.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -100,14 +100,14 @@ export class StatefulShop extends Shop {

async scheduleRendering({ render, cleanup, fetchData }) {
new MutationObserver(async mutations => {
if (this.shouldCleanup(mutations)) cleanup();
rarous marked this conversation as resolved.
Show resolved Hide resolved
if (this.shouldRender(mutations)) {
const info = await this.scrape();
if (!info) return;
const data = await fetchData(info);
if (!data) return;
render(false, data);
}
if (this.shouldCleanup(mutations)) cleanup();
}).observe(this.observerTarget, {
subtree: true,
childList: true
Expand Down
24 changes: 24 additions & 0 deletions lib/parse.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -37,3 +37,27 @@ export function parseIntText(text) {
export function parseFloatText(text) {
return text ? parseFloat(text.replace(/\s+/g, "")) : null;
}

/**
* @param {object} document
* @param {string} type
* @returns {object|null}
*/
export function getLdJsonByType(document, type) {
for (const scriptEl of document.querySelectorAll(`script[type="application/ld+json"]`)) {
const scriptText = scriptEl.textContent;
let scriptData;
try { // important, as JSON can be malformed
scriptData = JSON.parse(scriptText);
} catch (err) {
console.error(`Failed to parse JSON, skipping this script and continuing..., scriptText: ${scriptText}`);
continue;
}
if (Array.isArray(scriptData)) { // although unusual, one script can contain multiple objects
rarous marked this conversation as resolved.
Show resolved Hide resolved
const found = scriptData.find(x => x["@type"] === type);
if (found) return found;
} else if (scriptData?.["@type"] === type) {
return scriptData;
}
}
}