diff --git a/android/app/build.gradle b/android/app/build.gradle index 6bdd273c7bc03ea2ba7a6419efd9534842fe1a85..4114fafe7da4be7df0fd1cd21b6e7bfe7e6a9ca6 100644 --- a/android/app/build.gradle +++ b/android/app/build.gradle @@ -7,8 +7,8 @@ android { applicationId "com.chinak.app" minSdkVersion rootProject.ext.minSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion - versionCode 41 - versionName "1.0.31" + versionCode 42 + versionName "1.0.32" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } diff --git a/check_server_start.js b/check_server_start.js new file mode 100644 index 0000000000000000000000000000000000000000..4900f516b44f75cda86c0bef6a7c583e612e1ed9 --- /dev/null +++ b/check_server_start.js @@ -0,0 +1,22 @@ +const fs = require('fs'); +const http = require('http'); + +try { + fs.writeFileSync('check_status.txt', 'STARTING\n'); + const server = http.createServer((req, res) => { + res.writeHead(200); + res.end('OK'); + }); + + server.on('error', (err) => { + fs.appendFileSync('check_status.txt', 'ERROR: ' + err.message + '\n'); + process.exit(1); + }); + + server.listen(5001, () => { + fs.appendFileSync('check_status.txt', 'LISTENING 5001\n'); + console.log('Listening on 5001'); + }); +} catch (e) { + fs.writeFileSync('check_status.txt', 'CRASH: ' + e.message + '\n'); +} diff --git a/debug_start.ps1 b/debug_start.ps1 new file mode 100644 index 0000000000000000000000000000000000000000..ed6b34cc324065f01fbe33d3749ba5529c0b9d1a --- /dev/null +++ b/debug_start.ps1 @@ -0,0 +1,8 @@ +Start-Transcript -Path "debug_log.txt" +Write-Host "Starting node..." +try { + & node server/index.js +} catch { + Write-Host "Error: $_" +} +Stop-Transcript \ No newline at end of file diff --git a/package.json b/package.json index e6914b80647e71b7d55954901583a6289dd7c7cf..880f6442a75be7af2b519c09d9d1473b767d3ecf 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "project", "private": true, - "version": "1.0.31", + "version": "1.0.32", "type": "module", "scripts": { "dev": "concurrently \"npm run dev:frontend\" \"npm run dev:backend\"", diff --git a/run_db_fix.bat b/run_db_fix.bat new file mode 100644 index 0000000000000000000000000000000000000000..04445358b7f63d8af20367efea82d88a5c2c4075 --- /dev/null +++ b/run_db_fix.bat @@ -0,0 +1,4 @@ +@echo off +echo Running DB Fix... > db_fix_log.txt +cd server +node fix_mojibake_db.js >> ..\db_fix_log.txt 2>&1 diff --git a/run_server_simple.bat b/run_server_simple.bat new file mode 100644 index 0000000000000000000000000000000000000000..2889b4fac6c5431ed68c42f6fa45a61de1f06a09 --- /dev/null +++ b/run_server_simple.bat @@ -0,0 +1,4 @@ +@echo off +echo Starting server... > server_log.txt +cd server +node index.js >> ..\server_log.txt 2>&1 diff --git a/server/check_node.js b/server/check_node.js new file mode 100644 index 0000000000000000000000000000000000000000..74f4a7ff9e0375894f1789881fefd51e9eeacb60 --- /dev/null +++ b/server/check_node.js @@ -0,0 +1 @@ +console.log("NODE IS WORKING"); \ No newline at end of file diff --git a/server/check_products_cjs.cjs b/server/check_products_cjs.cjs new file mode 100644 index 0000000000000000000000000000000000000000..ee9ae37924632e3ce67727a99a95b16e342d4a05 --- /dev/null +++ b/server/check_products_cjs.cjs @@ -0,0 +1,55 @@ +const { PrismaClient } = require('@prisma/client'); +const fs = require('fs'); +const path = require('path'); + +// Explicitly load .env +const envPath = path.join(__dirname, '.env'); +if (fs.existsSync(envPath)) { + require('dotenv').config({ path: envPath }); +} + +const prisma = new PrismaClient(); + +async function check() { + try { + const where = { + isActive: true, + status: 'PUBLISHED' + }; + + console.log('Running query...'); + const products = await prisma.product.findMany({ + where, + select: { + id: true, + name: true, + price: true, + basePriceIQD: true, + image: true, + isFeatured: true, + domesticShippingFee: true, + deliveryTime: true, + variants: { + select: { + id: true, + combination: true, + price: true, + basePriceIQD: true, + image: true, + } + } + }, + take: 20, + orderBy: { updatedAt: 'desc' } + }); + console.log('Query success. Products found:', products.length); + fs.writeFileSync(path.join(__dirname, 'product_query_success.log'), JSON.stringify(products, null, 2)); + } catch (error) { + console.error('Query failed:', error); + fs.writeFileSync(path.join(__dirname, 'product_query_error.log'), error.message + '\n' + error.stack); + } finally { + await prisma.$disconnect(); + } +} + +check(); diff --git a/server/check_products_error.js b/server/check_products_error.js new file mode 100644 index 0000000000000000000000000000000000000000..7de2aa646c0b1b2b6b2e6dd3db202ed4f928f357 --- /dev/null +++ b/server/check_products_error.js @@ -0,0 +1,46 @@ +import prisma from './prismaClient.js'; +import fs from 'fs'; + +async function check() { + try { + const where = { + isActive: true, + status: 'PUBLISHED' + }; + + console.log('Running query...'); + const products = await prisma.product.findMany({ + where, + select: { + id: true, + name: true, + price: true, + basePriceIQD: true, + image: true, + isFeatured: true, + domesticShippingFee: true, + deliveryTime: true, + variants: { + select: { + id: true, + combination: true, + price: true, + basePriceIQD: true, + image: true, + } + } + }, + take: 20, + orderBy: { updatedAt: 'desc' } + }); + console.log('Query success. Products found:', products.length); + fs.writeFileSync('server/product_query_success.log', JSON.stringify(products, null, 2)); + } catch (error) { + console.error('Query failed:', error); + fs.writeFileSync('server/product_query_error.log', error.message + '\n' + error.stack); + } finally { + await prisma.$disconnect(); + } +} + +check(); diff --git a/server/check_products_simple.cjs b/server/check_products_simple.cjs new file mode 100644 index 0000000000000000000000000000000000000000..83355d8418ade54545bbb0db11a59041811ce5a6 --- /dev/null +++ b/server/check_products_simple.cjs @@ -0,0 +1,45 @@ +const { PrismaClient } = require('@prisma/client'); +const fs = require('fs'); +const path = require('path'); + +// Explicitly load .env +const envPath = path.join(__dirname, '.env'); +if (fs.existsSync(envPath)) { + require('dotenv').config({ path: envPath }); +} + +const prisma = new PrismaClient(); + +async function check() { + try { + const where = { + isActive: true, + status: 'PUBLISHED' + }; + + // Test connection first + await prisma.$connect(); + + console.log('Running query...'); + const products = await prisma.product.findMany({ + where, + select: { + id: true, + name: true, + price: true, + basePriceIQD: true, // Potential issue? + domesticShippingFee: true, // Potential issue? + }, + take: 1 + }); + console.log('Query success. Products found:', products.length); + fs.writeFileSync('check_products_output.log', 'SUCCESS: ' + JSON.stringify(products, null, 2)); + } catch (error) { + console.error('Query failed:', error); + fs.writeFileSync('check_products_output.log', 'ERROR: ' + error.message + '\n' + error.stack); + } finally { + await prisma.$disconnect(); + } +} + +check(); diff --git a/server/check_server_status.js b/server/check_server_status.js new file mode 100644 index 0000000000000000000000000000000000000000..4632afde2a674ee2f44d98907874e0d7e18a5ddd --- /dev/null +++ b/server/check_server_status.js @@ -0,0 +1,26 @@ + +import http from 'http'; +import fs from 'fs'; + +function check(url, name) { + return new Promise((resolve) => { + const req = http.get(url, (res) => { + resolve(`${name}: UP (${res.statusCode})`); + }); + req.on('error', (e) => { + resolve(`${name}: DOWN (${e.message})`); + }); + req.end(); + }); +} + +async function run() { + const frontend = await check('http://localhost:5173', 'Frontend'); + const backend = await check('http://localhost:5001/api/products', 'Backend'); + + const result = `${frontend}\n${backend}`; + console.log(result); + fs.writeFileSync('server/server_check_status.txt', result); +} + +run(); diff --git a/server/debug_api.js b/server/debug_api.js new file mode 100644 index 0000000000000000000000000000000000000000..a497e1c7fc40a80ce98271a05e017ab10fad7da7 --- /dev/null +++ b/server/debug_api.js @@ -0,0 +1,22 @@ +import axios from 'axios'; +import fs from 'fs'; + +async function testApi() { + try { + console.log('Fetching http://localhost:5001/api/products...'); + const response = await axios.get('http://localhost:5001/api/products'); + console.log('Success:', response.status); + fs.writeFileSync('server/api_success.json', JSON.stringify(response.data, null, 2)); + } catch (error) { + console.log('Error:', error.message); + if (error.response) { + console.log('Status:', error.response.status); + console.log('Data:', JSON.stringify(error.response.data, null, 2)); + fs.writeFileSync('server/api_error.json', JSON.stringify(error.response.data, null, 2)); + } else { + fs.writeFileSync('server/api_network_error.txt', error.message); + } + } +} + +testApi(); diff --git a/server/debug_db_schema.js b/server/debug_db_schema.js new file mode 100644 index 0000000000000000000000000000000000000000..3a15ce6ae883b93232e29316e81667357a8f77f0 --- /dev/null +++ b/server/debug_db_schema.js @@ -0,0 +1,75 @@ + +import { PrismaClient } from '@prisma/client'; +import dotenv from 'dotenv'; +import path from 'path'; +import { fileURLToPath } from 'url'; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); + +dotenv.config({ path: path.join(__dirname, '.env') }); + +const prisma = new PrismaClient(); + +async function main() { + try { + const output = []; + const log = (...args) => { + console.log(...args); + output.push(args.map(a => typeof a === 'object' ? JSON.stringify(a) : String(a)).join(' ')); + }; + + log('--- DB DIAGNOSTIC START ---'); + log('DATABASE_URL:', process.env.DATABASE_URL ? process.env.DATABASE_URL.substring(0, 20) + '...' : 'UNDEFINED'); + + // 1. Check if the table exists + const tableExists = await prisma.$queryRawUnsafe(` + SELECT EXISTS ( + SELECT FROM information_schema.tables + WHERE table_schema = 'public' + AND table_name = 'Product' + ); + `); + log('Table "Product" exists:', tableExists); + + // 2. Check if the column exists + const columns = await prisma.$queryRawUnsafe(` + SELECT column_name, data_type + FROM information_schema.columns + WHERE table_name = 'Product'; + `); + + log('Columns in "Product" table:'); + const columnNames = Array.isArray(columns) ? columns.map(c => c.column_name) : []; + log(columnNames.join(', ')); + + const hasScrapedReviews = columnNames.includes('scrapedReviews'); + log('Has "scrapedReviews" column:', hasScrapedReviews); + + if (!hasScrapedReviews) { + log('ATTEMPTING TO ADD COLUMN...'); + try { + await prisma.$executeRawUnsafe(`ALTER TABLE "Product" ADD COLUMN IF NOT EXISTS "scrapedReviews" JSONB;`); + log('Column added successfully.'); + } catch (err) { + log('Failed to add column:', err.message); + } + } else { + log('Column already exists. No action needed.'); + } + + log('--- DB DIAGNOSTIC END ---'); + + // Write to file + const fs = await import('fs'); + fs.writeFileSync(path.join(__dirname, 'db_check_result.txt'), output.join('\n')); + + + } catch (e) { + console.error('Diagnostic Error:', e); + } finally { + await prisma.$disconnect(); + } +} + +main(); diff --git a/server/fix_missing_column.js b/server/fix_missing_column.js new file mode 100644 index 0000000000000000000000000000000000000000..ba65759a17971fcca16db1c40491e9bc490f0da2 --- /dev/null +++ b/server/fix_missing_column.js @@ -0,0 +1,45 @@ + +import { PrismaClient } from '@prisma/client'; +import fs from 'fs'; + +const prisma = new PrismaClient(); + +async function main() { + console.log('Starting column check...'); + try { + // 1. Check if column exists using raw SQL + const checkQuery = ` + SELECT column_name + FROM information_schema.columns + WHERE table_name = 'Product' AND column_name = 'scrapedReviews'; + `; + console.log('Executing check query...'); + const result = await prisma.$queryRawUnsafe(checkQuery); + + if (result.length > 0) { + console.log('SUCCESS: "scrapedReviews" column ALREADY exists.'); + } else { + console.log('WARNING: "scrapedReviews" column MISSING. Attempting to add it...'); + + // 2. Add column if missing + const alterQuery = `ALTER TABLE "Product" ADD COLUMN IF NOT EXISTS "scrapedReviews" JSONB;`; + await prisma.$executeRawUnsafe(alterQuery); + console.log('SUCCESS: executed ALTER TABLE command.'); + + // 3. Verify again + const verifyResult = await prisma.$queryRawUnsafe(checkQuery); + if (verifyResult.length > 0) { + console.log('VERIFICATION: Column added successfully!'); + } else { + console.error('ERROR: Column still missing after ALTER TABLE.'); + } + } + + } catch (e) { + console.error('CRITICAL ERROR:', e); + } finally { + await prisma.$disconnect(); + } +} + +main(); diff --git a/server/force_add_column_direct.js b/server/force_add_column_direct.js new file mode 100644 index 0000000000000000000000000000000000000000..04dad75820b16b1a95b5d213264db1eeeadb02a6 --- /dev/null +++ b/server/force_add_column_direct.js @@ -0,0 +1,62 @@ + +import { PrismaClient } from '@prisma/client'; + +// Hardcoded DIRECT_URL to bypass any environment variable issues +const DIRECT_URL = "postgresql://postgres.puxjtecjxfjldwxiwzrk:aLajApB0IEwLdJaE@aws-1-eu-west-1.pooler.supabase.com:5432/postgres?sslmode=require"; + +console.log('Using DIRECT_URL:', DIRECT_URL); + +const prisma = new PrismaClient({ + datasources: { + db: { + url: DIRECT_URL, + }, + }, +}); + +async function main() { + try { + console.log('Connecting to database...'); + + // 1. Check existing columns + console.log('Checking existing columns in "Product" table...'); + const initialColumns = await prisma.$queryRawUnsafe(` + SELECT column_name + FROM information_schema.columns + WHERE table_name = 'Product'; + `); + console.log('Current columns:', initialColumns.map(c => c.column_name).join(', ')); + + // 2. Add the column + console.log('Attempting to add "scrapedReviews" column...'); + try { + await prisma.$executeRawUnsafe(`ALTER TABLE "Product" ADD COLUMN IF NOT EXISTS "scrapedReviews" JSONB;`); + console.log('ALTER TABLE command executed successfully.'); + } catch (e) { + console.error('Error executing ALTER TABLE:', e.message); + } + + // 3. Verify the column + console.log('Verifying "scrapedReviews" column...'); + const finalColumns = await prisma.$queryRawUnsafe(` + SELECT column_name + FROM information_schema.columns + WHERE table_name = 'Product'; + `); + + const hasColumn = finalColumns.some(c => c.column_name === 'scrapedReviews'); + + if (hasColumn) { + console.log('SUCCESS: "scrapedReviews" column is present in the database.'); + } else { + console.error('FAILURE: "scrapedReviews" column is STILL MISSING after ALTER TABLE.'); + } + + } catch (e) { + console.error('Critical Error:', e); + } finally { + await prisma.$disconnect(); + } +} + +main(); diff --git a/server/force_add_column_direct_v2.js b/server/force_add_column_direct_v2.js new file mode 100644 index 0000000000000000000000000000000000000000..f2fecf9ae6d7f9ee1ec1fdae1917bbc66edcd6ba --- /dev/null +++ b/server/force_add_column_direct_v2.js @@ -0,0 +1,68 @@ + +import { PrismaClient } from '@prisma/client'; +import fs from 'fs'; + +// Hardcoded DIRECT_URL to bypass any environment variable issues +const DIRECT_URL = "postgresql://postgres.puxjtecjxfjldwxiwzrk:aLajApB0IEwLdJaE@aws-1-eu-west-1.pooler.supabase.com:5432/postgres?sslmode=require"; + +const prisma = new PrismaClient({ + datasources: { + db: { + url: DIRECT_URL, + }, + }, +}); + +async function main() { + const output = []; + const log = (msg) => { + console.log(msg); + output.push(msg); + }; + + try { + log('Using DIRECT_URL: ' + DIRECT_URL.substring(0, 20) + '...'); + + // 1. Check existing columns + log('Checking existing columns in "Product" table...'); + const initialColumns = await prisma.$queryRawUnsafe(` + SELECT column_name + FROM information_schema.columns + WHERE table_name = 'Product'; + `); + log('Current columns: ' + initialColumns.map(c => c.column_name).join(', ')); + + // 2. Add the column + log('Attempting to add "scrapedReviews" column...'); + try { + await prisma.$executeRawUnsafe(`ALTER TABLE "Product" ADD COLUMN IF NOT EXISTS "scrapedReviews" JSONB;`); + log('ALTER TABLE command executed successfully.'); + } catch (e) { + log('Error executing ALTER TABLE: ' + e.message); + } + + // 3. Verify the column + log('Verifying "scrapedReviews" column...'); + const finalColumns = await prisma.$queryRawUnsafe(` + SELECT column_name + FROM information_schema.columns + WHERE table_name = 'Product'; + `); + + const hasColumn = finalColumns.some(c => c.column_name === 'scrapedReviews'); + + if (hasColumn) { + log('SUCCESS: "scrapedReviews" column is present in the database.'); + } else { + log('FAILURE: "scrapedReviews" column is STILL MISSING after ALTER TABLE.'); + } + + } catch (e) { + log('Critical Error: ' + e.message); + } finally { + await prisma.$disconnect(); + fs.writeFileSync('force_add_column_result.txt', output.join('\n')); + } +} + +main(); diff --git a/server/index.js b/server/index.js index d3fb039975f51dce64714fa95dd7be2bb6651749..035b5998a1e812a2ed17d7a19162074598941ef0 100644 --- a/server/index.js +++ b/server/index.js @@ -1,3 +1,9 @@ +import fs from 'fs'; +try { fs.writeFileSync('e:/mynewproject2/server/server_start.log', 'STARTING ' + new Date().toISOString() + '\n'); } catch (e) {} +process.on('uncaughtException', (err) => { + try { fs.appendFileSync('e:/mynewproject2/server/server_crash.log', `ERROR: ${err.message}\n${err.stack}\n`); } catch (e) {} +}); + import dns from 'node:dns'; dns.setDefaultResultOrder('ipv4first'); @@ -13,7 +19,6 @@ import compression from 'compression'; import https from 'https'; import { createServer } from 'http'; import { Server } from 'socket.io'; -import fs from 'fs'; import path from 'path'; import axios from 'axios'; import { fileURLToPath } from 'url'; @@ -27,6 +32,7 @@ const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); const { PrismaClient } = pkg; +// Note: We use the singleton 'prisma' from prismaClient.js instead of creating new instances // Explicitly load .env and log status const envPath = path.join(__dirname, '.env'); @@ -61,22 +67,27 @@ const applyDynamicPricingToProduct = (product, rates) => { // Helper to calculate price for a specific target (product or variant) const calcPrice = (target, method) => { - const basePrice = target.price || 0; - // Use target's basePriceIQD if available, else product's - const basePriceIQD = (target.basePriceIQD && target.basePriceIQD > 0) ? target.basePriceIQD : (product.basePriceIQD || null); - const domesticShippingFee = product.domesticShippingFee || 0; - - // Ensure getAdjustedPrice is available - if (typeof getAdjustedPrice !== 'function') { - console.warn('getAdjustedPrice is not a function, using fallback price'); - return Math.ceil(basePrice / 250) * 250; - } + try { + const basePrice = target.price || 0; + // Use target's basePriceIQD if available, else product's + const basePriceIQD = (target.basePriceIQD && target.basePriceIQD > 0) ? target.basePriceIQD : (product.basePriceIQD || null); + const domesticShippingFee = product.domesticShippingFee || 0; + + // Ensure getAdjustedPrice is available + if (typeof getAdjustedPrice !== 'function') { + console.warn('getAdjustedPrice is not a function, using fallback price'); + return Math.ceil(basePrice / 250) * 250; + } - return getAdjustedPrice( - basePrice, - domesticShippingFee, - basePriceIQD - ); + return getAdjustedPrice( + basePrice, + domesticShippingFee, + basePriceIQD + ); + } catch (err) { + console.error('Error in calcPrice:', err); + return Math.ceil((target.price || 0) / 250) * 250; + } }; // 1. Calculate for all variants if they exist @@ -592,7 +603,7 @@ io.on('connection', (socket) => { }); }); -const PORT = process.env.PORT || 5002; +const PORT = process.env.PORT || 5001; const JWT_SECRET = process.env.JWT_SECRET || 'c2hhbnNoYWw2Ni1teS1zaG9wLWJhY2tlbmQtc2VjcmV0LTIwMjY='; // --- Normalization Helpers --- @@ -2969,6 +2980,21 @@ app.get('/api/products', async (req, res) => { }); } catch (error) { console.error('[Products] Failed to fetch products:', error); + try { + const logPath = path.join(__dirname, 'server_error_full.log'); + fs.appendFileSync(logPath, `[${new Date().toISOString()}] Error in /api/products: ${error.message}\n${error.stack}\nQuery: ${JSON.stringify(req.query)}\n\n`); + } catch (e) { + console.error('Failed to write to error log:', e); + } + + try { + // Write error to public folder for debugging + const publicErrorPath = path.join(__dirname, '..', 'public', 'server_error.txt'); + fs.writeFileSync(publicErrorPath, `[${new Date().toISOString()}] Error in /api/products: ${error.message}\n${error.stack}\n`); + } catch (e) { + console.error('Failed to write to public error log:', e); + } + res.status(500).json({ error: 'Failed to fetch products', details: error.message, @@ -7116,14 +7142,44 @@ app.get('/api/products/:id/reviews', async (req, res) => { orderBy: { createdAt: 'desc' } }); - // Get product to check for reviews in specs field + // Get product to check for reviews in specs field and aiMetadata and scrapedReviews const product = await prisma.product.findUnique({ where: { id: productId }, - select: { specs: true } + select: { specs: true, aiMetadata: true, scrapedReviews: true } }); let importedReviews = []; + + // Extract reviews from new 'scrapedReviews' field (Primary Source) + if (product?.scrapedReviews && Array.isArray(product.scrapedReviews)) { + product.scrapedReviews.forEach((r, i) => { + importedReviews.push({ + id: -3000 - i, // Different ID range to avoid conflicts + rating: 5, + comment: r.comment || 'صور من تقييمات العملاء', + createdAt: new Date().toISOString(), + user: { name: r.name || 'تقييمات المتجر' }, + images: r.photos || r.images || [] + }); + }); + } + // Extract reviews from aiMetadata (Legacy Scraped Reviews) - Only if no new reviews + if (importedReviews.length === 0 && product?.aiMetadata?.reviews && Array.isArray(product.aiMetadata.reviews)) { + product.aiMetadata.reviews.forEach((r, i) => { + if (r.images && r.images.length > 0) { + importedReviews.push({ + id: -2000 - i, + rating: 5, + comment: 'صور من تقييمات العملاء', + createdAt: new Date().toISOString(), + user: { name: 'تقييمات المتجر' }, + images: r.images + }); + } + }); + } + // Extract reviews from specs field if they exist if (product && product.specs && typeof product.specs === 'string' && product.specs.includes('---REVIEW_SUMMARY---')) { try { @@ -7142,7 +7198,7 @@ app.get('/api/products/:id/reviews', async (req, res) => { if (rawReviews.length > 0) { // Direct reviews format: "reviews": [ { "user": "...", "comment": "..." } ] - importedReviews = rawReviews.map((review, index) => ({ + const newReviews = rawReviews.map((review, index) => ({ id: -index - 1, // Negative IDs to distinguish from database reviews rating: 5, // Default rating for imported reviews comment: review.comment || '', @@ -7150,9 +7206,10 @@ app.get('/api/products/:id/reviews', async (req, res) => { user: { name: review.user || 'عميل' }, images: [] })); + importedReviews = [...importedReviews, ...newReviews]; } else if (reviewSummary.detailedReviews && Array.isArray(reviewSummary.detailedReviews)) { // detailedReviews format (legacy) - importedReviews = reviewSummary.detailedReviews.map((review, index) => ({ + const newReviews = reviewSummary.detailedReviews.map((review, index) => ({ id: -index - 1, // Negative IDs to distinguish from database reviews rating: 5, // Default rating for imported reviews comment: review.comments ? (Array.isArray(review.comments) ? review.comments.join(' ') : review.comments) : '', @@ -7160,6 +7217,7 @@ app.get('/api/products/:id/reviews', async (req, res) => { user: { name: review.user || 'عميل' }, images: review.images || [] })); + importedReviews = [...importedReviews, ...newReviews]; } } } catch (parseError) { diff --git a/server/output.txt b/server/output.txt deleted file mode 100644 index 4c5415401c4dac4ebb16d117b6baa9692b2e57e9..0000000000000000000000000000000000000000 Binary files a/server/output.txt and /dev/null differ diff --git a/server/pg_force_add.js b/server/pg_force_add.js new file mode 100644 index 0000000000000000000000000000000000000000..463272b8afb0dee58acfe0a1194c45b5f1c11e9b --- /dev/null +++ b/server/pg_force_add.js @@ -0,0 +1,69 @@ + +import pg from 'pg'; +import fs from 'fs'; + +const { Client } = pg; + +// Hardcoded DIRECT_URL to bypass any environment variable issues +const connectionString = "postgresql://postgres.puxjtecjxfjldwxiwzrk:aLajApB0IEwLdJaE@aws-1-eu-west-1.pooler.supabase.com:5432/postgres?sslmode=require"; + +async function main() { + const output = []; + const log = (msg) => { + console.log(msg); + output.push(String(msg)); + }; + + const client = new Client({ + connectionString, + }); + + try { + log('Connecting to database via pg client...'); + await client.connect(); + log('Connected successfully.'); + + // 1. Check existing columns + log('Checking existing columns in "Product" table...'); + const resInitial = await client.query(` + SELECT column_name + FROM information_schema.columns + WHERE table_name = 'Product'; + `); + log('Current columns: ' + resInitial.rows.map(c => c.column_name).join(', ')); + + // 2. Add the column + log('Attempting to add "scrapedReviews" column...'); + try { + await client.query(`ALTER TABLE "Product" ADD COLUMN IF NOT EXISTS "scrapedReviews" JSONB;`); + log('ALTER TABLE command executed successfully.'); + } catch (e) { + log('Error executing ALTER TABLE: ' + e.message); + } + + // 3. Verify the column + log('Verifying "scrapedReviews" column...'); + const resFinal = await client.query(` + SELECT column_name + FROM information_schema.columns + WHERE table_name = 'Product'; + `); + + const hasColumn = resFinal.rows.some(c => c.column_name === 'scrapedReviews'); + + if (hasColumn) { + log('SUCCESS: "scrapedReviews" column is present in the database.'); + } else { + log('FAILURE: "scrapedReviews" column is STILL MISSING after ALTER TABLE.'); + } + + } catch (e) { + log('Critical Error: ' + e.message); + log(e.stack); + } finally { + await client.end(); + fs.writeFileSync('pg_force_result.txt', output.join('\n')); + } +} + +main(); diff --git a/server/prisma/schema.prisma b/server/prisma/schema.prisma index ed44b69e465713bd062d6d922556ada246d0f3ec..2a1733a4bd96a5df81132dbee7be0fafcab87d2d 100644 --- a/server/prisma/schema.prisma +++ b/server/prisma/schema.prisma @@ -95,6 +95,7 @@ model Product { createdAt DateTime @default(now()) updatedAt DateTime @updatedAt aiMetadata Json? + scrapedReviews Json? // New field for scraped reviews embedding Unsupported("vector")? domesticShippingFee Float? isAirRestricted Boolean @default(false) diff --git a/server/prismaClient.js b/server/prismaClient.js index 54c5145507a2a316a7e2ff54337d47ec7b4e177a..f2b44ce55569623eb986fd5d76c151edb4f54798 100644 --- a/server/prismaClient.js +++ b/server/prismaClient.js @@ -1,5 +1,28 @@ import pkg from '@prisma/client'; const { PrismaClient } = pkg; +import dotenv from 'dotenv'; +import path from 'path'; +import { fileURLToPath } from 'url'; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); +const envPath = path.join(__dirname, '.env'); +dotenv.config({ path: envPath }); + +// --- FIX DATABASE CONNECTION POOL --- +// Enforce connection limit globally for the server +if (process.env.DATABASE_URL) { + try { + const url = new URL(process.env.DATABASE_URL); + // Limit server connections to leave room for scraper/others + if (!url.searchParams.has('connection_limit')) { + url.searchParams.set('connection_limit', '5'); + process.env.DATABASE_URL = url.toString(); + } + } catch (e) { + console.warn('Warning: Could not parse DATABASE_URL to set connection_limit in prismaClient.js'); + } +} const prisma = new PrismaClient(); diff --git a/server/repair_db_schema.js b/server/repair_db_schema.js new file mode 100644 index 0000000000000000000000000000000000000000..56c56764e6e8294dddc93737b1323bff7a6afd22 --- /dev/null +++ b/server/repair_db_schema.js @@ -0,0 +1,39 @@ + +import { PrismaClient } from '@prisma/client'; + +const prisma = new PrismaClient(); + +async function main() { + try { + console.log('Attempting to manually fix database schema...'); + + // Check if column exists or just try to add it + // PostgreSQL syntax + try { + await prisma.$executeRawUnsafe(`ALTER TABLE "Product" ADD COLUMN IF NOT EXISTS "scrapedReviews" JSONB;`); + console.log('Successfully executed: ALTER TABLE "Product" ADD COLUMN IF NOT EXISTS "scrapedReviews" JSONB;'); + } catch (e) { + console.log('Error executing ADD COLUMN (might already exist or permission issue):', e.message); + } + + console.log('Verifying column existence...'); + // We can try to query it + try { + const result = await prisma.$queryRawUnsafe(`SELECT "scrapedReviews" FROM "Product" LIMIT 1;`); + console.log('Query successful, column exists.'); + } catch(e) { + console.error('Column verification failed:', e.message); + process.exit(1); + } + + console.log('Database repair complete.'); + + } catch (e) { + console.error('Critical error in repair script:', e); + process.exit(1); + } finally { + await prisma.$disconnect(); + } +} + +main(); diff --git a/server/run_fix.bat b/server/run_fix.bat new file mode 100644 index 0000000000000000000000000000000000000000..4629f2e7d98569f0aa7092d49ad1dca1f727eec4 --- /dev/null +++ b/server/run_fix.bat @@ -0,0 +1,2 @@ +@echo off +node server/scripts/fix_mojibake_db.js > fix_log.txt 2>&1 diff --git a/server/run_scraper.bat b/server/run_scraper.bat new file mode 100644 index 0000000000000000000000000000000000000000..7344022a0903df222a73b4e92a68bb69e94d9bb1 --- /dev/null +++ b/server/run_scraper.bat @@ -0,0 +1,2 @@ +@echo off +node scripts/pinduoduo-scraper.js "https://mobile.pinduoduo.com/catgoods.html?refer_page_name=index&opt_id=25667&opt_name=%E4%B8%8A%E8%A1%A3%E5%A4%96%E5%A5%97&opt_type=2&goods_id=836596630021&refer_page_id=10002_1770945474906_zhvvkggy6l&refer_page_sn=10002" > scraper_output.txt 2>&1 diff --git a/server/scripts/check_db_mojibake.js b/server/scripts/check_db_mojibake.js new file mode 100644 index 0000000000000000000000000000000000000000..3e5220949fd53f4051364333d95faae7d1fdaab8 --- /dev/null +++ b/server/scripts/check_db_mojibake.js @@ -0,0 +1,46 @@ +import { PrismaClient } from '@prisma/client'; +import fs from 'fs'; + +const prisma = new PrismaClient(); + +async function checkDb() { + const products = await prisma.product.findMany({ + take: 5, + where: { + OR: [ + { specs: { contains: 'ط§ظ„ظ…ط§ط±ظƒط©' } }, + { specs: { contains: 'الماركة' } } + ] + } + }); + + const options = await prisma.productOption.findMany({ + take: 5, + where: { + OR: [ + { name: { contains: 'ط§ظ„ظ…ط§ط±ظƒط©' } }, + { name: { contains: 'الماركة' } } + ] + } + }); + + let output = "DB Check Results:\n"; + output += `Found ${products.length} products with relevant specs.\n`; + products.forEach(p => { + output += `Product ID: ${p.id}, Name: ${p.name}\nSpecs: ${p.specs}\n\n`; + }); + + output += `Found ${options.length} options with relevant names.\n`; + options.forEach(o => { + output += `Option ID: ${o.id}, Name: ${o.name}\nValues: ${o.values}\n\n`; + }); + + console.log(output); + fs.writeFileSync('db_check_result.txt', output); +} + +checkDb() + .catch(e => fs.writeFileSync('db_check_result.txt', `Error: ${e.message}`)) + .finally(async () => { + await prisma.$disconnect(); + }); diff --git a/server/scripts/fix_mojibake_db.js b/server/scripts/fix_mojibake_db.js new file mode 100644 index 0000000000000000000000000000000000000000..cc14e05486495391b2e76735297d3293f17ed899 --- /dev/null +++ b/server/scripts/fix_mojibake_db.js @@ -0,0 +1,143 @@ +import { PrismaClient } from '@prisma/client'; + +const prisma = new PrismaClient(); + +const MOJIBAKE_MAP = { + 'ط§ظ„ظ…ط§ط±ظƒط©': 'الماركة', + 'ط§ظ„ظ„ظˆظ†': 'اللون', + 'ط§ظ„ظ…ظ‚ط§ط³': 'المقاس', + 'ط§ظ„ظ…ط§ط¯ط©': 'المادة', + 'ط§ظ„ظ…ظٹط²ط©': 'الميزة', + 'ط§ظ„طھطµظ…ظٹظ…': 'التصميم', + 'ط§ظ„ط§ط³طھط®ط¯ط§ظ…': 'الاستخدام', + 'ط§ط³ظ… ط؛ظٹط± ظ…طھظˆظپط±': 'اسم غير متوفر', + 'ط§ظ„ظ„ظˆظ† ط§ظ„ط§ظپطھط±ط§ط¶ظٹ': 'اللون الافتراضي', + 'ظƒظ…ط§ ظپظٹ ط§ظ„طµظˆط±ط©': 'كما في الصورة', + 'طھط®طµظٹطµ': 'تخصيص', + 'ط§طھطµط§ظ„': 'اتصال', + 'ط±ط§ط¨ط·': 'رابط', + 'ظپط±ظ‚': 'فرق', + 'ط¥ظٹط¯ط§ط¹': 'إيداع', + 'ظ„ط§ ظٹط±ط³ظ„': 'لا يرسل', + 'ط®ط¯ظ…ط© ط§ظ„ط¹ظ…ظ„ط§ط،': 'خدمة العملاء', + 'ظ…ط®طµطµ': 'مخصص' +}; + +async function fixMojibake() { + console.log('Starting Mojibake Fixer...'); + + // 1. Fix Products (Specs and Name) + const products = await prisma.product.findMany(); + console.log(`Found ${products.length} products to check.`); + + for (const p of products) { + let updated = false; + let newSpecsStr = p.specs; + let newName = p.name; + + // Fix Name + for (const [bad, good] of Object.entries(MOJIBAKE_MAP)) { + if (newName && newName.includes(bad)) { + newName = newName.split(bad).join(good); + updated = true; + } + } + + // Fix Specs (JSON string) + if (newSpecsStr) { + for (const [bad, good] of Object.entries(MOJIBAKE_MAP)) { + if (newSpecsStr.includes(bad)) { + newSpecsStr = newSpecsStr.split(bad).join(good); + updated = true; + } + } + } + + if (updated) { + console.log(`Fixing Product ID: ${p.id}`); + await prisma.product.update({ + where: { id: p.id }, + data: { + name: newName, + specs: newSpecsStr + } + }); + } + } + + // 2. Fix ProductOptions (Name and Values) + const options = await prisma.productOption.findMany(); + console.log(`Found ${options.length} options to check.`); + + for (const opt of options) { + let updated = false; + let newName = opt.name; + let newValues = opt.values; + + // Fix Name + for (const [bad, good] of Object.entries(MOJIBAKE_MAP)) { + if (newName && newName.includes(bad)) { + newName = newName.split(bad).join(good); + updated = true; + } + } + + // Fix Values (JSON string) + if (newValues) { + for (const [bad, good] of Object.entries(MOJIBAKE_MAP)) { + if (newValues.includes(bad)) { + newValues = newValues.split(bad).join(good); + updated = true; + } + } + } + + if (updated) { + console.log(`Fixing Option ID: ${opt.id}`); + await prisma.productOption.update({ + where: { id: opt.id }, + data: { + name: newName, + values: newValues + } + }); + } + } + + // 3. Fix ProductVariants (Combination) + const variants = await prisma.productVariant.findMany(); + console.log(`Found ${variants.length} variants to check.`); + + for (const v of variants) { + let updated = false; + let newCombination = v.combination; + + if (newCombination) { + for (const [bad, good] of Object.entries(MOJIBAKE_MAP)) { + if (newCombination.includes(bad)) { + newCombination = newCombination.split(bad).join(good); + updated = true; + } + } + } + + if (updated) { + console.log(`Fixing Variant ID: ${v.id}`); + await prisma.productVariant.update({ + where: { id: v.id }, + data: { + combination: newCombination + } + }); + } + } + + console.log('Mojibake Fix Complete.'); + fs.appendFileSync('e:/mynewproject2/fix_log_verbose.txt', 'Script finished\n'); +} + +fixMojibake() + .catch(e => console.error(e)) + .finally(async () => { + await prisma.$disconnect(); + }); diff --git a/server/scripts/part1.js b/server/scripts/part1.js new file mode 100644 index 0000000000000000000000000000000000000000..345763513cfa869760cdb6a0ae2cd35c128653ee --- /dev/null +++ b/server/scripts/part1.js @@ -0,0 +1,2451 @@ +import vanillaPuppeteer from 'puppeteer-core'; +import puppeteerExtra from 'puppeteer-extra'; +import StealthPlugin from 'puppeteer-extra-plugin-stealth'; + +const puppeteer = puppeteerExtra.addExtra(vanillaPuppeteer); +puppeteer.use(StealthPlugin()); + +import fs from 'fs'; +import path from 'path'; +import dotenv from 'dotenv'; +import OpenAI from 'openai'; // Use OpenAI SDK for SiliconFlow +import readline from 'readline'; +import { fileURLToPath } from 'url'; +import { PrismaClient } from '@prisma/client'; +import { processProductEmbedding } from '../services/aiService.js'; + +// Load .env +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); +const envPath = path.join(__dirname, '..', '.env'); // server/.env +dotenv.config({ path: envPath }); +const prisma = new PrismaClient(); +// const prisma = { $disconnect: async () => {} }; + +// --- EDIBLE ITEM FILTERING CONFIGURATION --- +const EDIBLE_KEYWORDS = [ + "é£ںه“پ", "é›¶é£ں", "ه‌ڑو‍œ", "ç½گه¤´", "饮و–™", "ç³–و‍œ", "饼ه¹²", "è°ƒو–™", "茶", "é…’", + "肉", "蛋", "ه¥¶", "و²¹", "ç±³", "é‌¢", "و‍œه†»", "ه·§ه…‹هٹ›", "ه’–ه•،", "food", "snack", + "nut", "can", "drink", "candy", "biscuit", "seasoning", "tea", "wine", + "meat", "egg", "milk", "oil", "rice", "noodle", "jelly", "chocolate", "coffee", + "هگƒ", "ه–‌", "ه‘³", "香", "甜", "è¾£", "ه’¸", "é…¸", "苦" // General taste/eating words (use with caution or in combination) +]; + +// Stricter list for immediate rejection +const STRICT_EDIBLE_KEYWORDS = [ + "é£ںه“پ", "é›¶é£ں", "ه‌ڑو‍œ", "ç½گه¤´", "饮و–™", "ç³–و‍œ", "饼ه¹²", "è°ƒو–™", "茶هڈ¶", "é…’و°´", + "鲜肉", "é¸،蛋", "牛ه¥¶", "é£ں用و²¹", "ه¤§ç±³", "é‌¢ç²‰", "و‍œه†»", "ه·§ه…‹هٹ›", "ه’–ه•،豆", + "ن؟‌هپ¥ه“پ", "ç»´ç”ںç´ ", "钙片", "酵素", "ç›ٹç”ںèڈŒ" // Supplements +]; + +function isEdiblePreCheck(title, description) { + const text = (title + " " + description).toLowerCase(); + + // Check strict keywords first + for (const keyword of STRICT_EDIBLE_KEYWORDS) { + if (text.includes(keyword)) { + return { isEdible: true, keyword: keyword }; + } + } + return { isEdible: false }; +} + +// Initialize AI (DeepInfra) +let aiClient = null; + +const AI_TIMEOUT_MS = Number(process.env.AI_TIMEOUT_MS) > 0 ? Number(process.env.AI_TIMEOUT_MS) : 180000; +const AI_MAX_ATTEMPTS = Number(process.env.AI_MAX_ATTEMPTS) > 0 ? Number(process.env.AI_MAX_ATTEMPTS) : 5; +const AI_BASE_RETRY_DELAY_MS = Number(process.env.AI_BASE_RETRY_DELAY_MS) > 0 ? Number(process.env.AI_BASE_RETRY_DELAY_MS) : 1500; + +const PUPPETEER_PROTOCOL_TIMEOUT_MS = + Number(process.env.PUPPETEER_PROTOCOL_TIMEOUT_MS) > 0 + ? Number(process.env.PUPPETEER_PROTOCOL_TIMEOUT_MS) + : 180000; +const PUPPETEER_DEFAULT_TIMEOUT_MS = + Number(process.env.PUPPETEER_DEFAULT_TIMEOUT_MS) > 0 + ? Number(process.env.PUPPETEER_DEFAULT_TIMEOUT_MS) + : 120000; + +let AI_PRIMARY_MODEL = process.env.AI_MODEL || "qwen/qwen-vl-plus"; +let AI_FALLBACK_MODEL = process.env.AI_FALLBACK_MODEL || AI_PRIMARY_MODEL; +let AI_MODEL = AI_PRIMARY_MODEL; +if (process.env.DEEPINFRA_API_KEY) { + AI_PRIMARY_MODEL = process.env.DEEPINFRA_MODEL || process.env.AI_MODEL || "google/gemma-3-12b-it"; + AI_FALLBACK_MODEL = process.env.DEEPINFRA_FALLBACK_MODEL || "google/gemma-3-27b-it"; + AI_MODEL = AI_PRIMARY_MODEL; + aiClient = new OpenAI({ + baseURL: "https://api.deepinfra.com/v1/openai", + apiKey: process.env.DEEPINFRA_API_KEY, + timeout: AI_TIMEOUT_MS, + maxRetries: 0, + }); + console.log(`AI Initialized (DeepInfra: primary=${AI_PRIMARY_MODEL}, fallback=${AI_FALLBACK_MODEL})`); +} else if (process.env.SILICONFLOW_API_KEY) { + // Fallback to SiliconFlow if DeepInfra not set (backward compatibility) + AI_PRIMARY_MODEL = process.env.SILICONFLOW_MODEL || process.env.AI_MODEL || AI_PRIMARY_MODEL; + AI_FALLBACK_MODEL = process.env.SILICONFLOW_FALLBACK_MODEL || process.env.AI_FALLBACK_MODEL || AI_PRIMARY_MODEL; + AI_MODEL = AI_PRIMARY_MODEL; + aiClient = new OpenAI({ + baseURL: "https://api.siliconflow.cn/v1", + apiKey: process.env.SILICONFLOW_API_KEY, + timeout: AI_TIMEOUT_MS, + maxRetries: 0, + }); + console.log(`AI Initialized (SiliconFlow: primary=${AI_PRIMARY_MODEL}, fallback=${AI_FALLBACK_MODEL})`); +} else { + console.log('Warning: No AI API KEY found. AI features will use mock data.'); +} + +const isModelBusyError = (e) => { + const message = (e && e.message) ? String(e.message) : String(e); + const code = (e && e.code) ? e.code : ''; + return ( + message.includes('429') || + String(code) === '429' || + message.toLowerCase().includes('model busy') || + message.toLowerCase().includes('rate limit') || + message.toLowerCase().includes('too many requests') + ); +}; + +const isTimeoutError = (e) => { + const message = (e && e.message) ? String(e.message) : String(e); + const name = (e && e.name) ? String(e.name) : ''; + const code = (e && e.code) ? String(e.code) : ''; + const status = (e && typeof e.status !== 'undefined') ? String(e.status) : ''; + return ( + name.toLowerCase().includes('timeout') || + message.toLowerCase().includes('timeout') || + code === 'ETIMEDOUT' || + code === 'UND_ERR_CONNECT_TIMEOUT' || + code === 'ECONNRESET' || + message.toLowerCase().includes('socket hang up') || + status === '408' + ); +}; + +const AI_BUSY_FALLBACK_MODEL = "google/gemma-3-27b-it"; + + +// --- Configuration --- +// Allow URL to be passed via command line argument +const cliUrl = process.argv[2]; +let CATEGORY_URL = cliUrl && cliUrl.startsWith('http') + ? cliUrl + : 'https://mobile.pinduoduo.com/search_result.html?search_key=%E5%8D%95%E8%82%A9%E5%8C%85%E5%A5%B3&search_type=goods&source=index&options=3&paste=1&search_met_track=manual&refer_page_el_sn=99885&refer_page_name=search_result&refer_page_id=10015_1771136715200_6j6plj2ual&refer_page_sn=10015&page_id=10015_1771136725342_6mr9yzf00z&bsch_is_search_mall=&bsch_show_active_page=&flip=0%3B0%3B0%3B0%3B630af7c3-043b-2964-39b0-12664add80c2%3B%2F20%3B0%3B0%3B47270af4a8bda0d0d524441a2e99ac18&sort_type=default&price_index=0&price=0%2C25&filter=price%2C0%2C25&opt_tag_name=&brand_tab_filter=&item_index=1'; + +if (cliUrl) { + console.log('Using URL from command line:', cliUrl); +} else { + console.log('Using default/hardcoded URL.'); +} + +const TARGET_PRODUCT_COUNT = 999999; // Effectively infinite +const OUTPUT_FILE = path.join(__dirname, '..', 'pinduoduo-products.json'); +const PAGE_LOAD_TIMEOUT = 60000; + +// Global flag for graceful shutdown +let isRunning = true; +process.on('SIGINT', () => { + console.log('\nReceived SIGINT. Stopping scraper gracefully...'); + isRunning = false; +}); + +function askQuestion(query) { + const rl = readline.createInterface({ + input: process.stdin, + output: process.stdout, + }); + return new Promise(resolve => rl.question(query, ans => { + rl.close(); + resolve(ans); + })); +} + +// Helper: Process with AI +async function enrichWithAI(title, description, price) { + if (!aiClient) { + return { + translatedTitle: title + " (Translation Pending)", + translatedDesc: description + " (Translation Pending)", + aiMetadata: { + synonyms: ["Placeholder"], + market_tags: ["Tag"], + category_suggestion: "General" + } + }; + } + + try { + const safeTitle = String(title || '').slice(0, 220); + const safeDescription = String(description || '').slice(0, 1200); + const safePrice = String(price || '').slice(0, 50); + + const prompt = ` + You are a product data enrichment assistant for an Iraqi e-commerce site. + + Original Product Title (Chinese): "${safeTitle}" + Product Description: "${safeDescription}" + Price: "${safePrice}" + + Task: + 1. Extract the Brand Name in English (e.g., "Nike", "Sony", "Xiaomi"). If no brand is found, ignore it. + 2. Translate the Product Name to ARABIC accurately. + - TARGET LANGUAGE: ARABIC (Iraq dialect or MSA). + - INPUT: Chinese -> OUTPUT: Arabic. + - DO NOT output English (except for the Brand Name). + - Remove marketing fluff like "hot sale", "new arrival", "2024", "Ready Stock". + - Example: "ه†¬ه­£هٹ ç»’هچ«è،£" -> "ظƒظ†ط²ط© ط´طھظˆظٹط© ظ…ط¨ط·ظ†ط©" (NOT "Winter Fleece Sweater"). + 3. Combine them into "product_name_ar" format: "[Arabic Name]". + - ONLY include the brand if it is a well-known international brand (e.g. Nike, Adidas, Sony). + - If the brand is generic, unknown, or "No Brand", DO NOT include it in the title. + - NEVER include text like "No Brand", "Generic", "Other", "ماركة غير معروفة" in the title. + - IMPORTANT: You MUST translate the actual title. Do NOT use placeholder text like "اسم المنتج بالعربية". + 4. Extract "product_details_ar" as a structured Key-Value JSON object in ARABIC. + 5. Generate "aiMetadata" based strictly on the product Title and Description. + - "synonyms": Array of 3-5 alternative Arabic names SPECIFIC to this product. + - "market_tags": Array of 3-5 relevant tags in Arabic. + - "category_suggestion": A specific category path in Arabic. + 6. DETECT IF THE PRODUCT IS EDIBLE (Food, Drink, Nuts, Cans, Snacks, Ingredients, Supplements, Vitamins, Medicine). + - Set "is_edible": true if it is food/edible/supplement. + - Set "is_edible": false if it is NOT edible (e.g. clothes, electronics, tools). + - BE VERY CAREFUL. "Food Container" is NOT edible. "Dog Food" IS edible (sort of, but usually restricted). "Almond Oil for Skin" is NOT edible (cosmetic). "Almond Oil for Cooking" IS edible. + - If in doubt, set true to be safe. + + CRITICAL INSTRUCTIONS: + - The "product_name_ar" MUST be in ARABIC script (except the brand). + - If the original title is "WASSUP BEAVER...", translate "WASSUP BEAVER" as the Brand, and the rest as the Arabic name. + - NEVER return "اسم غير متوفر" (Name Not Available). ALWAYS generate a descriptive Arabic name based on the description if the title is unclear. + - Example: If title is "2025 Winter Jacket", output "سترة شتوية 2025". + - The translation MUST be high quality and natural for Arabic speakers in Iraq. + - If the product name is vague or generic in Chinese, infer the specific type from description or context. + - The "product_details_ar" field MUST be a JSON OBJECT (key-value pairs), NOT a string. + - Example format for details: + "product_details_ar": { + "المادة": "قماش كتان", + "الميزة": "ألوان متعددة", + "التصميم": "إبداعي", + "الاستخدام": "غرفة المعيشة" + } + - STRICTLY EXCLUDE any "return policy", "refund", "replacement", "shipping", "free shipping", or "guarantee" information from details. + - STRICTLY EXCLUDE any PRICE or COST information (e.g., "السعر", "Price", "29.9 ريال") from details. + - DO NOT include keys with EMPTY values (e.g. "الماركة": "" should be removed). + - Do NOT include any Chinese characters (like ¥, 包邮, 品牌, etc.) in values. + - English text IS ALLOWED for Brand Names and Model Numbers. + - Convert all prices and measurements to Arabic format if possible. + + Return ONLY a valid JSON object with this structure (no markdown): + { + "product_name_ar": "Put Translated Name Here", + "is_edible": false, + "product_details_ar": { + "الماركة": "قيمة", + "اللون": "قيمة", + "المادة": "قيمة" + }, + "aiMetadata": { + "synonyms": ["مرادف1", "مرادف2"], + "market_tags": ["تاق1", "تاق2"], + "category_suggestion": "اسم التصنيف" + } + } + `; + + let attempts = 0; + + while (attempts < AI_MAX_ATTEMPTS) { + try { + const create = async (model) => { + return await aiClient.chat.completions.create({ + model, + messages: [{ role: "user", content: prompt }], + temperature: 0.2, + max_tokens: 900, + }); + }; + + let response; + try { + response = await create(AI_PRIMARY_MODEL); + } catch (e) { + if (isTimeoutError(e)) { + throw e; + } + if (isModelBusyError(e)) { + console.log(`AI busy on ${AI_PRIMARY_MODEL}. Falling back to ${AI_BUSY_FALLBACK_MODEL}...`); + response = await create(AI_BUSY_FALLBACK_MODEL); + } else if (AI_FALLBACK_MODEL && AI_FALLBACK_MODEL !== AI_PRIMARY_MODEL) { + console.log(`AI error on ${AI_PRIMARY_MODEL}. Falling back to ${AI_FALLBACK_MODEL}...`); + response = await create(AI_FALLBACK_MODEL); + } else { + throw e; + } + } + + let text = response.choices[0].message.content; + text = text.replace(/```json/g, '').replace(/```/g, '').trim(); + + // Attempt to fix common JSON syntax errors from AI + // 1. Remove trailing commas in objects/arrays: ,} -> } or ,] -> ] + text = text.replace(/,(\s*[}\]])/g, '$1'); + + const jsonStart = text.indexOf('{'); + let parsed = null; + + if (jsonStart !== -1) { + let endSearchPos = text.lastIndexOf('}'); + while (endSearchPos > jsonStart) { + try { + const candidate = text.substring(jsonStart, endSearchPos + 1); + parsed = JSON.parse(candidate); + break; + } catch (e) { + endSearchPos = text.lastIndexOf('}', endSearchPos - 1); + } + } + } + + if (!parsed) { + console.error("Failed to parse AI response. Raw text:", text); + throw new Error("JSON parsing failed after multiple attempts."); + } + + // CHECK FOR INVALID/PLACEHOLDER NAMES + if (parsed.product_name_ar) { + const badNames = [ + 'اسم غير متوفر', + 'name not available', + 'اسم المنتج بالعربيه', + 'اسم المنتج بالعربية', + 'put translated name here', + 'arabic name', + 'ترجمة اسم المنتج' + ]; + const lowerName = parsed.product_name_ar.toLowerCase(); + + // Check if name matches any bad pattern or contains Chinese + if (badNames.some(bad => lowerName.includes(bad)) || /[\u4e00-\u9fa5]/.test(parsed.product_name_ar)) { + console.log(`AI returned invalid name: "${parsed.product_name_ar}". Retrying...`); + throw new Error('AI returned invalid name (placeholder or Chinese)'); + } + } else { + throw new Error('AI returned empty product_name_ar'); + } + + try { + const stripChinese = (str) => { + if (typeof str !== 'string') return str; + // Don't strip immediately, let's keep it for now or refine logic + // Only strip if it's mixed, but for Arabic name we want PURE Arabic. + // However, if AI returns "Brand (English) + Arabic", that's fine. + return str.trim(); + }; + + // if (parsed.product_name_ar) { ... } // Removed redundant check block since we did it above + + if (parsed.product_details_ar) { + for (const key in parsed.product_details_ar) { + // Strip Chinese + parsed.product_details_ar[key] = stripChinese(parsed.product_details_ar[key]); + + // Check if value still has Chinese characters + if (/[\u4e00-\u9fa5]/.test(parsed.product_details_ar[key])) { + delete parsed.product_details_ar[key]; // Remove key if translation failed + } + + // Remove empty keys + if (!parsed.product_details_ar[key] || parsed.product_details_ar[key].trim() === '') { + delete parsed.product_details_ar[key]; + } + } + } + + if (parsed.aiMetadata) { + // Ensure arrays are arrays + if (!Array.isArray(parsed.aiMetadata.synonyms)) parsed.aiMetadata.synonyms = []; + if (!Array.isArray(parsed.aiMetadata.market_tags)) parsed.aiMetadata.market_tags = []; + if (!parsed.aiMetadata.category_suggestion) parsed.aiMetadata.category_suggestion = "ط¹ط§ظ…"; + } else { + // Fallback: Try to infer from parsed name if possible, otherwise use generic but marked as fallback + parsed.aiMetadata = { + synonyms: [parsed.product_name_ar], // Use the name itself as a synonym at least + market_tags: ["ظ…ظ†طھط¬ ظ…ظ…ظٹط²"], + category_suggestion: "ط£ط®ط±ظ‰" + }; + } + + return parsed; + } catch (jsonError) { + throw jsonError; + } + } catch (e) { + attempts++; + const message = (e && e.message) ? e.message : String(e); + console.error(`AI Error (Attempt ${attempts}/${AI_MAX_ATTEMPTS}):`, message); + + const isRateLimit = isModelBusyError(e) || message.includes('429'); + const isTimeout = isTimeoutError(e); + + if (isRateLimit) { + const waitTime = Math.min(45000, 5000 * attempts) + Math.floor(Math.random() * 1000); + console.log(`Rate limit hit. Waiting ${(waitTime / 1000).toFixed(1)}s...`); + await delay(waitTime); + continue; + } + + if (isTimeout) { + const waitTime = Math.min(45000, AI_BASE_RETRY_DELAY_MS * (2 ** Math.max(0, attempts - 1))) + Math.floor(Math.random() * 1000); + await delay(waitTime); + continue; + } + + await delay(2000 + Math.floor(Math.random() * 500)); + } + } + throw new Error("Max AI attempts reached"); + } catch (e) { + console.error("AI Generation Error:", e.message); + // CRITICAL CHANGE: If all attempts failed or returned bad names, SKIP this product. + // Return a special flag to the caller. + return { + shouldSkip: true, + reason: "AI Translation Failed (Max Attempts)" + }; + } +} + +const CHROME_PATHS = [ + 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe', + 'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe', + 'C:\\Program Files\\Microsoft\\Edge\\Application\\msedge.exe', + 'C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe' +]; + +function getExecutablePath() { + for (const p of CHROME_PATHS) { + if (fs.existsSync(p)) return p; + } + return null; +} + +const delay = (ms) => new Promise(resolve => { + const end = Date.now() + ms; + const timer = setInterval(() => { + if (Date.now() >= end) { + clearInterval(timer); + resolve(); + } + }, 100); +}); +const humanDelay = (min = 1000, max = 3000) => delay(Math.floor(Math.random() * (max - min + 1)) + min); + +async function applyPageTimeouts(page) { + if (!page) return; + try { page.setDefaultTimeout(PUPPETEER_DEFAULT_TIMEOUT_MS); } catch (e) {} + try { page.setDefaultNavigationTimeout(PUPPETEER_DEFAULT_TIMEOUT_MS); } catch (e) {} +} + +async function waitForStableUrl(page, stableMs = 1200, timeoutMs = 12000) { + const start = Date.now(); + let lastUrl = ''; + let lastChangeAt = Date.now(); + try { lastUrl = page.url(); } catch (e) { lastUrl = ''; } + lastChangeAt = Date.now(); + + while (Date.now() - start < timeoutMs) { + if (!page || (page.isClosed && page.isClosed())) return lastUrl; + await delay(200); + let cur = ''; + try { cur = page.url(); } catch (e) { cur = lastUrl; } + if (cur && cur !== lastUrl) { + lastUrl = cur; + lastChangeAt = Date.now(); + } + if (Date.now() - lastChangeAt >= stableMs) return lastUrl; + } + return lastUrl; +} + +async function safeEvaluate(page, pageFunction, args = [], maxAttempts = 4) { + let lastErr = null; + for (let attempt = 1; attempt <= maxAttempts; attempt++) { + try { + return await page.evaluate(pageFunction, ...args); + } catch (e) { + lastErr = e; + const msg = String(e?.message || e || ''); + const isContextDestroyed = + msg.includes('Execution context was destroyed') || + msg.includes('Cannot find context') || + msg.includes('Target closed') || + msg.includes('Session closed') || + msg.includes('Most likely the page has been closed') || + msg.includes('Navigating frame was detached') || + msg.includes('frame was detached'); + + if (!isContextDestroyed) throw e; + + try { + await delay(300 * attempt); + await Promise.race([ + page.waitForNavigation({ waitUntil: 'domcontentloaded', timeout: 8000 }).catch(() => null), + waitForStableUrl(page, 1400, 12000) + ]); + } catch (e2) {} + } + } + throw lastErr || new Error('safeEvaluate failed'); +} + +async function createBrowser() { + const executablePath = getExecutablePath(); + if (!executablePath) { + console.error('Chrome/Edge executable not found.'); + process.exit(1); + } + + return await puppeteer.launch({ + executablePath, + headless: false, + defaultViewport: null, + protocolTimeout: PUPPETEER_PROTOCOL_TIMEOUT_MS, + // userDataDir: 'chrome_data_pdd_fresh_v36', + userDataDir: 'chrome_data_pdd_persistent', // Use fixed directory to keep session alive + args: [ + '--no-sandbox', + '--disable-setuid-sandbox', + '--disable-infobars', + '--window-position=0,0', + '--ignore-certificate-errors', + '--ignore-certificate-errors-spki-list', + '--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36', + '--lang=zh-CN,zh' + ] + }); +} + +async function autoScroll(page) { + await page.evaluate(async () => { + await new Promise((resolve) => { + let totalHeight = 0; + const distance = 100; + const timer = setInterval(() => { + const scrollHeight = document.body.scrollHeight; + window.scrollBy(0, distance); + totalHeight += distance; + if (totalHeight >= 600) { + clearInterval(timer); + resolve(); + } + }, 100); + }); + }); +} + +async function run() { + console.log('[Start] Initializing Pinduoduo Scraper (Click-and-Scrape Mode)...'); + + // Ask for URL or use predefined + console.log('----------------------------------------------------'); + let urlInput = ''; + + // Check if CATEGORY_URL is already set in the code (length > 10) + if (CATEGORY_URL && CATEGORY_URL.length > 10) { + urlInput = CATEGORY_URL; + console.log('Using predefined CATEGORY_URL from script.'); + } else if (process.argv[2]) { + urlInput = process.argv[2]; + } else { + urlInput = await askQuestion('Enter the Pinduoduo Category URL to scrape: '); + } + + urlInput = urlInput.trim(); + if (!urlInput.startsWith('http')) { + console.error('â‌Œ Error: Invalid URL provided. The URL must start with "http" or "https".'); + console.error('You entered:', urlInput); + console.log('Please restart the script and paste the correct URL.'); + process.exit(1); + } + + // const urlInput = "https://mobile.pinduoduo.com/catgoods.html?refer_page_name=index&opt_id=25667&opt_name=%E4%B8%8A%E8%A1%A3%E5%A4%96%E5%A5%97&opt_type=2&goods_id=836596630021&refer_page_id=10002_1770945474906_zhvvkggy6l&refer_page_sn=10002"; + console.log('Using URL:', urlInput); + console.log('----------------------------------------------------'); + CATEGORY_URL = urlInput.trim(); + + let browser = await createBrowser(); + console.log('Browser launched'); + let page = await browser.newPage(); + console.log('Page created'); + + // Enable console log forwarding from the browser to the terminal + page.on('console', msg => { + const type = msg.type(); + const text = msg.text(); + // Filter out some noise if needed, but user wants logs so keep most + if (!text.includes('ERR_BLOCKED_BY_CLIENT')) { + console.log(`[Browser Console] ${type.toUpperCase()}: ${text}`); + } + }); + + page.on('pageerror', err => { + console.log(`[Browser Error]: ${err.toString()}`); + }); + + await applyPageTimeouts(page); + + // --- STEALTH MEASURES --- + + // 1. Set Mobile Viewport (Android) + // await page.setViewport({ width: 360, height: 800, isMobile: true, hasTouch: true }); + + // Switch to Desktop Viewport + await page.setViewport({ width: 1366, height: 768 }); + + // 2. Override Navigator Properties to mimic Android + await page.evaluateOnNewDocument(() => { + // Force language to Chinese + Object.defineProperty(navigator, 'language', { get: () => 'zh-CN' }); + Object.defineProperty(navigator, 'languages', { get: () => ['zh-CN', 'zh'] }); + + // Add minimal mouse movement to simulate human + window.addEventListener('load', () => { + document.body.addEventListener('mousemove', () => {}); + document.body.addEventListener('touchstart', () => {}); + }); + }); + + // 4. Load cookies if exist + try { + const cookiePath = path.join(__dirname, 'pdd_cookies.json'); + if (fs.existsSync(cookiePath)) { + const cookies = JSON.parse(fs.readFileSync(cookiePath, 'utf8')); + if (cookies.length > 0) { + console.log(`Loading ${cookies.length} saved cookies...`); + await page.setCookie(...cookies); + } + } + } catch (err) { + console.error('Failed to load cookies:', err.message); + } + + // 5. Perform Login DIRECTLY on the target Category Page + // Why? Navigating from Home -> Category often triggers "Drifting" or "Bot Detection". + // It's better to just go straight to the category, log in there if needed, and then start scraping. + + // FORCE LOGIN NAVIGATION IF NOT LOGGED IN + console.log('Visiting Login URL first to ensure valid session...'); + try { + await page.goto('https://mobile.pinduoduo.com/login.html', { waitUntil: 'domcontentloaded', timeout: PAGE_LOAD_TIMEOUT }); + } catch(e) { console.log('Login goto error (might be redirect):', e.message); } + + console.log('Login page loaded (or redirected).'); + + console.log('================================================================'); + console.log(' PAUSING FOR MANUAL LOGIN (30 seconds)'); + console.log(' 1. Please login manually using SMS/Phone.'); + console.log(' 2. Once logged in, you should see the home page.'); + console.log(' 3. The script will then redirect to the category page.'); + console.log('================================================================'); + await delay(30000); + + // CLEAN CATEGORY URL to remove tracking params + let cleanUrl = CATEGORY_URL; + try { + const u = new URL(CATEGORY_URL); + const searchKey = u.searchParams.get('search_key'); + const catId = u.searchParams.get('cat_id'); + const optId = u.searchParams.get('opt_id'); + + // Construct a clean URL + if (searchKey) { + cleanUrl = `https://mobile.pinduoduo.com/search_result.html?search_key=${encodeURIComponent(searchKey)}&search_type=goods`; + } else if (catId) { + cleanUrl = `https://mobile.pinduoduo.com/catgoods.html?cat_id=${catId}&opt_id=${optId || catId}`; + } else if (optId) { + cleanUrl = `https://mobile.pinduoduo.com/catgoods.html?opt_id=${optId}`; + } + + console.log('Original URL:', CATEGORY_URL); + console.log('Cleaned URL:', cleanUrl); + } catch(e) { + console.log('Error cleaning URL:', e.message); + cleanUrl = CATEGORY_URL; // Fallback + } + + console.log('Visiting Clean Category URL:', cleanUrl); + await page.goto(cleanUrl, { waitUntil: 'domcontentloaded', timeout: PAGE_LOAD_TIMEOUT }); + console.log('Category page loaded.'); + + // SWITCH TO MOBILE VIEWPORT AFTER LOGIN & NAVIGATION + console.log('Switching to Mobile Viewport for scraping...'); + await page.setViewport({ width: 360, height: 800, isMobile: true, hasTouch: true }); + await delay(2000); + + /* + console.log('Visiting Category URL (and performing login check there):', CATEGORY_URL); + await page.goto(CATEGORY_URL, { waitUntil: 'domcontentloaded', timeout: PAGE_LOAD_TIMEOUT }); + console.log('Goto done'); + + console.log('================================================================'); + console.log(' PAUSING FOR MANUAL LOGIN / CHECK (40 seconds)'); + console.log(' 1. If you see a login screen, please log in.'); + console.log(' 2. If you see "Sold Out", try refreshing manually.'); + console.log(' 3. Make sure you see the product list before this timer ends.'); + console.log('================================================================'); + console.log('Starting delay...'); + await delay(40000); + console.log('Delay finished. Resuming...'); + */ + + // SAVE COOKIES AFTER LOGIN + try { + const cookies = await page.cookies(); + const cookiePath = path.join(__dirname, 'pdd_cookies.json'); + fs.writeFileSync(cookiePath, JSON.stringify(cookies, null, 2)); + console.log('✅ Login cookies saved to pdd_cookies.json'); + } catch (err) { + console.error('Failed to save cookies:', err.message); + } + + // Wait extra time for the page to fully stabilize + console.log('Waiting 5s for page stabilization...'); + await delay(5000); + + // --- SCROLL PAST HEADER --- + console.log('Scrolling down to bypass header/category icons...'); + + try { + // Scroll down one full screen height + a bit more + await page.evaluate(async () => { + const viewportHeight = window.innerHeight; + window.scrollBy(0, viewportHeight + 200); + await new Promise(r => setTimeout(r, 1000)); + }); + } catch (e) { + console.warn('âڑ ï¸ڈ Scroll error (ignoring):', e.message); + // If execution context destroyed, it usually means page refreshed or navigated. + // We can just wait a bit and proceed. + await delay(1000); + } + + await humanDelay(2000, 3000); + + // 3. Click and Scrape Loop + console.log('[Phase 1] Starting Click-and-Scrape Loop...'); + + // STRATEGY CHANGE: Blind Click in Center-Right + // Since element detection is being blocked or misled by PDD's anti-bot structure, + // we will simulate a human tapping on a likely product location. + // On mobile view (375x667 approx), products are usually in a 2-column grid. + // A tap at roughly (75% width, 50% height) should hit the right-side product. + + let products = []; + try { + if (fs.existsSync(OUTPUT_FILE)) { + products = JSON.parse(fs.readFileSync(OUTPUT_FILE)); + } + } catch(e) {} + + // Main Loop + // User requested infinite loop until manually stopped + while (isRunning) { + + // --- VALIDATE CURRENT URL --- + // Ensure we are still on the category page or search result page we started with. + // If we drifted to home or another category, go back. + const currentUrlBeforeScroll = page.url(); + const isHomePage = currentUrlBeforeScroll === 'https://mobile.pinduoduo.com/' || currentUrlBeforeScroll.includes('page_id=10002'); + // Simple check: if we are not on the category URL and not on a product page (which we shouldn't be here), go back. + // Better: Check if the URL contains key parts of our CATEGORY_URL + // Extract 'search_key' from CATEGORY_URL if it exists + let requiredParam = ''; + try { + const catUrlObj = new URL(CATEGORY_URL); + if (catUrlObj.searchParams.has('search_key')) { + requiredParam = 'search_key=' + encodeURIComponent(catUrlObj.searchParams.get('search_key')); + } else if (catUrlObj.searchParams.has('cat_id')) { + requiredParam = 'cat_id=' + catUrlObj.searchParams.get('cat_id'); + } + } catch(e) {} + + // DISABLE AUTO-REDIRECT for now - it's causing loops if the URL format changes slightly + // if (isHomePage || (requiredParam && !currentUrlBeforeScroll.includes(decodeURIComponent(requiredParam)) && !currentUrlBeforeScroll.includes(requiredParam))) { + // console.log('WARNING: Drifted away from category page. Redirecting back to:', CATEGORY_URL); + // await page.goto(CATEGORY_URL, { waitUntil: 'domcontentloaded', timeout: PAGE_LOAD_TIMEOUT }); + // await humanDelay(3000, 5000); + // } + + + // --- 4-POINT BLIND CLICK STRATEGY --- + console.log('Scrolling down to find new batch of products...'); + + // 1. Scroll down one screen size + a bit + try { + await page.evaluate(async () => { + // Random scroll + const viewportHeight = window.innerHeight; + const distance = viewportHeight + 100 + Math.floor(Math.random() * 200); + window.scrollBy(0, distance); + await new Promise(r => setTimeout(r, 1000)); + }); + } catch (e) { + console.warn('âڑ ï¸ڈ Scroll error in loop (recovering):', e.message); + // Wait and reload context if needed + await delay(2000); + if (page.isClosed()) break; + continue; // Skip this iteration + } + + await humanDelay(2000, 3000); + + // Define the 4 click points (percentages of viewport) + // Adjust for Mobile Viewport in Desktop Browser + const clickPoints = [ + { name: "Top-Right", xPct: 0.75, yPct: 0.30 }, + { name: "Top-Left", xPct: 0.25, yPct: 0.30 }, + { name: "Bot-Left", xPct: 0.25, yPct: 0.70 }, + { name: "Bot-Right", xPct: 0.75, yPct: 0.70 } + ]; + + for (const point of clickPoints) { + if (!isRunning) break; + // if (products.length >= TARGET_PRODUCT_COUNT) break; // Removed limit as per request + + console.log(`Preparing to click: ${point.name}...`); + + const clickCoordinates = await page.evaluate((pt) => { + const width = window.innerWidth; + const height = window.innerHeight; + + // Add randomization (+/- 15px) + const randomX = Math.floor(Math.random() * 30) - 15; + const randomY = Math.floor(Math.random() * 30) - 15; + + return { + x: Math.floor(width * pt.xPct) + randomX, + y: Math.floor(height * pt.yPct) + randomY + }; + }, point); + + console.log(`Clicking at (${clickCoordinates.x}, ${clickCoordinates.y})...`); + + // Listen for new target + const newTargetPromise = new Promise(resolve => browser.once('targetcreated', resolve)); + const currentUrl = page.url(); + + try { + // Use evaluating touchstart for mobile simulation if mouse click fails + await page.mouse.click(clickCoordinates.x, clickCoordinates.y); + } catch (e) { + console.log('Click failed:', e.message); + } + + // Wait for navigation + let newPage = null; + let navigationHappened = false; + + try { + const target = await Promise.race([ + newTargetPromise, + delay(3000).then(() => null) + ]); + + if (target && target.type() === 'page') { + console.log('New tab detected.'); + newPage = await target.page(); + + // ENABLE CONSOLE LOGS FOR NEW TAB + newPage.on('console', msg => { + const type = msg.type(); + const text = msg.text(); + if (!text.includes('ERR_BLOCKED_BY_CLIENT')) { + console.log(`[Browser NewPage] ${type.toUpperCase()}: ${text}`); + } + }); + + await applyPageTimeouts(newPage); + + // STEALTH: Ensure new page looks like it came from the main page + await newPage.bringToFront(); + + // IMPORTANT: Set viewport for the new tab too! + await newPage.setViewport({ width: 360, height: 800, isMobile: true, hasTouch: true }); + + try { + await newPage.setExtraHTTPHeaders({ + 'Referer': currentUrl, + // 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8' // Already handled by args + }); + } catch(e) {} + } else { + console.log('No new tab. Checking if current page navigated...'); + await delay(2000); + if (page.url() !== currentUrl && !page.url().includes('catgoods')) { + console.log('Current page navigated. Treating as product page.'); + newPage = page; + navigationHappened = true; + await applyPageTimeouts(newPage); + } else { + console.log('Click did not trigger navigation. Moving to next point.'); + // Just continue to next point in loop + continue; + } + } + } catch (e) { + console.log('Target detection error:', e.message); + continue; + } + + if (!newPage) continue; + + // --- SCRAPE PRODUCT PAGE --- + try { + await newPage.waitForLoadState ? newPage.waitForLoadState('domcontentloaded') : newPage.waitForSelector('body', { timeout: 15000 }); + await humanDelay(2000, 4000); + await waitForStableUrl(newPage, 1200, 12000); + + // CHECK FOR "SOLD OUT" STATE + const isLogin = await safeEvaluate(newPage, () => { + const t = (document.body && document.body.innerText) ? document.body.innerText : ''; + const s = String(t || ''); + return s.includes('ç™»ه½•') && (s.includes('و‰«ç پç™»ه½•') || s.includes('هگŒو„ڈوœچهٹ،هچڈè®®') || s.includes('éڑگç§پو”؟ç­–')); + }, [], 12); + + if (isLogin) { + console.log('âڑ ï¸ڈ Hit login page. Skipping product and returning to listing...'); + if (!navigationHappened && newPage.close) await newPage.close(); + else { + try { + await newPage.goBack({ waitUntil: 'domcontentloaded', timeout: PAGE_LOAD_TIMEOUT }); + } catch (e) { + try { + await newPage.goto(currentUrl || CATEGORY_URL, { waitUntil: 'domcontentloaded', timeout: PAGE_LOAD_TIMEOUT }); + } catch (e2) {} + } + } + continue; + } + + const isSoldOut = await safeEvaluate(newPage, () => { + const text = document.body.innerText; + return text.includes('ه•†ه“په·²ه”®ç½„') || text.includes('ه·²ه”®ه®Œ') || text.includes('ن¸‹و‍¶'); + }); + + if (isSoldOut) { + console.log('âڑ ï¸ڈ Product is SOLD OUT (or Anti-Bot triggered). Skipping...'); + console.log(' -> Hint: If this happens for ALL products, try deleting pdd_cookies.json and re-login.'); + if (!navigationHappened) await newPage.close(); + else await newPage.goBack(); + continue; + } + + const productUrl = newPage.url(); + console.log(`Scraping Product URL: ${productUrl}`); + + // --- ROBUST DEDUPLICATION --- + try { + const urlObj = new URL(productUrl); + const goodsId = urlObj.searchParams.get('goods_id'); + + if (goodsId) { + // 1. Check if already in current session (in-memory) + const alreadyScrapedInSession = products.some(p => p.url && p.url.includes(goodsId)); + if (alreadyScrapedInSession) { + console.log(`Product already scraped in THIS SESSION. Skipping: ${goodsId}`); + if (!navigationHappened) await newPage.close(); + else await newPage.goBack(); + continue; + } + + // 2. Check Database + const existingProduct = await prisma.product.findFirst({ + where: { + purchaseUrl: { + contains: goodsId + } + } + }); + + if (existingProduct) { + console.log(`Product already in DB (ID: ${existingProduct.id}). Skipping: ${goodsId}`); + if (!navigationHappened) await newPage.close(); + else await newPage.goBack(); + continue; + } + } + } catch (dbCheckError) { + console.error('Error checking DB for duplicate:', dbCheckError.message); + } + + // Deduplicate by URL (Fallback) + if (products.some(p => p.url === productUrl)) { + console.log('Duplicate product URL. Skipping.'); + if (!navigationHappened) await newPage.close(); + else await newPage.goBack(); + continue; + } + + // --- WAIT FOR PAGE LOAD --- + // Ensure the page is fully loaded before scraping + try { + await newPage.waitForLoadState ? newPage.waitForLoadState('domcontentloaded') : newPage.waitForSelector('body', { timeout: 15000 }); + await humanDelay(2000, 4000); + } catch (e) { + console.log('Page load timeout, attempting scrape anyway...'); + } + + /* + // --- RANDOM MOVES ON PRODUCT PAGE (Anti-Detection) --- + console.log('Performing random moves on product page...'); + try { + await newPage.evaluate(async () => { + const wait = (ms) => new Promise(r => setTimeout(r, ms)); + const height = document.body.scrollHeight; + + // Scroll down a bit + window.scrollBy(0, 300 + Math.random() * 200); + await wait(1000 + Math.random() * 1000); + + // Scroll up a bit + window.scrollBy(0, -100); + await wait(500 + Math.random() * 500); + + // Maybe scroll to bottom + if (Math.random() > 0.5) { + window.scrollTo(0, height * 0.7); + await wait(1000); + } + }); + + // Stay on page for 5-10 seconds + const stayTime = 5000 + Math.random() * 5000; + console.log(`Staying on product page for ${(stayTime/1000).toFixed(1)}s...`); + await delay(stayTime); + } catch(e) { + console.log('Random moves failed:', e.message); + } + */ + + const openOptionsModalIfNeeded = async (page) => { + const modalSelector = '.HidQ9ROd, div[role="dialog"][aria-modal="true"], div[role="dialog"]'; + + const hasVisibleSkuModal = async () => { + return await page.evaluate((sel) => { + const visible = (el) => { + if (!el) return false; + if (el.getAttribute && el.getAttribute('aria-hidden') === 'true') return false; + const style = window.getComputedStyle(el); + if (!style) return false; + if (style.display === 'none' || style.visibility === 'hidden') return false; + const opacity = parseFloat(style.opacity || '1'); + if (!Number.isNaN(opacity) && opacity <= 0.02) return false; + const r = el.getBoundingClientRect(); + if (!r || r.width < 40 || r.height < 40) return false; + const intersects = + r.bottom > 0 && + r.right > 0 && + r.top < window.innerHeight && + r.left < window.innerWidth; + if (!intersects) return false; + const x = Math.floor(Math.min(window.innerWidth - 2, Math.max(1, r.left + r.width * 0.5))); + const y = Math.floor(Math.min(window.innerHeight - 2, Math.max(1, r.top + r.height * 0.5))); + const top = document.elementFromPoint(x, y); + if (top && (el === top || el.contains(top))) return true; + return false; + }; + + const isSku = (m) => { + try { + if (m && m.matches && m.matches('.HidQ9ROd')) return true; + } catch (e) {} + if (m && m.querySelector && m.querySelector('.iW4aEGbb')) return false; + const t = String(m?.innerText || m?.textContent || ''); + if (t.includes('ه·²é€‰') || t.includes('请选و‹©') || t.includes('è§„و ¼')) return true; + if (m.querySelector('.O7pEFvHR') || m.querySelector('.bIhLWVqm') || m.querySelector('li.TpUpcNRp') || m.querySelector('div._8gg8ho2u')) return true; + return false; + }; + + const modals = Array.from(document.querySelectorAll(sel)); + return modals.some(m => visible(m) && isSku(m)); + }, modalSelector).catch(() => false); + }; + + if (await hasVisibleSkuModal()) { + console.log('[PDD] Options modal already open'); + return true; + } + + const tryClickAndWaitModal = async (x, y, modalWaitMs = 2500) => { + let before = ''; + try { before = page.url(); } catch (e) { before = ''; } + + try { + try { await page.mouse.move(Math.max(1, x - 18), Math.max(1, y - 18)); } catch (e) {} + await humanDelay(700, 1200); + await page.mouse.click(x, y); + } catch (e) { + return false; + } + + await humanDelay(1200, 2200); + const ok = await page.waitForFunction( + (sel) => { + const visible = (el) => { + if (!el) return false; + if (el.getAttribute && el.getAttribute('aria-hidden') === 'true') return false; + const style = window.getComputedStyle(el); + if (!style) return false; + if (style.display === 'none' || style.visibility === 'hidden') return false; + const opacity = parseFloat(style.opacity || '1'); + if (!Number.isNaN(opacity) && opacity <= 0.02) return false; + const r = el.getBoundingClientRect(); + if (!r || r.width < 40 || r.height < 40) return false; + const intersects = + r.bottom > 0 && + r.right > 0 && + r.top < window.innerHeight && + r.left < window.innerWidth; + if (!intersects) return false; + const x = Math.floor(Math.min(window.innerWidth - 2, Math.max(1, r.left + r.width * 0.5))); + const y = Math.floor(Math.min(window.innerHeight - 2, Math.max(1, r.top + r.height * 0.5))); + const top = document.elementFromPoint(x, y); + if (top && (el === top || el.contains(top))) return true; + return false; + }; + + const isSku = (m) => { + try { + if (m && m.matches && m.matches('.HidQ9ROd')) return true; + } catch (e) {} + if (m && m.querySelector && m.querySelector('.iW4aEGbb')) return false; + const t = String(m?.innerText || m?.textContent || ''); + if (t.includes('ه·²é€‰') || t.includes('请选و‹©') || t.includes('è§„و ¼')) return true; + if (m.querySelector('.O7pEFvHR') || m.querySelector('.bIhLWVqm') || m.querySelector('li.TpUpcNRp') || m.querySelector('div._8gg8ho2u')) return true; + return false; + }; + + const modals = Array.from(document.querySelectorAll(sel)); + return modals.some(m => visible(m) && isSku(m)); + }, + { timeout: modalWaitMs }, + modalSelector + ).catch(() => null); + if (ok) return true; + + let after = ''; + try { after = page.url(); } catch (e) { after = before; } + if (after.includes('/order_checkout.html') || after.includes('order_checkout.html')) { + try { + await page.goBack({ waitUntil: 'domcontentloaded', timeout: PAGE_LOAD_TIMEOUT }); + await waitForStableUrl(page, 1400, 15000); + } catch (e) {} + } + + return false; + }; + + await waitForStableUrl(page, 1200, 15000); + + const getViewport = async () => { + const vp = (page.viewport && page.viewport()) ? page.viewport() : null; + if (vp && vp.width && vp.height) return { width: vp.width, height: vp.height }; + const ev = await page.evaluate(() => ({ width: window.innerWidth, height: window.innerHeight })).catch(() => null); + return { width: ev?.width || 360, height: ev?.height || 800 }; + }; + + const tryOpenViaBottomRight = async (modalWaitMs = 9000) => { + const vp = await getViewport(); + const clamp = (v, min, max) => Math.max(min, Math.min(max, v)); + const maxX = Math.floor(vp.width - 2); + const maxY = Math.floor(vp.height - 2); + const marginX = 3 + Math.floor(Math.random() * 9); + const marginY = 1 + Math.floor(Math.random() * 6); + + const x = clamp(maxX - marginX, 1, maxX); + const y = clamp(maxY - marginY, 1, maxY); + + console.log(`[PDD] Trying to open options via bottom-right click (x=${x},y=${y})`); + return await tryClickAndWaitModal(x, y, modalWaitMs); + }; + + for (let attempt = 0; attempt < 5; attempt++) { + if (attempt > 0) await humanDelay(1400, 2600); + const ok = await tryOpenViaBottomRight(9000); + if (ok) return true; + } + + return false; + }; + + const clickO7pEFvHRAndWait = async (page, scopeSelectors = null) => { + const closeIfIwwPopupOpened = async () => { + const pt = await page.evaluate(() => { + const popup = document.querySelector('.iW4aEGbb'); + if (!popup) return null; + const close = + popup.querySelector('div[role="button"][aria-label*="ه…³é—­"]') || + popup.querySelector('button[aria-label*="ه…³é—­"]') || + popup.querySelector('div[role="button"][aria-label="ه…³é—­ه¼¹çھ—"]') || + popup.querySelector('div[role="button"][aria-label="ه…³é—­"]') || + popup.querySelector('button') || + null; + const el = close || popup; + const r = el.getBoundingClientRect(); + if (!r || r.width < 4 || r.height < 4) return { x: Math.floor(window.innerWidth / 2), y: Math.floor(window.innerHeight * 0.2) }; + const x = Math.floor(r.left + r.width * 0.5); + const y = Math.floor(r.top + r.height * 0.5); + return { x, y }; + }).catch(() => null); + + if (!pt?.x || !pt?.y) return false; + + try { + for (let i = 0; i < 2; i++) { + try { await page.mouse.move(Math.max(1, pt.x - 16), Math.max(1, pt.y - 16)); } catch (e) {} + await humanDelay(450, 900); + await page.mouse.click(pt.x, pt.y); + await humanDelay(650, 1200); + const still = await page.$('.iW4aEGbb').catch(() => null); + if (!still) return true; + } + } catch (e) {} + return false; + }; + + const clickNormalizedPoint = async (nx, ny) => { + const vp = (page.viewport && page.viewport()) ? page.viewport() : null; + const width = (vp && vp.width) ? vp.width : 360; + const height = (vp && vp.height) ? vp.height : 800; + const clamp = (v, min, max) => Math.max(min, Math.min(max, v)); + const x = clamp(Math.floor((Number(nx) / 1000) * width), 1, Math.floor(width - 2)); + const y = clamp(Math.floor((Number(ny) / 1000) * height), 1, Math.floor(height - 2)); + try { + try { await page.mouse.move(Math.max(1, x - 18), Math.max(1, y - 18)); } catch (e) {} + await humanDelay(650, 1200); + await page.mouse.click(x, y); + return true; + } catch (e) { + return false; + } + }; + + const clickCenterLeft = async () => { + const pt = await page.evaluate(() => { + const clamp = (v, min, max) => Math.max(min, Math.min(max, v)); + const modal = document.querySelector('.HidQ9ROd') || document.querySelector('div[role="dialog"][aria-modal="true"]') || document.querySelector('div[role="dialog"]'); + if (modal) { + const r = modal.getBoundingClientRect(); + if (r && r.width > 40 && r.height > 40) { + const x = clamp(Math.floor(r.left + r.width * 0.25), 1, Math.floor(window.innerWidth - 2)); + const y = clamp(Math.floor(r.top + r.height * 0.5), 1, Math.floor(window.innerHeight - 2)); + return { x, y }; + } + } + const x = clamp(Math.floor(window.innerWidth * 0.25), 1, Math.floor(window.innerWidth - 2)); + const y = clamp(Math.floor(window.innerHeight * 0.5), 1, Math.floor(window.innerHeight - 2)); + return { x, y }; + }).catch(() => null); + + if (!pt?.x || !pt?.y) return false; + try { + try { await page.mouse.move(Math.max(1, pt.x - 18), Math.max(1, pt.y - 18)); } catch (e) {} + await humanDelay(650, 1200); + await page.mouse.click(pt.x, pt.y); + return true; + } catch (e) { + return false; + } + }; + + const nudgeModalScroll = async () => { + if (!scopeSelectors) return; + const did = await page.evaluate(() => { + const modal = document.querySelector('.HidQ9ROd') || document.querySelector('div[role="dialog"][aria-modal="true"]') || document.querySelector('div[role="dialog"]'); + if (!modal) return false; + const all = [modal, ...Array.from(modal.querySelectorAll('*'))]; + const scroller = all.find(el => { + try { + return el.scrollHeight > el.clientHeight + 80; + } catch (e) { + return false; + } + }); + if (!scroller) return false; + const max = Math.max(0, scroller.scrollHeight - scroller.clientHeight); + if (max <= 0) return false; + const next = Math.min(max, scroller.scrollTop + Math.floor(scroller.clientHeight * 0.6)); + scroller.scrollTop = next; + return true; + }).catch(() => false); + if (did) await humanDelay(650, 1200); + }; + + const waitForOptionsList = async (timeoutMs = 6000) => { + const fast = await page.waitForSelector('li.TpUpcNRp, div._8gg8ho2u', { timeout: Math.min(2500, timeoutMs) }).catch(() => null); + if (fast) return true; + const ok = await page.waitForFunction(() => { + const modal = document.querySelector('.HidQ9ROd') || document.querySelector('div[role="dialog"][aria-modal="true"]') || document.querySelector('div[role="dialog"]'); + const root = modal || document; + const groupCount = root.querySelectorAll('.bIhLWVqm').length; + const optionCount = root.querySelectorAll('.bIhLWVqm .F7sZG3xe, .bIhLWVqm .s1O5M5fO .F7sZG3xe, .s1O5M5fO .F7sZG3xe').length; + if (groupCount > 0 && optionCount >= 2) return true; + const nodes = Array.from(root.querySelectorAll('li, div[role="button"], button, a')); + let count = 0; + for (const el of nodes) { + const t = String(el.innerText || el.textContent || '').replace(/\s+/g, ' ').trim(); + if (!t) continue; + if (!t.includes('آ¥') && !t.includes('ï؟¥')) continue; + const r = el.getBoundingClientRect(); + if (!r || r.width < 40 || r.height < 16 || r.height > 140) continue; + count++; + if (count >= 2) return true; + } + return false; + }, { timeout: timeoutMs }).catch(() => null); + return !!ok; + }; + + if (scopeSelectors) { + console.log('[PDD] Trying normalized click to open thumbnails/options (x=159,y=447)'); + const ok = await clickNormalizedPoint(159, 447); + if (ok) { + await closeIfIwwPopupOpened(); + await nudgeModalScroll(); + const hasAfter = await waitForOptionsList(7000); + if (hasAfter) { + console.log('[PDD] Options detected after normalized click'); + return true; + } + } + } + + const pickClickable = async (selector) => { + const handles = await page.$$(selector).catch(() => []); + for (const h of handles) { + const box = await h.boundingBox().catch(() => null); + if (!box) continue; + if (box.width < 3 || box.height < 3) continue; + return { handle: h, box }; + } + return null; + }; + + const clickByBox = async (box) => { + const x = Math.floor(box.x + box.width * 0.5); + const y = Math.floor(box.y + box.height * 0.5); + try { await page.mouse.move(Math.max(1, x - 18), Math.max(1, y - 18)); } catch (e) {} + await humanDelay(550, 1100); + await page.mouse.click(x, y); + }; + + const selectors = []; + if (!scopeSelectors) { + selectors.push('.O7pEFvHR', '.O7pEFvHR img'); + } else { + const scopes = Array.isArray(scopeSelectors) ? scopeSelectors : [scopeSelectors]; + for (const s of scopes) { + selectors.push(`${s} .O7pEFvHR`, `${s} .O7pEFvHR img`); + } + } + + console.log(`[PDD] Trying to click O7pEFvHR via ${selectors.length} selectors`); + let target = null; + let usedSelector = ''; + for (const sel of selectors) { + const picked = await pickClickable(sel); + if (picked) { + target = picked; + usedSelector = sel; + break; + } + } + + if (!target) { + if (!scopeSelectors) { + console.log('[PDD] O7pEFvHR not found/clickable (no modal scope); skipping heuristic click'); + return false; + } + + console.log('[PDD] O7pEFvHR not found/clickable; trying heuristic click inside SKU popup'); + + const scopes = scopeSelectors + ? (Array.isArray(scopeSelectors) ? scopeSelectors : [scopeSelectors]) + : []; + const pt = await page.evaluate((scopeSelList) => { + const clamp = (v, min, max) => Math.max(min, Math.min(max, v)); + const toPt = (r) => { + const x = clamp(Math.floor(r.left + r.width * 0.5), 1, Math.floor(window.innerWidth - 2)); + const y = clamp(Math.floor(r.top + r.height * 0.5), 1, Math.floor(window.innerHeight - 2)); + return { x, y }; + }; + + const visibleRect = (r) => { + if (!r || r.width < 12 || r.height < 12) return false; + if (r.bottom < 0 || r.right < 0) return false; + if (r.top > window.innerHeight || r.left > window.innerWidth) return false; + return true; + }; + + const isGoodSrc = (src) => { + const s = String(src || ''); + if (!s) return false; + if (!s.startsWith('http')) return false; + if (s.includes('avatar') || s.includes('icon') || s.includes('coupon')) return false; + return true; + }; + + const areas = []; + const roots = []; + if (scopeSelList && scopeSelList.length > 0) { + for (const sel of scopeSelList) { + const el = document.querySelector(sel); + if (el) roots.push(el); + } + } + if (roots.length === 0) roots.push(document); + + for (const root of roots) { + const imgs = Array.from(root.querySelectorAll('img')); + for (const img of imgs) { + if (img.closest && img.closest('.iW4aEGbb')) continue; + const r = img.getBoundingClientRect(); + if (!visibleRect(r)) continue; + if (!isGoodSrc(img.currentSrc || img.src)) continue; + const score = r.width * r.height; + areas.push({ score, rect: r }); + } + const divs = Array.from(root.querySelectorAll('div[role="button"], button')); + for (const el of divs) { + if (el.closest && el.closest('.iW4aEGbb')) continue; + const t = String(el.innerText || el.textContent || '').replace(/\s+/g, ' ').trim(); + if (!t) continue; + if (!t.includes('ه›¾') && !t.includes('ه›¾ç‰‡')) continue; + const r = el.getBoundingClientRect(); + if (!visibleRect(r)) continue; + const score = r.width * r.height * 0.6; + areas.push({ score, rect: r }); + } + } + + areas.sort((a, b) => b.score - a.score); + const best = areas[0]; + if (!best) return null; + return toPt(best.rect); + }, scopes).catch(() => null); + + if (!pt?.x || !pt?.y) return false; + + try { + try { await page.mouse.move(Math.max(1, pt.x - 18), Math.max(1, pt.y - 18)); } catch (e) {} + await humanDelay(600, 1200); + await page.mouse.click(pt.x, pt.y); + console.log('[PDD] Heuristic click executed'); + await closeIfIwwPopupOpened(); + await nudgeModalScroll(); + } catch (e) { + return false; + } + } + + if (target) { + console.log(`[PDD] Clicking O7pEFvHR using: ${usedSelector}`); + try { + await page.evaluate((sel) => { + const el = document.querySelector(sel); + if (el && el.scrollIntoView) el.scrollIntoView({ block: 'center', inline: 'center' }); + }, usedSelector).catch(() => null); + await humanDelay(500, 900); + const pt = await page.evaluate((sel) => { + const el = document.querySelector(sel); + if (!el) return null; + const r = el.getBoundingClientRect(); + if (!r || r.width < 4 || r.height < 4) return null; + const clamp = (v, min, max) => Math.max(min, Math.min(max, v)); + const xs = [0.5, 0.35, 0.65, 0.2, 0.8].map(p => Math.floor(r.left + r.width * p)); + const ys = [0.5, 0.35, 0.65, 0.2, 0.8].map(p => Math.floor(r.top + r.height * p)); + for (const y of ys) { + for (const x of xs) { + const xx = clamp(x, 1, Math.floor(window.innerWidth - 2)); + const yy = clamp(y, 1, Math.floor(window.innerHeight - 2)); + const top = document.elementFromPoint(xx, yy); + if (top && (el === top || el.contains(top))) return { x: xx, y: yy }; + } + } + return null; + }, usedSelector).catch(() => null); + + if (pt?.x && pt?.y) { + try { await page.mouse.move(Math.max(1, pt.x - 18), Math.max(1, pt.y - 18)); } catch (e) {} + await humanDelay(550, 1100); + await page.mouse.click(pt.x, pt.y); + } else { + const refreshed = await pickClickable(usedSelector); + if (refreshed?.box) target = refreshed; + await clickByBox(target.box); + } + console.log('[PDD] Clicked O7pEFvHR'); + await closeIfIwwPopupOpened(); + await nudgeModalScroll(); + } catch (e) { + console.log(`[PDD] O7pEFvHR click failed: ${e?.message || e}`); + return false; + } + } + + const has = await waitForOptionsList(7000); + if (has) { + console.log('[PDD] Options list detected'); + return true; + } + + console.log('[PDD] Options list not detected; trying center-left click inside modal'); + try { + const ok = await clickCenterLeft(); + if (ok) { + await closeIfIwwPopupOpened(); + await nudgeModalScroll(); + const hasAfter = await waitForOptionsList(7000); + if (hasAfter) { + console.log('[PDD] Options list detected after center-left click'); + return true; + } + } + } catch (e) {} + + const fallbackCounts = await page.evaluate(() => { + const modal = document.querySelector('.HidQ9ROd') || document.querySelector('div[role="dialog"][aria-modal="true"]') || document.querySelector('div[role="dialog"]'); + const root = modal || document; + const li = root.querySelectorAll('li').length; + const buttons = root.querySelectorAll('button, div[role="button"]').length; + const groups = root.querySelectorAll('.bIhLWVqm').length; + const opts = root.querySelectorAll('.bIhLWVqm .F7sZG3xe, .s1O5M5fO .F7sZG3xe').length; + return { li, buttons, groups, opts }; + }).catch(() => ({ li: 0, buttons: 0 })); + console.log(`[PDD] Options list not detected (li=${fallbackCounts.li}, buttons=${fallbackCounts.buttons}, groups=${fallbackCounts.groups || 0}, opts=${fallbackCounts.opts || 0})`); + return false; + }; + + console.log('[PDD] Opening options popup before clicking O7pEFvHR'); + const optionsModalOpened = await openOptionsModalIfNeeded(newPage); + let hasOptionsList = false; + if (optionsModalOpened) { + hasOptionsList = await clickO7pEFvHRAndWait(newPage, [ + '.HidQ9ROd', + 'div[role="dialog"][aria-modal="true"]', + 'div[role="dialog"]' + ]); + } else { + console.log('[PDD] Could not open options modal'); + } + if (hasOptionsList) { + const liCount = await newPage.$$eval('li.TpUpcNRp', els => els.length).catch(() => 0); + const cardCount = await newPage.$$eval('div._8gg8ho2u', els => els.length).catch(() => 0); + console.log(`[PDD] Options elements found: li.TpUpcNRp=${liCount}, div._8gg8ho2u=${cardCount}`); + } else { + console.log('[PDD] Options list not found; continuing without selecting any options'); + } + + await waitForStableUrl(newPage, 1400, 15000); + + console.log('[Main] Starting main product data extraction (safeEvaluate)...'); + const data = await safeEvaluate(newPage, async () => { + const wait = (ms) => new Promise(r => setTimeout(r, ms)); + + // HELPER: Strict Price Extraction from User Target + const getTargetPrice = (root) => { + const r = (root && typeof root.querySelector === 'function') ? root : document; + const targetDiv = r.querySelector('.ujEqGzEB') || document.querySelector('.ujEqGzEB'); + if (targetDiv) { + // Try aria-label first (e.g. "首ن»¶آ¥29.88") + const imgSpan = targetDiv.querySelector('span[role="img"]'); + if (imgSpan && imgSpan.getAttribute('aria-label')) { + const label = imgSpan.getAttribute('aria-label'); + const match = label.match(/آ¥\s*(\d+(\.\d+)?)/); + if (match) return 'آ¥' + match[1]; + } + // Fallback to text content + const text = targetDiv.innerText; + const match = text.match(/آ¥\s*(\d+(\.\d+)?)/); + if (match) return match[0]; + } + + const altPriceEl = + r.querySelector('div.kYzukoxf') || + r.querySelector('.Ngfn6pTR .kYzukoxf') || + document.querySelector('div.kYzukoxf') || + document.querySelector('.Ngfn6pTR .kYzukoxf'); + if (altPriceEl) { + const text = altPriceEl.innerText.replace(/\n/g, ' ').trim(); + const match = text.match(/آ¥\s*(\d+(\.\d+)?)/); + if (match) return match[0]; + } + + return null; + }; + + const waitForPriceAfterClick = async (prevPriceStr, root) => { + const start = Date.now(); + let last = null; + let stable = 0; + while (Date.now() - start < 7000) { + const cur = getTargetPrice(root); + if (cur) { + if (cur === last) stable++; + else { + last = cur; + stable = 0; + } + const changed = prevPriceStr ? (cur !== prevPriceStr) : true; + if (changed && stable >= 1) return cur; + if (!prevPriceStr && stable >= 1) return cur; + } + await wait(120); + } + return getTargetPrice(root) || last || null; + }; + + // 1. Title Extraction (User specific selector) + let title = ''; + const titleEl = document.querySelector('.tLYIg_Ju span') || + document.querySelector('.KlGVpw3u span') || + document.querySelector('.goods-name'); + if (titleEl) title = titleEl.innerText.trim(); + if (!title) title = document.title; + + // 2. Price Extraction (Initial fallback) + let price = getTargetPrice(document); + const priceEl = document.querySelector('.goods-price, [class*="price-info"], [class*="goods-price"]'); + if (!price && priceEl) { + price = priceEl.innerText.trim(); + } + if (!price) { + const bodyText = document.body.innerText; + const priceMatch = bodyText.match(/آ¥\s*(\d+(\.\d+)?)/); + if (priceMatch) price = priceMatch[0]; + } + + // 3. Description & Details + let description = ''; + let productDetails = {}; + + // Extract key-value details from .jvsKAdEs > .iUUH2sOQ + // Structure: .iUUH2sOQ -> .rMnkPxwx (Key) + .KjtdjVU2 (Value) + const detailItems = document.querySelectorAll('.iUUH2sOQ'); + detailItems.forEach(item => { + const key = item.querySelector('.rMnkPxwx')?.innerText.trim(); + const val = item.querySelector('.KjtdjVU2')?.innerText.trim(); + if (key && val) { + productDetails[key] = val; + description += `${key}: ${val}\n`; // Append to text description as well + } + }); + + // Fallback description if details are empty + if (!description) { + description = document.querySelector('.goods-details, [class*="detail-desc"]')?.innerText.trim() || ''; + } + + // 4. Variant & Price Extraction from Modal + let variants = {}; + let skuMap = {}; // Store price for each combination + let variantImages = {}; // Map color -> imageUrl + let skuThumbMap = {}; // Map optionKey -> imageUrl (per SKU or per single option) + let lowestVariantPrice = null; // Track lowest price found in variants + + try { + const extractOptionCardsFromRoot = () => { + const liEls = Array.from(document.querySelectorAll('li.TpUpcNRp')); + const containerEls = liEls.length > 0 + ? liEls.map(li => li.querySelector('div._8gg8ho2u') || li).filter(Boolean) + : Array.from(document.querySelectorAll('div._8gg8ho2u')); + const items = []; + const seen = new Set(); + + for (const c of containerEls) { + const nameEl = c?.querySelector?.('.RITrraU3 span.U63Kdv8C') || c?.querySelector?.('.RITrraU3 span') || c?.querySelector?.('span.U63Kdv8C'); + const textRaw = nameEl?.innerText || nameEl?.textContent || ''; + const text = String(textRaw || '').replace(/\s+/g, ' ').trim(); + + const priceEl = c?.querySelector?.('.nvN5jV0G') || c?.querySelector?.('[class*="nvN5jV0G"]'); + const priceRaw = priceEl?.innerText || priceEl?.textContent || ''; + const pm = String(priceRaw || '').match(/(\d+(\.\d+)?)/); + const priceStr = pm ? (`آ¥${pm[1]}`) : null; + + const imgEl = + c.querySelector('.PQoZYCec img') || + c.querySelector('.PQoZYCec img[data-src]') || + c.querySelector('.PQoZYCec img[data-lazy-src]') || + c.querySelector('.PQoZYCec img[data-original]') || + c.querySelector('img'); + const rawSrc = + imgEl?.getAttribute('src') || + imgEl?.getAttribute('data-src') || + imgEl?.getAttribute('data-lazy-src') || + imgEl?.getAttribute('data-original') || + imgEl?.src || + ''; + let thumb = rawSrc ? rawSrc.split('?')[0] : null; + if (!thumb) { + const pq = c.querySelector('.PQoZYCec') || c; + const styleBg = pq?.style?.backgroundImage || ''; + let bg = styleBg; + if (!bg) { + try { bg = window.getComputedStyle(pq).backgroundImage || ''; } catch (e) {} + } + const m = String(bg || '').match(/url\((['"]?)(.*?)\1\)/i); + const url = m?.[2] || ''; + thumb = url ? url.split('?')[0] : null; + } + + if (text && priceStr) { + const k = `${text}||${priceStr}||${thumb || ''}`; + if (seen.has(k)) continue; + seen.add(k); + items.push({ text, priceStr, thumb }); + } + } + + return items; + }; + + const cardsOnPage = extractOptionCardsFromRoot(); + if (cardsOnPage.length > 0) { + for (const card of cardsOnPage) { + skuMap[card.text] = card.priceStr; + if (card.thumb) skuThumbMap[card.text] = card.thumb; + } + } + + const modal = document.querySelector('.HidQ9ROd') || document.querySelector('div[role="dialog"][aria-modal="true"]') || document.querySelector('div[role="dialog"]'); + if (modal) { + const waitForOptionCards = async (timeoutMs = 2500) => { + const start = Date.now(); + while (Date.now() - start < timeoutMs) { + const hasLi = document.querySelectorAll('li.TpUpcNRp').length > 0; + const hasCards = document.querySelectorAll('div._8gg8ho2u').length > 0; + if (hasLi || hasCards) return true; + await wait(120); + } + return false; + }; + + const host = modal.querySelector('.O7pEFvHR'); + if (host) { + try { + host.scrollIntoView({ block: 'center', inline: 'center' }); + } catch (e) {} + try { + host.click(); + } catch (e) {} + await waitForOptionCards(3000); + const cardsAfterHostClick = extractOptionCardsFromRoot(); + if (cardsAfterHostClick.length > 0) { + for (const card of cardsAfterHostClick) { + skuMap[card.text] = card.priceStr; + if (card.thumb) skuThumbMap[card.text] = card.thumb; + } + } + } + + const getModalThumb = () => { + const img = modal.querySelector('.O7pEFvHR img'); + const raw = + img?.getAttribute?.('src') || + img?.getAttribute?.('data-src') || + img?.getAttribute?.('data-lazy-src') || + img?.currentSrc || + img?.src || + ''; + if (raw) return String(raw).split('?')[0]; + + const host = modal.querySelector('.O7pEFvHR'); + if (host) { + const styleBg = host.style?.backgroundImage || ''; + let bg = styleBg; + if (!bg) { + try { bg = window.getComputedStyle(host).backgroundImage || ''; } catch (e) {} + } + const m = String(bg || '').match(/url\((['"]?)(.*?)\1\)/i); + const url = m?.[2] || ''; + if (url) return url.split('?')[0]; + } + return null; + }; + + // Extract basic variants list first + const groups = Array.from(modal.querySelectorAll('.bIhLWVqm')); + let specKeys = []; + let specValues = []; + + groups.forEach(group => { + const keyEl = group.querySelector('.sku-specs-key'); + const valContainer = group.querySelector('.s1O5M5fO'); + + if (keyEl && valContainer) { + const key = keyEl.innerText.trim(); + const vals = Array.from(valContainer.querySelectorAll('.F7sZG3xe')) // Get the clickables + .map(el => ({ + text: el.querySelector('span.J109_25J')?.innerText.trim(), + element: el + })) + .filter(v => v.text); + variants[key] = vals.map(v => v.text); + specKeys.push(key); + specValues.push(vals); + } + }); + + if (specValues.length === 0) { + console.error('CRITICAL: Modal opened but no variants found. Structure might have changed.'); + } + + const isDisabledOption = (el) => { + if (!el) return true; + const ariaDisabled = el.getAttribute('aria-disabled'); + if (ariaDisabled && ariaDisabled.toLowerCase() === 'true') return true; + if (el.hasAttribute('disabled')) return true; + const cls = String(el.className || '').toLowerCase(); + if (cls.includes('disabled')) return true; + return false; + }; + + const getOptionText = (el) => { + return el?.querySelector('span.J109_25J')?.innerText.trim() || el?.innerText.trim() || ''; + }; + + const safeClick = async (el) => { + if (!el) return false; + try { el.scrollIntoView({ block: 'center', inline: 'center' }); } catch(e) {} + try { el.click(); return true; } catch(e) {} + try { + el.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window })); + return true; + } catch(e) {} + return false; + }; + + const getGroupOptions = (groupEl) => { + const valContainer = groupEl?.querySelector('.s1O5M5fO'); + if (!valContainer) return []; + return Array.from(valContainer.querySelectorAll('.F7sZG3xe')) + .map(el => ({ text: getOptionText(el), element: el })) + .filter(v => v.text && !isDisabledOption(v.element)); + }; + + const getGroup1 = () => Array.from(modal.querySelectorAll('.bIhLWVqm'))[0] || null; + const getGroup2 = () => Array.from(modal.querySelectorAll('.bIhLWVqm'))[1] || null; + + const isSelectedOption = (el) => { + if (!el) return false; + const clsRaw = String(el.className || ''); + const cls = clsRaw.toLowerCase(); + if (cls.includes('hr353bdx')) return true; + if (cls.includes('kv0lnch3')) return true; + const ariaChecked = el.getAttribute('aria-checked'); + if (ariaChecked && ariaChecked.toLowerCase() === 'true') return true; + const ariaSelected = el.getAttribute('aria-selected'); + if (ariaSelected && ariaSelected.toLowerCase() === 'true') return true; + const ariaPressed = el.getAttribute('aria-pressed'); + if (ariaPressed && ariaPressed.toLowerCase() === 'true') return true; + const dataState = el.getAttribute('data-state'); + if (dataState && (dataState === 'checked' || dataState === 'selected')) return true; + const dataSelected = el.getAttribute('data-selected'); + if (dataSelected && dataSelected.toLowerCase() === 'true') return true; + if (el.querySelector && el.querySelector('[aria-checked="true"], [aria-selected="true"]')) return true; + if (cls.includes('selected') || cls.includes('active') || cls.includes('checked') || cls.includes('current') || cls.includes('cur') || cls.includes('on')) return true; + return false; + }; + + const getGroupOptionElements = (groupEl) => { + const valContainer = groupEl?.querySelector('.s1O5M5fO'); + if (!valContainer) return []; + return Array.from(valContainer.querySelectorAll('.F7sZG3xe')) + .filter(el => !isDisabledOption(el) && !!getOptionText(el)); + }; + + const getOptionStyleKey = (el) => { + try { + const s = window.getComputedStyle(el); + const bg = s.backgroundColor || ''; + const border = s.borderColor || ''; + const color = s.color || ''; + const fw = s.fontWeight || ''; + const outline = s.outlineColor || ''; + return `${bg}|${border}|${color}|${fw}|${outline}`; + } catch (e) { + return ''; + } + }; + + const getSelectedOptionEl = (groupEl) => { + const optionEls = getGroupOptionElements(groupEl); + if (optionEls.length === 0) return null; + + const ariaSelectedEl = optionEls.find(isSelectedOption) || null; + if (ariaSelectedEl) return ariaSelectedEl; + + const keyCounts = new Map(); + for (const el of optionEls) { + const key = getOptionStyleKey(el); + keyCounts.set(key, (keyCounts.get(key) || 0) + 1); + } + + let bestEl = null; + let bestCount = Infinity; + for (const el of optionEls) { + const key = getOptionStyleKey(el); + const c = keyCounts.get(key) || 0; + if (c > 0 && c < bestCount) { + bestCount = c; + bestEl = el; + } + } + + if (bestEl && bestCount < optionEls.length) return bestEl; + return null; + }; + + const getSelectedOptionText = (groupEl) => { + const selectedEl = getSelectedOptionEl(groupEl); + return selectedEl ? getOptionText(selectedEl) : null; + }; + + const findOptionElByText = (groupEl, text) => { + if (!groupEl) return null; + const valContainer = groupEl.querySelector('.s1O5M5fO'); + if (!valContainer) return null; + const optionEls = Array.from(valContainer.querySelectorAll('.F7sZG3xe')); + for (const el of optionEls) { + if (isDisabledOption(el)) continue; + if (getOptionText(el) === text) return el; + } + return null; + }; + + const waitFor = async (predicate, timeoutMs = 2500, intervalMs = 120) => { + const start = Date.now(); + while (Date.now() - start < timeoutMs) { + try { + if (predicate()) return true; + } catch (e) {} + await wait(intervalMs); + } + return false; + }; + + const waitForStableTargetPrice = async (root, timeoutMs = 5000, intervalMs = 150, stableTicks = 2) => { + const start = Date.now(); + let last = null; + let stable = 0; + while (Date.now() - start < timeoutMs) { + const cur = getTargetPrice(root); + if (cur) { + if (cur === last) stable++; + else { + last = cur; + stable = 0; + } + if (stable >= stableTicks) return cur; + } + await wait(intervalMs); + } + return getTargetPrice(root) || last || null; + }; + + const waitForStableModalThumb = async (prevThumb, timeoutMs = 5000, intervalMs = 150, stableTicks = 2) => { + const start = Date.now(); + let last = getModalThumb(); + let stable = 0; + while (Date.now() - start < timeoutMs) { + const cur = getModalThumb(); + if (cur) { + if (cur !== last) { + last = cur; + stable = 0; + } else { + stable++; + } + if (prevThumb && cur !== prevThumb && stable >= stableTicks) return cur; + if (!prevThumb && stable >= stableTicks) return cur; + } + await wait(intervalMs); + } + return getModalThumb() || last || null; + }; + + const recordSku = (key, priceStr, thumb) => { + if (!key || !priceStr) return; + skuMap[key] = priceStr; + if (thumb) { + skuThumbMap[key] = thumb; + } + const pMatch = String(priceStr || '').match(/(\d+(\.\d+)?)/); + if (pMatch) { + const pVal = parseFloat(pMatch[1]); + if (Number.isFinite(pVal)) { + if (lowestVariantPrice === null || pVal < lowestVariantPrice) { + lowestVariantPrice = pVal; + price = `آ¥${pMatch[1]}`; + } + } + } + }; + + if (Object.keys(skuMap).length === 0 && Array.isArray(specValues) && specValues.length > 0) { + const startedAt = Date.now(); + const timeBudgetMs = 65000; + const group1 = specValues[0] || []; + const group2 = specValues[1] || []; + const group1Opts = group1.filter(v => v?.text && v?.element && !isDisabledOption(v.element)); + const group2Opts = group2.filter(v => v?.text && v?.element && !isDisabledOption(v.element)); + + if (group1Opts.length > 0 && group2Opts.length === 0) { + for (const o1 of group1Opts) { + if (Date.now() - startedAt > timeBudgetMs) break; + const prevPrice = getTargetPrice(document); + const prevThumb = getModalThumb(); + await safeClick(o1.element); + await wait(180); + const priceStr = await waitForPriceAfterClick(prevPrice, document); + const thumb = await waitForStableModalThumb(prevThumb, 4500, 160, 2); + if (thumb) variantImages[o1.text] = thumb; + recordSku(o1.text, priceStr || prevPrice || priceStr, thumb); + } + } else if (group1Opts.length > 0 && group2Opts.length > 0) { + for (const o1 of group1Opts) { + if (Date.now() - startedAt > timeBudgetMs) break; + const prevThumbColor = getModalThumb(); + await safeClick(o1.element); + await wait(220); + const colorThumb = await waitForStableModalThumb(prevThumbColor, 4500, 160, 2); + if (colorThumb) variantImages[o1.text] = colorThumb; + + for (const o2 of group2Opts) { + if (Date.now() - startedAt > timeBudgetMs) break; + const prevPrice = getTargetPrice(document); + const prevThumb = getModalThumb(); + await safeClick(o2.element); + await wait(200); + const priceStr = await waitForPriceAfterClick(prevPrice, document); + const thumb = await waitForStableModalThumb(prevThumb, 4500, 160, 2); + const key = `${o1.text}__SEP__${o2.text}`; + recordSku(key, priceStr || prevPrice || priceStr, thumb || colorThumb); + } + } + } + } + + const extractCardTextPrice = (c) => { + const nameEl = c?.querySelector?.('.RITrraU3 span.U63Kdv8C') || c?.querySelector?.('.RITrraU3 span') || c?.querySelector?.('span.U63Kdv8C'); + let textRaw = nameEl?.innerText || nameEl?.textContent || ''; + let text = String(textRaw || '').replace(/\s+/g, ' ').trim(); + if (!text) { + const spans = Array.from(c?.querySelectorAll?.('span') || []); + for (const s of spans) { + const t = String(s?.innerText || s?.textContent || '').replace(/\s+/g, ' ').trim(); + if (!t) continue; + if (t.includes('آ¥') || t.includes('ï؟¥')) continue; + if (t.includes('ه·²é€‰') || t.includes('请选و‹©')) continue; + if (t.length > 80) continue; + text = t; + break; + } + } + + const priceEl = c?.querySelector?.('.nvN5jV0G') || c?.querySelector?.('[class*="nvN5jV0G"]'); + let priceRaw = priceEl?.innerText || priceEl?.textContent || ''; + if (!priceRaw) { + const t = String(c?.innerText || c?.textContent || ''); + const m = t.match(/[آ¥ï؟¥]\s*(\d+(\.\d+)?)/); + if (m) priceRaw = m[0]; + } + const pm = String(priceRaw || '').match(/(\d+(\.\d+)?)/); + const priceStr = pm ? (`آ¥${pm[1]}`) : null; + + return { text, priceStr }; + }; + + const extractCardThumb = (c) => { + const imgEl = c.querySelector('.PQoZYCec img') || c.querySelector('.PQoZYCec img[data-src]') || c.querySelector('.PQoZYCec img[data-lazy-src]') || c.querySelector('.PQoZYCec img[data-original]') || c.querySelector('img'); + const rawSrc = + imgEl?.getAttribute('src') || + imgEl?.getAttribute('data-src') || + imgEl?.getAttribute('data-lazy-src') || + imgEl?.getAttribute('data-original') || + imgEl?.src || + ''; + if (rawSrc) return rawSrc.split('?')[0]; + + const pq = c.querySelector('.PQoZYCec') || c; + const styleBg = pq?.style?.backgroundImage || ''; + let bg = styleBg; + if (!bg) { + try { bg = window.getComputedStyle(pq).backgroundImage || ''; } catch (e) {} + } + const m = String(bg || '').match(/url\((['"]?)(.*?)\1\)/i); + const url = m?.[2] || ''; + return url ? url.split('?')[0] : null; + }; + + const scanThumbsViaO7pEFvHR = async (group1Texts, group2Texts, maxSwipes = 28) => { + const out = {}; + const seenKeys = new Set(); + const host = modal.querySelector('.O7pEFvHR') || modal.querySelector('.O7pEFvHR img'); + if (!host) return out; + + const getSelectedSummaryText = () => { + const el = modal.querySelector('.xJDS9NLo .Mbx2m60G') || modal.querySelector('.Mbx2m60G'); + const t = el?.innerText || el?.textContent || ''; + return String(t || '').replace(/\s+/g, ' ').trim(); + }; + + const normalizeSelectedSummary = (t) => { + return String(t || '').replace(/^ه·²é€‰\s*[:ï¼ڑ]\s*/g, '').trim(); + }; + + const pickComboKey = (summary) => { + const s = String(summary || ''); + const v1 = (group1Texts || []).find(t => t && s.includes(t)) || null; + const v2 = (group2Texts || []).find(t => t && s.includes(t)) || null; + if (v1 && v2) return `${v1}__SEP__${v2}`; + return summary || null; + }; + + const swipeLeft = async () => { + try { + const r = host.getBoundingClientRect(); + const startX = Math.floor(r.left + r.width * 0.78); + const endX = Math.floor(r.left + r.width * 0.22); + const y = Math.floor(r.top + r.height * 0.5); + const touchStart = new Touch({ identifier: Date.now(), target: host, clientX: startX, clientY: y }); + const touchEnd = new Touch({ identifier: Date.now(), target: host, clientX: endX, clientY: y }); + host.dispatchEvent(new TouchEvent('touchstart', { touches: [touchStart], bubbles: true })); + host.dispatchEvent(new TouchEvent('touchmove', { touches: [touchEnd], bubbles: true })); + host.dispatchEvent(new TouchEvent('touchend', { changedTouches: [touchEnd], bubbles: true })); + await wait(380); + return true; + } catch (e) { + try { + const r = host.getBoundingClientRect(); + const startX = Math.floor(r.left + r.width * 0.78); + const endX = Math.floor(r.left + r.width * 0.22); + const y = Math.floor(r.top + r.height * 0.5); + host.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, cancelable: true, clientX: startX, clientY: y })); + host.dispatchEvent(new MouseEvent('mousemove', { bubbles: true, cancelable: true, clientX: endX, clientY: y })); + host.dispatchEvent(new MouseEvent('mouseup', { bubbles: true, cancelable: true, clientX: endX, clientY: y })); + await wait(380); + return true; + } catch (e2) {} + } + return false; + }; + + let stagnation = 0; + let lastKey = null; + for (let i = 0; i < maxSwipes; i++) { + const summary = normalizeSelectedSummary(getSelectedSummaryText()); + const key = pickComboKey(summary); + const thumb = getModalThumb(); + if (key && thumb) out[key] = thumb; + + if (key && key === lastKey) stagnation++; + else stagnation = 0; + lastKey = key || lastKey; + + if (key) seenKeys.add(key); + if (seenKeys.size >= 6 && stagnation >= 2) break; + + const didSwipe = await swipeLeft(); + if (!didSwipe) break; + } + + return out; + }; + + const extractOptionCards = (root) => { + const scope = (root || document); + const liEls = Array.from(scope.querySelectorAll('li.TpUpcNRp')); + const containerEls = liEls.length > 0 + ? liEls.map(li => li.querySelector('div._8gg8ho2u')).filter(Boolean) + : Array.from(scope.querySelectorAll('div._8gg8ho2u')); + const items = []; + const seen = new Set(); + const addFromContainer = (c) => { + const thumb = extractCardThumb(c); + const { text, priceStr } = extractCardTextPrice(c); + + if (text && priceStr) { + const k = `${text}||${priceStr}||${thumb || ''}`; + if (seen.has(k)) return; + seen.add(k); + items.push({ text, priceStr, thumb }); + } + }; + + for (const c of containerEls) addFromContainer(c); + + if (items.length === 0) { + const priceEls = Array.from(scope.querySelectorAll('.nvN5jV0G, [class*="nvN5jV0G"]')); + const candidates = []; + const uniq = new Set(); + for (const p of priceEls) { + const t = String(p?.innerText || p?.textContent || '').replace(/\s+/g, ' ').trim(); + if (!t || (!t.includes('آ¥') && !t.includes('ï؟¥'))) continue; + const c = p.closest('li') || p.closest('div') || p.parentElement; + if (!c) continue; + const key = c === scope ? null : (c.getAttribute?.('class') || '') + '::' + (c.innerText || '').slice(0, 60); + if (key && uniq.has(key)) continue; + if (key) uniq.add(key); + candidates.push(c); + if (candidates.length >= 40) break; + } + for (const c of candidates) addFromContainer(c); + } + + return items; + }; + + const cards = extractOptionCards(modal); + if (cards.length > 0) { + for (const card of cards) { + skuMap[card.text] = card.priceStr; + if (card.thumb) skuThumbMap[card.text] = card.thumb; + + const pMatch = card.priceStr.match(/(\d+(\.\d+)?)/); + if (pMatch) { + const pVal = parseFloat(pMatch[1]); + if (lowestVariantPrice === null || pVal < lowestVariantPrice) { + lowestVariantPrice = pVal; + price = card.priceStr; + } + } + } + } + } + } catch (e) { + console.log('Variant extraction failed:', e.message); + } + + // 5. Image Extraction with Slider Logic + let images = []; + + // Helper to capture current visible images + const captureImages = () => { + // STRICT SLIDER SELECTOR: Only target images within the known slider container classes + // .goods-slider, .swiper-slide, or specific top containers + // We avoid #main > div img as it is too broad and catches header icons/text + const sliderSelectors = [ + '.goods-slider img', + '.swiper-slide img', + '.swiper-container img', + '.banner-slider img', + '#main > div > div:first-child img', // Often the first div is the slider + '.slick-slide img' + ]; + + const imgs = document.querySelectorAll(sliderSelectors.join(', ')); + + imgs.forEach(img => { + if (img.src && img.src.startsWith('http') && img.naturalWidth > 400) { + // Clean the URL + let cleanSrc = img.src.split('?')[0]; + + // Filter out video snapshots, avatars, icons, and coupons + if (cleanSrc.includes('video-snapshot') || + cleanSrc.includes('avatar') || + cleanSrc.includes('icon') || + cleanSrc.includes('coupon') || + cleanSrc.includes('.slim.png')) return; + + // ASPECT RATIO CHECK: Exclude wide banners or tiny strips + // Product images are usually 1:1 or 3:4. + // Banners are usually > 2:1. + if (img.naturalHeight > 0) { + const aspect = img.naturalWidth / img.naturalHeight; + if (aspect > 2.2 || aspect < 0.4) { + // console.log(`Skipping image due to aspect ratio ${aspect.toFixed(2)}: ${cleanSrc}`); + return; + } + } + + images.push(cleanSrc); + } + }); + + // FALLBACK: If strict slider extraction failed (empty), try slightly broader but still top-area + if (images.length === 0) { + // Get images from the top 50% of the page only + const allImgs = document.querySelectorAll('img'); + allImgs.forEach(img => { + const rect = img.getBoundingClientRect(); + if (rect.top < window.innerHeight * 0.6 && img.naturalWidth > 400) { + let cleanSrc = img.src.split('?')[0]; + if (cleanSrc.startsWith('http') && + !cleanSrc.includes('avatar') && + !cleanSrc.includes('icon') && + !cleanSrc.includes('coupon')) { + + // Aspect Ratio Check for Fallback too + if (img.naturalHeight > 0) { + const aspect = img.naturalWidth / img.naturalHeight; + if (aspect > 2.2 || aspect < 0.4) return; + } + + images.push(cleanSrc); + } + } + }); + } + }; + + // Initial capture + captureImages(); + + // Attempt to slide right (swipe left gesture) to reveal more images + const sliderContainer = document.querySelector('#main > div') || document.body; + + if (sliderContainer) { + for (let i = 0; i < 5; i++) { // Swipe 5 times + try { + // Simulate touch swipe left SAFE + // Some environments (Headless) might not support Touch constructor directly or it behaves oddly + // Use a simpler dispatch if possible, or wrap in try/catch + if (typeof Touch !== 'undefined' && typeof TouchEvent !== 'undefined') { + const touchStart = new Touch({ identifier: Date.now(), target: sliderContainer, clientX: 300, clientY: 200 }); + const touchEnd = new Touch({ identifier: Date.now(), target: sliderContainer, clientX: 50, clientY: 200 }); + + sliderContainer.dispatchEvent(new TouchEvent('touchstart', { touches: [touchStart], bubbles: true })); + sliderContainer.dispatchEvent(new TouchEvent('touchmove', { touches: [touchEnd], bubbles: true })); + sliderContainer.dispatchEvent(new TouchEvent('touchend', { changedTouches: [touchEnd], bubbles: true })); + } + } catch (e) { + // console.log('Swipe simulation failed (non-fatal):', e.message); + } + + await wait(800); // Wait for animation + captureImages(); + } + } + + // --- MAIN IMAGE FIX: Prioritize Images from Specific Picture Div --- + // User Request: "set the first main img is the imgs shows in that the picture div" + // This usually refers to the main gallery or a specific container that holds the high-res images + + // 1. Try to find the specific "Picture Div" (often .goods-slider or .slick-slider) + // If we found images in the slider, we should prioritize them. + // The `images` array already collects them, but let's make sure they are unique and ordered correctly. + + images = [...new Set(images)]; // Deduplicate first + + // If we have slider images, they are already at the top. + // But if the user meant the "Details" images (which are sometimes high res), we should be careful. + // Usually "Main Image" is the first one in the slider. + + // Let's verify if there's a specific container the user might be referring to. + // Often in Pinduoduo mobile, the main image is in a swiper at the top. + // We already target that. + + // However, sometimes "other pictures" (like description images) get mixed in if we use broad selectors. + // Our `captureImages` is already quite strict. + + // Let's double check if we can be even stricter for the FIRST image. + // Look for the absolute first image in the slider container + let firstSliderImg = document.querySelector('.goods-slider img') || + document.querySelector('.swiper-slide-active img') || + document.querySelector('.slick-current img') || + document.querySelector('#main > div > div:first-child img'); + + // Validation: If first image is a banner (wide), ignore it + if (firstSliderImg) { + if (firstSliderImg.naturalHeight > 0) { + const aspect = firstSliderImg.naturalWidth / firstSliderImg.naturalHeight; + if (aspect > 2.0 || aspect < 0.5) { + // console.log('First slider image rejected due to aspect ratio:', aspect); + firstSliderImg = null; + } + } + } + + // Fallback: If no slider image found, find the largest image in the top 500px + if (!firstSliderImg) { + const allImgs = Array.from(document.querySelectorAll('img')); + let maxArea = 0; + let bestImg = null; + + allImgs.forEach(img => { + const rect = img.getBoundingClientRect(); + if (rect.top < 600 && rect.height > 100 && rect.width > 100) { + const area = rect.width * rect.height; + const aspect = rect.width / rect.height; + + // Only consider reasonable aspect ratios + if (aspect > 0.5 && aspect < 2.0) { + if (area > maxArea) { + maxArea = area; + bestImg = img; + } + } + } + }); + if (bestImg) firstSliderImg = bestImg; + } + + if (firstSliderImg && firstSliderImg.src) { + const mainSrc = firstSliderImg.src.split('?')[0]; + // Move this image to the front of the array if it exists + images = images.filter(img => img !== mainSrc); + images.unshift(mainSrc); + } else if (images.length > 0) { + // If we couldn't pinpoint the slider element but captured images, + // ensure the first one in the captured list stays first. + // (Already handled by array order, but good to be explicit) + } + + + // 6. Description Images Extraction + let product_desc_imgs = []; + + console.log('Starting description image extraction sequence...'); + await wait(5000); + try { + for (let i = 0; i < 2; i++) { + const x = Math.floor(window.innerWidth / 2); + const y = 12; + const el = document.elementFromPoint(x, y); + if (el) el.click(); + await wait(220); + } + const backBtn = document.querySelector('div[role="button"][aria-label*="è؟”ه›‍"]') || + document.querySelector('div[role="button"][aria-label*="هگژ退"]') || + document.querySelector('div[role="button"][aria-label*="ه…³é—­"]'); + if (backBtn) { + backBtn.click(); + await wait(600); + } + } catch (e) {} + await wait(5000); + + // Step A: Close the variant modal explicitly + try { + // User mentioned: "hit the exit button" (likely the X button) + // Selector hints: div[role="button"][aria-label="ه…³é—­ه¼¹çھ—"] OR .pD0kR4N1 + const closeBtn = document.querySelector('div[role="button"][aria-label="ه…³é—­ه¼¹çھ—"]') || + document.querySelector('.pD0kR4N1') || + document.querySelector('div[role="button"] .pD0kR4N1')?.parentElement; + + if (closeBtn) { + // console.log('Closing variant modal...'); + closeBtn.click(); + await wait(1000); + } else { + // Try clicking the overlay/mask + const mask = document.querySelector('.ReactModal__Overlay, [class*="overlay"], [class*="mask"]'); + if (mask) { + mask.click(); + await wait(1000); + } + } + } catch(e) { + // console.log('Error closing modal:', e.message); + } + diff --git a/server/scripts/part2.js b/server/scripts/part2.js new file mode 100644 index 0000000000000000000000000000000000000000..e418ef8c5dae939f454c950db6d94872a6e63577 --- /dev/null +++ b/server/scripts/part2.js @@ -0,0 +1,158 @@ + // STOPPING ACTIONS AS REQUESTED + console.log('[Reviews] Stopping all previous actions and stabilizing page before review scraping...'); + await wait(2000); + + let hasReviews = false; + try { + console.log(`[Reviews] Checking for reviews (商品评价)...`); + let reviewBtn = null; + try { + const xpath = "//*[contains(text(), '商品评价')]"; + const result = document.evaluate(xpath, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); + for (let i = 0; i < result.snapshotLength; i++) { + const el = result.snapshotItem(i); + if (el.textContent && el.textContent.length < 20) { + if (el.innerText && el.innerText.includes('商品评价')) { + reviewBtn = el; + break; + } + } + } + } catch(e) {} + + if (!reviewBtn) { + const allElements = Array.from(document.querySelectorAll('div, span, p')); + reviewBtn = allElements.find(el => el.innerText && el.innerText.includes('商品评价') && el.innerText.length < 20); + } + + if (reviewBtn) { + console.log(`[Reviews] Found review button, clicking...`); + reviewBtn.click(); + hasReviews = true; + } else { + console.log('[Reviews] No review button found.'); + } + } catch (e) { + console.log(`[Reviews] Error checking reviews: ${e.message}`); + } + + return { title, price, description, images: [...new Set(images)], variants, skuMap, skuThumbMap, productDetails, variantImages, hasReviews }; + }, [], 12); + + // --- PART 2: REVIEWS (Separate Context) --- + let reviews = []; + if (data.hasReviews) { + console.log('[Reviews] Button clicked in previous step. Waiting 5s for page load (Node.js wait)...'); + await new Promise(r => setTimeout(r, 5000)); + + console.log('[Reviews] Starting review extraction (New Context)...'); + reviews = await safeEvaluate(newPage, async () => { + const wait = (ms) => new Promise(r => setTimeout(r, ms)); + const extractedReviews = []; + try { + // Scroll Logic + const reviewContent = document.querySelector('.comment-item') || document.querySelector('img[src*="avatar"]'); + if (!reviewContent) { + console.log('[Reviews] Review content not immediately visible, waiting...'); + await wait(2000); + } + + console.log('[Reviews] Starting scroll sequence...'); + for (let i = 0; i < 4; i++) { + window.scrollBy(0, window.innerHeight); + await wait(800 + Math.random() * 400); + } + + console.log('[Reviews] Extracting reviews...'); + // Strategy: Group elements by class name to find review items + const divs = Array.from(document.querySelectorAll('div')); + const classCounts = {}; + divs.forEach(d => { + if (d.className && typeof d.className === 'string') { + const c = d.className; + if (!classCounts[c]) classCounts[c] = []; + classCounts[c].push(d); + } + }); + + let bestClass = null; + let maxCount = 0; + for (const [cls, items] of Object.entries(classCounts)) { + if (items.length > 1) { + const first = items[0]; + const text = first.innerText.trim(); + const imgs = first.querySelectorAll('img'); + const hasValidImg = Array.from(imgs).some(img => img.naturalWidth > 50 && !img.src.includes('avatar')); + if (text.length > 5 && hasValidImg) { + if (items.length > maxCount) { maxCount = items.length; bestClass = cls; } + } + } + } + + if (bestClass) { + const items = classCounts[bestClass]; + items.forEach(item => { + const text = item.innerText.trim(); + const imgs = Array.from(item.querySelectorAll('img')).filter(img => img.naturalWidth > 50 && !img.src.includes('avatar')).map(img => img.src.split('?')[0]); + if (text && imgs.length > 0) { + const lines = text.split('\n').map(l => l.trim()).filter(l => l); + let name = 'Pinduoduo Shopper'; + let comment = text; + if (lines.length > 1 && lines[0].length < 20) { name = lines[0]; comment = lines.slice(1).join(' '); } + extractedReviews.push({ name, comment, photos: [...new Set(imgs)] }); + } + }); + } else { + const visibleImgs = Array.from(document.querySelectorAll('img')).filter(img => img.naturalWidth > 100 && !img.src.includes('avatar')).map(img => img.src.split('?')[0]); + const uniqueImgs = [...new Set(visibleImgs)]; + for (let i = 0; i < uniqueImgs.length; i += 3) { + extractedReviews.push({ name: 'Pinduoduo Shopper', comment: 'صور من تقييمات العملاء', photos: uniqueImgs.slice(i, i+3) }); + } + } + + console.log(`[Reviews] Extracted ${extractedReviews.length} reviews.`); + + // Go Back + console.log('[Reviews] Going back...'); + const backBtn = document.querySelector('div[role="button"][aria-label*="返回"]') || document.querySelector('[data-testid="back-button"]'); + if (backBtn) backBtn.click(); + else window.history.back(); + + } catch (e) { console.log('Review error:', e.message); } + return extractedReviews; + }); + + console.log(`[Reviews] Extracted ${reviews.length} reviews. Waiting 2s for back navigation...`); + await new Promise(r => setTimeout(r, 2000)); + } + data.reviews = reviews; + + // --- PART 3: DESCRIPTION IMAGES (Separate Context) --- + console.log('[Description] Starting description image extraction (New Context)...'); + const product_desc_imgs = await safeEvaluate(newPage, async () => { + const wait = (ms) => new Promise(r => setTimeout(r, ms)); + const imgs = []; + + // Scroll + console.log('[Description] Scrolling...'); + const steps = 20; + const stepSize = document.body.scrollHeight / steps; + for (let i = 0; i < steps; i++) { + window.scrollBy(0, stepSize); + await wait(100); + } + await wait(2000); + + // Extract + const allImgs = Array.from(document.querySelectorAll('img')); + allImgs.forEach(img => { + let src = img.getAttribute('data-src') || img.src; + if (src && !src.startsWith('data:') && img.naturalWidth > 300) { + if (!src.includes('avatar') && !src.includes('icon')) { + imgs.push(src.split('?')[0]); + } + } + }); + return [...new Set(imgs)]; + }); + data.product_desc_imgs = product_desc_imgs; diff --git a/server/scripts/part3.js b/server/scripts/part3.js new file mode 100644 index 0000000000000000000000000000000000000000..bb8a1d8106397ea1a9627c2cc90812a62508cb4d --- /dev/null +++ b/server/scripts/part3.js @@ -0,0 +1,514 @@ + + // Enrich + console.log(`Enriching: ${data.title.substring(0, 20)}...`); + + let general_price = 0; + if (data.price) { + const match = data.price.match(/(\d+(\.\d+)?)/); + if (match) general_price = parseFloat(match[1]) * 200; + } + + // --- EDIBLE CHECK (KEYWORD PRE-FILTER) --- + const preCheck = isEdiblePreCheck(data.title, data.description); + if (preCheck.isEdible) { + console.log(`Skipping product (EDIBLE KEYWORD DETECTED: ${preCheck.keyword}): ${data.title.substring(0, 30)}...`); + if (!navigationHappened) await newPage.close(); + else await newPage.goBack(); + continue; + } + + const aiData = await enrichWithAI(data.title, data.description, data.price); + + // CHECK: Did AI fail completely? + if (aiData.shouldSkip) { + console.error(`Skipping product due to AI translation failure: ${aiData.reason}`); + if (!navigationHappened) await newPage.close(); + else await newPage.goBack(); + continue; + } + + // CHECK: Is it edible (AI Detection)? + if (aiData.is_edible) { + console.log(`Skipping product (AI DETECTED EDIBLE): ${data.title.substring(0, 30)}...`); + if (!navigationHappened) await newPage.close(); + else await newPage.goBack(); + continue; + } + + // --- GENERATE OPTIONS FROM SKU MAP (WITH TRANSLATION) --- + let generated_options = []; + const variantImages = data.variantImages || {}; + const skuThumbMap = data.skuThumbMap || {}; + + if (data.skuMap && Object.keys(data.skuMap).length > 0) { + const rawVariantEntries = Object.entries(data.skuMap || {}); + console.log(`Variant prices BEFORE translation (${rawVariantEntries.length})`); + const rawPreviewLimit = 80; + rawVariantEntries.slice(0, rawPreviewLimit).forEach(([k, v]) => { + const m = String(v || '').match(/(\d+(\.\d+)?)/); + const p = m ? Math.round(parseFloat(m[1]) * 200) : 0; + console.log(` ${k} => ${v} (${p} IQD)`); + }); + if (rawVariantEntries.length > rawPreviewLimit) { + console.log(` ... truncated ${rawVariantEntries.length - rawPreviewLimit} more`); + } + + // Helper to translate color/size via AI if possible, or simple mapping + // Since we want strict Arabic, we might need a quick AI pass or just use the aiData logic + // For now, let's process the structure first, then maybe translate the labels + + const resolveThumbnail = (optionKey, colorStr) => { + if (optionKey && skuThumbMap[optionKey]) return skuThumbMap[optionKey]; + if (!colorStr) return null; + if (variantImages[colorStr]) return variantImages[colorStr]; + const keys = Object.keys(variantImages || {}); + const matchingKey = keys.find(k => k && (k.includes(colorStr) || colorStr.includes(k))); + return matchingKey ? variantImages[matchingKey] : null; + }; + + for (const [key, priceStr] of rawVariantEntries) { + let color = key; + let size = null; + + if (key.includes('__SEP__')) { + const parts = key.split('__SEP__'); + color = parts[0]; + size = parts[1]; + } + + let priceVal = 0; + const match = String(priceStr || '').match(/(\d+(\.\d+)?)/); + if (match) priceVal = parseFloat(match[1]) * 200; + + color = String(color || '') + .replace(/\n.*$/, '') + .replace(/م€گ.*?م€‘/g, '') + .replace(/\s+/g, ' ') + .trim(); + + if (size) { + size = String(size || ''); + size = size.replace(/(\d+(\.\d+)?)\s*[-~]\s*(\d+(\.\d+)?)\s*و–¤/g, (m, p1, p2, p3) => { + const start = parseFloat(p1) / 2; + const end = parseFloat(p3) / 2; + return `${start}-${end}kg`; + }); + size = size.replace(/(\d+(\.\d+)?)\s*و–¤/g, (m, p1) => `${parseFloat(p1) / 2}kg`); + size = size.replace(/\n.*$/, '').replace(/م€گ.*?م€‘/g, '').replace(/\s+/g, ' ').trim(); + if (!size) size = null; + } + + generated_options.push({ + color, + sizes: size ? [size] : [], + price: priceVal, + thumbnail: resolveThumbnail(key, color) + }); + } + + console.log(`Generated options from SKU map (${generated_options.length})`); + + // --- TRANSLATE OPTIONS IF AI IS AVAILABLE --- + if (aiClient && generated_options.length > 0) { + console.log(`Translating ${generated_options.length} options via AI (chunked)...`); + + const translateChunk = async (chunk) => { + const optionsText = JSON.stringify(chunk.map(o => ({ c: o.color, s: (o.sizes && o.sizes[0]) ? o.sizes[0] : "" }))); + const transPrompt = ` + Translate these product options to Arabic. + Input: ${optionsText} + + IMPORTANT: + - Return ONLY a JSON array. Do not include any conversational text like "Here is the JSON" or markdown code blocks. + - Keep the number of items EXACTLY the same as input. + - Keep the order EXACTLY the same as input. + - Each output item must be {"c": "...", "s": "..."}. + - If the input contains "kg" (kilograms), KEEP "kg" in the translation (e.g. "80kg" -> "80kg" or "80 ظƒط؛ظ…"). + - Do NOT convert numbers back to original units. + - Remove any Chinese characters or marketing text like "ه؟«è¦پو–­ç پ", "ه›¾ç‰‡è‰²" (Image Color), "é«کè´¨é‡ڈ", "ه»؛è®®", "و–¤". + - "图片色" or "默认" should be translated as "كما في الصورة" (As shown in image) or "اللون الافتراضي" (Default Color). + - Remove any newlines or extra whitespace. + - Return pure, clean Arabic names for colors and sizes. + - TRANSLATE COLORS TO ARABIC (e.g. "Black" -> "أسود", "红色" -> "أحمر"). + - TRANSLATE "建议" (Recommended) to "مقترح" or remove it if just a label. + - STRICTLY REMOVE any "return policy", "refund", "replacement" (e.g. "包退", "包换") text from option names. + `; + + const translate = async (model) => { + return await aiClient.chat.completions.create({ + model, + messages: [{ role: "user", content: transPrompt }], + temperature: 0.3, + max_tokens: 2048 + }); + }; + + let transRes; + try { + transRes = await translate(AI_PRIMARY_MODEL); + } catch (e) { + if (isTimeoutError(e)) { + throw e; + } + if (isModelBusyError(e)) { + console.log(`AI busy on ${AI_PRIMARY_MODEL}. Falling back to ${AI_BUSY_FALLBACK_MODEL} for options translation...`); + transRes = await translate(AI_BUSY_FALLBACK_MODEL); + } else if (AI_FALLBACK_MODEL && AI_FALLBACK_MODEL !== AI_PRIMARY_MODEL) { + console.log(`AI error on ${AI_PRIMARY_MODEL}. Falling back to ${AI_FALLBACK_MODEL} for options translation...`); + transRes = await translate(AI_FALLBACK_MODEL); + } else { + throw e; + } + } + + let transJson = transRes.choices[0].message.content.replace(/```json/g, '').replace(/```/g, '').trim(); + const startIdx = transJson.indexOf('['); + const endIdx = transJson.lastIndexOf(']'); + if (startIdx !== -1 && endIdx !== -1) transJson = transJson.substring(startIdx, endIdx + 1); + + const transArr = JSON.parse(transJson); + if (!Array.isArray(transArr) || transArr.length !== chunk.length) { + throw new Error(`Translation length mismatch (${Array.isArray(transArr) ? transArr.length : 'invalid'} vs ${chunk.length})`); + } + return transArr; + }; + + const applyTranslation = (chunk, transArr) => { + for (let i = 0; i < chunk.length; i++) { + const opt = chunk[i]; + const t = transArr[i] || {}; + if (t.c) opt.color = String(t.c).trim().replace(/\s+/g, ' '); + if (Array.isArray(opt.sizes) && opt.sizes.length > 0) { + if (t.s !== undefined && t.s !== null) { + const nextSize = String(t.s).trim().replace(/\s+/g, ' '); + if (nextSize) opt.sizes[0] = nextSize; + } + } + } + }; + + const baseChunkSize = Number(process.env.AI_OPTIONS_TRANSLATE_CHUNK_SIZE) > 0 ? Number(process.env.AI_OPTIONS_TRANSLATE_CHUNK_SIZE) : 25; + const queue = []; + for (let i = 0; i < generated_options.length; i += baseChunkSize) { + queue.push([i, Math.min(i + baseChunkSize, generated_options.length)]); + } + + while (queue.length > 0) { + const [start, end] = queue.shift(); + const chunk = generated_options.slice(start, end); + let ok = false; + let attempts = 0; + const maxAttempts = 3; + while (!ok && attempts < maxAttempts) { + attempts++; + try { + const transArr = await translateChunk(chunk); + applyTranslation(chunk, transArr); + ok = true; + } catch (e) { + if (attempts >= maxAttempts) break; + await delay(700); + } + } + if (!ok) { + if (chunk.length <= 1) continue; + const mid = start + Math.floor((end - start) / 2); + queue.unshift([mid, end]); + queue.unshift([start, mid]); + } + } + + console.log('Options translation applied (chunked best-effort).'); + } else { + console.log('Skipping options translation (AI not ready or no options).'); + } + + console.log(`Variant prices AFTER translation (${generated_options.length})`); + const postLines = []; + for (const opt of generated_options) { + const s = (opt.sizes && opt.sizes[0]) ? opt.sizes[0] : ''; + postLines.push(`${opt.color}${s ? `__SEP__${s}` : ''} => ${opt.price} IQD`); + } + const postPreviewLimit = 120; + postLines.slice(0, postPreviewLimit).forEach(l => console.log(` ${l}`)); + if (postLines.length > postPreviewLimit) console.log(` ... truncated ${postLines.length - postPreviewLimit} more`); + } + + const enrichedProduct = { + product_name: aiData.product_name_ar || 'اسم غير متوفر', + // original_name: data.title, // REMOVED as per request + main_images: data.images.slice(0, 5), + url: productUrl, + // product_details: data.productDetails, // REMOVED as per request + product_details: aiData.product_details_ar, // Use Arabic details as main 'product_details' + // product_details_ar: aiData.product_details_ar, // REMOVED redundancy + product_desc_imgs: data.product_desc_imgs || [], // Description Images + general_price: general_price, + generated_options: generated_options, // New Field + scrapedReviews: data.reviews || [], // Store reviews at top level (renamed from reviews) + aiMetadata: { ...(aiData.aiMetadata || {}) }, // Removed reviews from here + isAirRestricted: aiData.isAirRestricted || false, // New Field + // variants: data.variants, // REMOVED as per request + // skuMap: data.skuMap // REMOVED as per request + }; + + // Calculate Final Price with 15% Profit + const calculateFinalPrice = (base) => { + const price = Number(base) || 0; + if (price <= 0) return 0; + // Formula: (BaseIQD + Domestic) * 1.15 / 10 * 10 (ceil) + // Assuming domestic shipping is 0 or handled separately in cart logic, + // but usually scraper stores the inclusive price. + // Let's stick to the basic profit margin here. + return Math.ceil((price * 1.15) / 10) * 10; + }; + + const finalPrice = calculateFinalPrice(general_price); + + // CHECK: Skip product if price is too low (<= 250 IQD) + // This usually indicates a failed price extraction or a dummy product + if (finalPrice <= 250) { + console.log(`Skipping product: Price too low (Final: ${finalPrice}, Base: ${general_price}). URL: ${productUrl}`); + if (!navigationHappened) await newPage.close(); + else await newPage.goBack(); + continue; + } + + products.push(enrichedProduct); + console.log(`Scraped successfully. Total: ${products.length}`); + + fs.writeFileSync(OUTPUT_FILE, JSON.stringify(products, null, 2)); + + // --- DATABASE INSERTION --- + console.log('Inserting into Database...'); + try { + // 1. Create Product + const newProduct = await prisma.product.create({ + data: { + name: enrichedProduct.product_name, + price: finalPrice, // Store FINAL price with profit + basePriceIQD: enrichedProduct.general_price || 0, // Store BASE price (Cost) + image: enrichedProduct.main_images[0] || '', + purchaseUrl: enrichedProduct.url, + specs: JSON.stringify(enrichedProduct.product_details || {}), + aiMetadata: enrichedProduct.aiMetadata || {}, + scrapedReviews: enrichedProduct.scrapedReviews || [], // Save reviews to DB + isAirRestricted: enrichedProduct.isAirRestricted || false, // Save to DB + status: "PUBLISHED", + isActive: true, + } + }); + console.log(`Product created: ID ${newProduct.id}`); + + // 2. Create Product Images (Gallery) + if (enrichedProduct.main_images && enrichedProduct.main_images.length > 0) { + await prisma.productImage.createMany({ + data: enrichedProduct.main_images.map((url, i) => ({ + productId: newProduct.id, + url: url, + order: i, + type: "GALLERY" + })) + }); + } + + // 3. Create Description Images + if (enrichedProduct.product_desc_imgs && enrichedProduct.product_desc_imgs.length > 0) { + await prisma.productImage.createMany({ + data: enrichedProduct.product_desc_imgs.map((url, i) => ({ + productId: newProduct.id, + url: url, + order: i + 100, // Offset to keep them after gallery + type: "DESCRIPTION" + })) + }); + } + + // 4. Create Product Options (Color & Size) - VALIDATED + const colors = new Set(); + const sizes = new Set(); + + // Filter out Chinese characters from options + const containsChinese = (str) => /[\u4e00-\u9fa5]/.test(str); + + // Filter out invalid/suspicious options (Custom orders, deposits, etc.) + const invalidKeywords = [ + '定制', '专拍', '补差', '邮费', '不发货', '联系客服', // Chinese + 'تخصيص', 'اتصال', 'رابط', 'فرق', 'إيداع', 'لا يرسل', 'خدمة العملاء', 'مخصص' // Arabic + ]; + + enrichedProduct.generated_options = enrichedProduct.generated_options.filter(opt => { + const text = (opt.color || '') + ' ' + (opt.sizes ? opt.sizes.join(' ') : ''); + const hasInvalidKeyword = invalidKeywords.some(kw => text.includes(kw)); + + if (hasInvalidKeyword) { + console.log(`Skipping invalid/suspicious option: ${text} (Price: ${opt.price})`); + return false; + } + return true; + }); + + enrichedProduct.generated_options.forEach(opt => { + // Skip entire option if color is Chinese + if (opt.color && !containsChinese(opt.color)) { + colors.add(opt.color); + } else if (opt.color) { + // RETRY TRANSLATION FOR SINGLE OPTION + // We do a synchronous-like blocking call here or just use it as is if critical? + // User said: "try to translate it again if you can't then use it, don't skip generated options" + console.log(`Chinese color detected: ${opt.color}. Attempting fallback translation/usage...`); + colors.add(opt.color); // Add it anyway, don't skip + } + + if (opt.sizes && Array.isArray(opt.sizes)) { + opt.sizes.forEach(s => { + if (!containsChinese(s)) { + sizes.add(s); + } else { + console.log(`Chinese size detected: ${s}. Using it anyway.`); + sizes.add(s); + } + }); + } + }); + + // Only create options if we have valid values + if (colors.size > 0) { + await prisma.productOption.create({ + data: { + productId: newProduct.id, + name: "اللون", + values: JSON.stringify(Array.from(colors)) + } + }); + } + + if (sizes.size > 0) { + await prisma.productOption.create({ + data: { + productId: newProduct.id, + name: "المقاس", + values: JSON.stringify(Array.from(sizes)) + } + }); + } + + // 5. Create Variants - VALIDATED + const variantsData = []; + const normalizeVariantBasePrice = (basePrice) => { + let p = Number(basePrice) || 0; + if (p > 0 && p < 100) { + console.log(`Warning: Suspiciously low price (${p}). Assuming RMB and multiplying by 200.`); + p = p * 200; + } else if (p > 0 && p < 1000 && enrichedProduct.general_price > 5000) { + console.log(`Warning: Variant price ${p} vs Main ${enrichedProduct.general_price}. Assuming RMB.`); + p = p * 200; + } + return p; + }; + for (const opt of enrichedProduct.generated_options) { + // SKIP if color is Chinese (DISABLED: User wants to keep them) + // if (containsChinese(opt.color)) continue; + + const color = opt.color; + const fallbackBasePrice = normalizeVariantBasePrice(opt.price || enrichedProduct.general_price || 0); + const variantImg = opt.thumbnail || enrichedProduct.main_images[0] || ''; + + if (opt.sizes && Array.isArray(opt.sizes) && opt.sizes.length > 0) { + for (const size of opt.sizes) { + const variantBasePrice = fallbackBasePrice; + const variantFinalPrice = calculateFinalPrice(variantBasePrice); + const combinationObj = { + "اللون": color, + "المقاس": size + }; + variantsData.push({ + productId: newProduct.id, + combination: JSON.stringify(combinationObj), + price: variantFinalPrice, + basePriceIQD: variantBasePrice, + image: variantImg + }); + } + } else { + const variantBasePrice = fallbackBasePrice; + const variantFinalPrice = calculateFinalPrice(variantBasePrice); + const combinationObj = { "اللون": color }; + variantsData.push({ + productId: newProduct.id, + combination: JSON.stringify(combinationObj), + price: variantFinalPrice, + basePriceIQD: variantBasePrice, + image: variantImg + }); + } + } + + if (variantsData.length > 0) { + await prisma.productVariant.createMany({ + data: variantsData + }); + } + console.log('Database insertion complete.'); + + // Generate and save embedding for new product + if (newProduct && newProduct.id) { + try { + console.log('Triggers the embedding...'); + await processProductEmbedding(newProduct.id); + } catch (embedErr) { + console.error(`Embedding generation failed for product ${newProduct.id} (non-fatal):`, embedErr.message); + } + } + + } catch (dbErr) { + console.error('Database Insertion Failed:', dbErr.message); + } + + // --- SKIP DB INSERTION (Local Mode) --- + // console.log('Skipping Database Insertion (Local Mode)'); + + } catch (scrapeErr) { + console.error('Scrape error:', scrapeErr.message); + } + + // Clean up + if (!navigationHappened) { + await newPage.close(); + } else { + console.log('Going back to category page...'); + await page.goBack({ waitUntil: 'domcontentloaded' }); + await humanDelay(2000, 3000); + } + + await humanDelay(2000, 5000); + + // Random Delay between 10-15 seconds before next item + const nextItemDelay = 10000 + Math.random() * 5000; + console.log(`Waiting ${(nextItemDelay/1000).toFixed(1)}s before next item...`); + await delay(nextItemDelay); + } // End of 4-click loop + + // Scroll down to load more items for next pass + console.log('Finished batch of 4 clicks. Scrolling for more items...'); + await autoScroll(page); + await humanDelay(3000, 5000); + } + + console.log('[End] Scraping Complete.'); + await browser.close(); + await prisma.$disconnect(); +} + +run().catch(err => console.error('Fatal Error:', err)); + +process.on('unhandledRejection', (reason, p) => { + console.error('Unhandled Rejection at:', p, 'reason:', reason); +}); + +// Force keep-alive +setInterval(() => { + try { + fs.appendFileSync('scraper_debug.log', `Tick: ${new Date().toISOString()}\n`); + } catch(e) {} +}, 5000); diff --git a/server/scripts/pinduoduo-scraper.bak b/server/scripts/pinduoduo-scraper.bak new file mode 100644 index 0000000000000000000000000000000000000000..bf94b188c7efc0f0130ad6768d0b33c7913e03d8 --- /dev/null +++ b/server/scripts/pinduoduo-scraper.bak @@ -0,0 +1,3267 @@ +import vanillaPuppeteer from 'puppeteer-core'; +import puppeteerExtra from 'puppeteer-extra'; +import StealthPlugin from 'puppeteer-extra-plugin-stealth'; + +const puppeteer = puppeteerExtra.addExtra(vanillaPuppeteer); +puppeteer.use(StealthPlugin()); + +import fs from 'fs'; +import path from 'path'; +import dotenv from 'dotenv'; +import OpenAI from 'openai'; // Use OpenAI SDK for SiliconFlow +import readline from 'readline'; +import { fileURLToPath } from 'url'; +import { PrismaClient } from '@prisma/client'; +import { processProductEmbedding } from '../services/aiService.js'; + +// Load .env +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); +const envPath = path.join(__dirname, '..', '.env'); // server/.env +dotenv.config({ path: envPath }); +const prisma = new PrismaClient(); +// const prisma = { $disconnect: async () => {} }; + +// --- EDIBLE ITEM FILTERING CONFIGURATION --- +const EDIBLE_KEYWORDS = [ + "食品", "零食", "坚果", "罐头", "饮料", "糖果", "饼干", "调料", "茶", "酒", + "肉", "蛋", "奶", "油", "米", "面", "果冻", "巧克力", "咖啡", "food", "snack", + "nut", "can", "drink", "candy", "biscuit", "seasoning", "tea", "wine", + "meat", "egg", "milk", "oil", "rice", "noodle", "jelly", "chocolate", "coffee", + "吃", "喝", "味", "香", "甜", "辣", "咸", "酸", "苦" // General taste/eating words (use with caution or in combination) +]; + +// Stricter list for immediate rejection +const STRICT_EDIBLE_KEYWORDS = [ + "食品", "零食", "坚果", "罐头", "饮料", "糖果", "饼干", "调料", "茶叶", "酒水", + "鲜肉", "鸡蛋", "牛奶", "食用油", "大米", "面粉", "果冻", "巧克力", "咖啡豆", + "保健品", "维生素", "钙片", "酵素", "益生菌" // Supplements +]; + +function isEdiblePreCheck(title, description) { + const text = (title + " " + description).toLowerCase(); + + // Check strict keywords first + for (const keyword of STRICT_EDIBLE_KEYWORDS) { + if (text.includes(keyword)) { + return { isEdible: true, keyword: keyword }; + } + } + return { isEdible: false }; +} + +// Initialize AI (DeepInfra) +let aiClient = null; + +const AI_TIMEOUT_MS = Number(process.env.AI_TIMEOUT_MS) > 0 ? Number(process.env.AI_TIMEOUT_MS) : 180000; +const AI_MAX_ATTEMPTS = Number(process.env.AI_MAX_ATTEMPTS) > 0 ? Number(process.env.AI_MAX_ATTEMPTS) : 5; +const AI_BASE_RETRY_DELAY_MS = Number(process.env.AI_BASE_RETRY_DELAY_MS) > 0 ? Number(process.env.AI_BASE_RETRY_DELAY_MS) : 1500; + +const PUPPETEER_PROTOCOL_TIMEOUT_MS = + Number(process.env.PUPPETEER_PROTOCOL_TIMEOUT_MS) > 0 + ? Number(process.env.PUPPETEER_PROTOCOL_TIMEOUT_MS) + : 180000; +const PUPPETEER_DEFAULT_TIMEOUT_MS = + Number(process.env.PUPPETEER_DEFAULT_TIMEOUT_MS) > 0 + ? Number(process.env.PUPPETEER_DEFAULT_TIMEOUT_MS) + : 120000; + +let AI_PRIMARY_MODEL = process.env.AI_MODEL || "qwen/qwen-vl-plus"; +let AI_FALLBACK_MODEL = process.env.AI_FALLBACK_MODEL || AI_PRIMARY_MODEL; +let AI_MODEL = AI_PRIMARY_MODEL; +if (process.env.DEEPINFRA_API_KEY) { + AI_PRIMARY_MODEL = process.env.DEEPINFRA_MODEL || process.env.AI_MODEL || "google/gemma-3-12b-it"; + AI_FALLBACK_MODEL = process.env.DEEPINFRA_FALLBACK_MODEL || "google/gemma-3-27b-it"; + AI_MODEL = AI_PRIMARY_MODEL; + aiClient = new OpenAI({ + baseURL: "https://api.deepinfra.com/v1/openai", + apiKey: process.env.DEEPINFRA_API_KEY, + timeout: AI_TIMEOUT_MS, + maxRetries: 0, + }); + console.log(`AI Initialized (DeepInfra: primary=${AI_PRIMARY_MODEL}, fallback=${AI_FALLBACK_MODEL})`); +} else if (process.env.SILICONFLOW_API_KEY) { + // Fallback to SiliconFlow if DeepInfra not set (backward compatibility) + AI_PRIMARY_MODEL = process.env.SILICONFLOW_MODEL || process.env.AI_MODEL || AI_PRIMARY_MODEL; + AI_FALLBACK_MODEL = process.env.SILICONFLOW_FALLBACK_MODEL || process.env.AI_FALLBACK_MODEL || AI_PRIMARY_MODEL; + AI_MODEL = AI_PRIMARY_MODEL; + aiClient = new OpenAI({ + baseURL: "https://api.siliconflow.cn/v1", + apiKey: process.env.SILICONFLOW_API_KEY, + timeout: AI_TIMEOUT_MS, + maxRetries: 0, + }); + console.log(`AI Initialized (SiliconFlow: primary=${AI_PRIMARY_MODEL}, fallback=${AI_FALLBACK_MODEL})`); +} else { + console.log('Warning: No AI API KEY found. AI features will use mock data.'); +} + +const isModelBusyError = (e) => { + const message = (e && e.message) ? String(e.message) : String(e); + const code = (e && e.code) ? e.code : ''; + return ( + message.includes('429') || + String(code) === '429' || + message.toLowerCase().includes('model busy') || + message.toLowerCase().includes('rate limit') || + message.toLowerCase().includes('too many requests') + ); +}; + +const isTimeoutError = (e) => { + const message = (e && e.message) ? String(e.message) : String(e); + const name = (e && e.name) ? String(e.name) : ''; + const code = (e && e.code) ? String(e.code) : ''; + const status = (e && typeof e.status !== 'undefined') ? String(e.status) : ''; + return ( + name.toLowerCase().includes('timeout') || + message.toLowerCase().includes('timeout') || + code === 'ETIMEDOUT' || + code === 'UND_ERR_CONNECT_TIMEOUT' || + code === 'ECONNRESET' || + message.toLowerCase().includes('socket hang up') || + status === '408' + ); +}; + +const AI_BUSY_FALLBACK_MODEL = "google/gemma-3-27b-it"; + + +// --- Configuration --- +// Allow URL to be passed via command line argument +const cliUrl = process.argv[2]; +let CATEGORY_URL = cliUrl && cliUrl.startsWith('http') + ? cliUrl + : 'https://mobile.pinduoduo.com/search_result.html?search_key=%E5%8D%95%E8%82%A9%E5%8C%85%E5%A5%B3&search_type=goods&source=index&options=3&paste=1&search_met_track=manual&refer_page_el_sn=99885&refer_page_name=search_result&refer_page_id=10015_1771136715200_6j6plj2ual&refer_page_sn=10015&page_id=10015_1771136725342_6mr9yzf00z&bsch_is_search_mall=&bsch_show_active_page=&flip=0%3B0%3B0%3B0%3B630af7c3-043b-2964-39b0-12664add80c2%3B%2F20%3B0%3B0%3B47270af4a8bda0d0d524441a2e99ac18&sort_type=default&price_index=0&price=0%2C25&filter=price%2C0%2C25&opt_tag_name=&brand_tab_filter=&item_index=1'; + +if (cliUrl) { + console.log('Using URL from command line:', cliUrl); +} else { + console.log('Using default/hardcoded URL.'); +} + +const TARGET_PRODUCT_COUNT = 999999; // Effectively infinite +const OUTPUT_FILE = path.join(__dirname, '..', 'pinduoduo-products.json'); +const PAGE_LOAD_TIMEOUT = 60000; + +// Global flag for graceful shutdown +let isRunning = true; +process.on('SIGINT', () => { + console.log('\nReceived SIGINT. Stopping scraper gracefully...'); + isRunning = false; +}); + +function askQuestion(query) { + const rl = readline.createInterface({ + input: process.stdin, + output: process.stdout, + }); + return new Promise(resolve => rl.question(query, ans => { + rl.close(); + resolve(ans); + })); +} + +// Helper: Process with AI +async function enrichWithAI(title, description, price) { + if (!aiClient) { + return { + translatedTitle: title + " (Translation Pending)", + translatedDesc: description + " (Translation Pending)", + aiMetadata: { + synonyms: ["Placeholder"], + market_tags: ["Tag"], + category_suggestion: "General" + } + }; + } + + try { + const safeTitle = String(title || '').slice(0, 220); + const safeDescription = String(description || '').slice(0, 1200); + const safePrice = String(price || '').slice(0, 50); + + const prompt = ` + You are a product data enrichment assistant for an Iraqi e-commerce site. + + Original Product Title (Chinese): "${safeTitle}" + Product Description: "${safeDescription}" + Price: "${safePrice}" + + Task: + 1. Extract the Brand Name in English (e.g., "Nike", "Sony", "Xiaomi"). If no brand is found, ignore it. + 2. Translate the Product Name to ARABIC accurately. + - TARGET LANGUAGE: ARABIC (Iraq dialect or MSA). + - INPUT: Chinese -> OUTPUT: Arabic. + - DO NOT output English (except for the Brand Name). + - Remove marketing fluff like "hot sale", "new arrival", "2024", "Ready Stock". + - Example: "冬季加绒卫衣" -> "كنزة شتوية مبطنة" (NOT "Winter Fleece Sweater"). + 3. Combine them into "product_name_ar" format: "[Arabic Name]". + - ONLY include the brand if it is a well-known international brand (e.g. Nike, Adidas, Sony). + - If the brand is generic, unknown, or "No Brand", DO NOT include it in the title. + - NEVER include text like "No Brand", "Generic", "Other", "ماركة غير معروفة" in the title. + - IMPORTANT: You MUST translate the actual title. Do NOT use placeholder text like "اسم المنتج بالعربية". + 4. Extract "product_details_ar" as a structured Key-Value JSON object in ARABIC. + 5. Generate "aiMetadata" based strictly on the product Title and Description. + - "synonyms": Array of 3-5 alternative Arabic names SPECIFIC to this product. + - "market_tags": Array of 3-5 relevant tags in Arabic. + - "category_suggestion": A specific category path in Arabic. + 6. DETECT IF THE PRODUCT IS EDIBLE (Food, Drink, Nuts, Cans, Snacks, Ingredients, Supplements, Vitamins, Medicine). + - Set "is_edible": true if it is food/edible/supplement. + - Set "is_edible": false if it is NOT edible (e.g. clothes, electronics, tools). + - BE VERY CAREFUL. "Food Container" is NOT edible. "Dog Food" IS edible (sort of, but usually restricted). "Almond Oil for Skin" is NOT edible (cosmetic). "Almond Oil for Cooking" IS edible. + - If in doubt, set true to be safe. + + CRITICAL INSTRUCTIONS: + - The "product_name_ar" MUST be in ARABIC script (except the brand). + - If the original title is "WASSUP BEAVER...", translate "WASSUP BEAVER" as the Brand, and the rest as the Arabic name. + - NEVER return "اسم غير متوفر" (Name Not Available). ALWAYS generate a descriptive Arabic name based on the description if the title is unclear. + - Example: If title is "2025 Winter Jacket", output "سترة شتوية 2025". + - The translation MUST be high quality and natural for Arabic speakers in Iraq. + - If the product name is vague or generic in Chinese, infer the specific type from description or context. + - The "product_details_ar" field MUST be a JSON OBJECT (key-value pairs), NOT a string. + - Example format for details: + "product_details_ar": { + "المادة": "قماش كتّان", + "الميزة": "ألوان متعددة", + "التصميم": "إبداعي", + "الاستخدام": "غرفة المعيشة" + } + - STRICTLY EXCLUDE any "return policy", "refund", "replacement", "shipping", "free shipping", or "guarantee" information from details. + - STRICTLY EXCLUDE any PRICE or COST information (e.g., "السعر", "Price", "29.9 ريال") from details. + - DO NOT include keys with EMPTY values (e.g. "الماركة": "" should be removed). + - Do NOT include any Chinese characters (like ¥, 包邮, 品牌, etc.) in values. + - English text IS ALLOWED for Brand Names and Model Numbers. + - Convert all prices and measurements to Arabic format if possible. + + Return ONLY a valid JSON object with this structure (no markdown): + { + "product_name_ar": "Put Translated Name Here", + "is_edible": false, + "product_details_ar": { + "الماركة": "قيمة", + "اللون": "قيمة", + "المادة": "قيمة" + }, + "aiMetadata": { + "synonyms": ["مرادف1", "مرادف2"], + "market_tags": ["تاق1", "تاق2"], + "category_suggestion": "اسم التصنيف" + } + } + `; + + let attempts = 0; + + while (attempts < AI_MAX_ATTEMPTS) { + try { + const create = async (model) => { + return await aiClient.chat.completions.create({ + model, + messages: [{ role: "user", content: prompt }], + temperature: 0.2, + max_tokens: 900, + }); + }; + + let response; + try { + response = await create(AI_PRIMARY_MODEL); + } catch (e) { + if (isTimeoutError(e)) { + throw e; + } + if (isModelBusyError(e)) { + console.log(`AI busy on ${AI_PRIMARY_MODEL}. Falling back to ${AI_BUSY_FALLBACK_MODEL}...`); + response = await create(AI_BUSY_FALLBACK_MODEL); + } else if (AI_FALLBACK_MODEL && AI_FALLBACK_MODEL !== AI_PRIMARY_MODEL) { + console.log(`AI error on ${AI_PRIMARY_MODEL}. Falling back to ${AI_FALLBACK_MODEL}...`); + response = await create(AI_FALLBACK_MODEL); + } else { + throw e; + } + } + + let text = response.choices[0].message.content; + text = text.replace(/```json/g, '').replace(/```/g, '').trim(); + + // Attempt to fix common JSON syntax errors from AI + // 1. Remove trailing commas in objects/arrays: ,} -> } or ,] -> ] + text = text.replace(/,(\s*[}\]])/g, '$1'); + + const jsonStart = text.indexOf('{'); + let parsed = null; + + if (jsonStart !== -1) { + let endSearchPos = text.lastIndexOf('}'); + while (endSearchPos > jsonStart) { + try { + const candidate = text.substring(jsonStart, endSearchPos + 1); + parsed = JSON.parse(candidate); + break; + } catch (e) { + endSearchPos = text.lastIndexOf('}', endSearchPos - 1); + } + } + } + + if (!parsed) { + console.error("Failed to parse AI response. Raw text:", text); + throw new Error("JSON parsing failed after multiple attempts."); + } + + // CHECK FOR INVALID/PLACEHOLDER NAMES + if (parsed.product_name_ar) { + const badNames = [ + 'اسم غير متوفر', + 'name not available', + 'اسم المنتج بالعربيه', + 'اسم المنتج بالعربية', + 'put translated name here', + 'arabic name', + 'ترجمة اسم المنتج' + ]; + const lowerName = parsed.product_name_ar.toLowerCase(); + + // Check if name matches any bad pattern or contains Chinese + if (badNames.some(bad => lowerName.includes(bad)) || /[\u4e00-\u9fa5]/.test(parsed.product_name_ar)) { + console.log(`AI returned invalid name: "${parsed.product_name_ar}". Retrying...`); + throw new Error('AI returned invalid name (placeholder or Chinese)'); + } + } else { + throw new Error('AI returned empty product_name_ar'); + } + + try { + const stripChinese = (str) => { + if (typeof str !== 'string') return str; + // Don't strip immediately, let's keep it for now or refine logic + // Only strip if it's mixed, but for Arabic name we want PURE Arabic. + // However, if AI returns "Brand (English) + Arabic", that's fine. + return str.trim(); + }; + + // if (parsed.product_name_ar) { ... } // Removed redundant check block since we did it above + + if (parsed.product_details_ar) { + for (const key in parsed.product_details_ar) { + // Strip Chinese + parsed.product_details_ar[key] = stripChinese(parsed.product_details_ar[key]); + + // Check if value still has Chinese characters + if (/[\u4e00-\u9fa5]/.test(parsed.product_details_ar[key])) { + delete parsed.product_details_ar[key]; // Remove key if translation failed + } + + // Remove empty keys + if (!parsed.product_details_ar[key] || parsed.product_details_ar[key].trim() === '') { + delete parsed.product_details_ar[key]; + } + } + } + + if (parsed.aiMetadata) { + // Ensure arrays are arrays + if (!Array.isArray(parsed.aiMetadata.synonyms)) parsed.aiMetadata.synonyms = []; + if (!Array.isArray(parsed.aiMetadata.market_tags)) parsed.aiMetadata.market_tags = []; + if (!parsed.aiMetadata.category_suggestion) parsed.aiMetadata.category_suggestion = "عام"; + } else { + // Fallback: Try to infer from parsed name if possible, otherwise use generic but marked as fallback + parsed.aiMetadata = { + synonyms: [parsed.product_name_ar], // Use the name itself as a synonym at least + market_tags: ["منتج مميز"], + category_suggestion: "أخرى" + }; + } + + return parsed; + } catch (jsonError) { + throw jsonError; + } + } catch (e) { + attempts++; + const message = (e && e.message) ? e.message : String(e); + console.error(`AI Error (Attempt ${attempts}/${AI_MAX_ATTEMPTS}):`, message); + + const isRateLimit = isModelBusyError(e) || message.includes('429'); + const isTimeout = isTimeoutError(e); + + if (isRateLimit) { + const waitTime = Math.min(45000, 5000 * attempts) + Math.floor(Math.random() * 1000); + console.log(`Rate limit hit. Waiting ${(waitTime / 1000).toFixed(1)}s...`); + await delay(waitTime); + continue; + } + + if (isTimeout) { + const waitTime = Math.min(45000, AI_BASE_RETRY_DELAY_MS * (2 ** Math.max(0, attempts - 1))) + Math.floor(Math.random() * 1000); + await delay(waitTime); + continue; + } + + await delay(2000 + Math.floor(Math.random() * 500)); + } + } + throw new Error("Max AI attempts reached"); + } catch (e) { + console.error("AI Generation Error:", e.message); + // CRITICAL CHANGE: If all attempts failed or returned bad names, SKIP this product. + // Return a special flag to the caller. + return { + shouldSkip: true, + reason: "AI Translation Failed (Max Attempts)" + }; + } +} + +const CHROME_PATHS = [ + 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe', + 'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe', + 'C:\\Program Files\\Microsoft\\Edge\\Application\\msedge.exe', + 'C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe' +]; + +function getExecutablePath() { + for (const p of CHROME_PATHS) { + if (fs.existsSync(p)) return p; + } + return null; +} + +const delay = (ms) => new Promise(resolve => { + const end = Date.now() + ms; + const timer = setInterval(() => { + if (Date.now() >= end) { + clearInterval(timer); + resolve(); + } + }, 100); +}); +const humanDelay = (min = 1000, max = 3000) => delay(Math.floor(Math.random() * (max - min + 1)) + min); + +async function applyPageTimeouts(page) { + if (!page) return; + try { page.setDefaultTimeout(PUPPETEER_DEFAULT_TIMEOUT_MS); } catch (e) {} + try { page.setDefaultNavigationTimeout(PUPPETEER_DEFAULT_TIMEOUT_MS); } catch (e) {} +} + +async function waitForStableUrl(page, stableMs = 1200, timeoutMs = 12000) { + const start = Date.now(); + let lastUrl = ''; + let lastChangeAt = Date.now(); + try { lastUrl = page.url(); } catch (e) { lastUrl = ''; } + lastChangeAt = Date.now(); + + while (Date.now() - start < timeoutMs) { + if (!page || (page.isClosed && page.isClosed())) return lastUrl; + await delay(200); + let cur = ''; + try { cur = page.url(); } catch (e) { cur = lastUrl; } + if (cur && cur !== lastUrl) { + lastUrl = cur; + lastChangeAt = Date.now(); + } + if (Date.now() - lastChangeAt >= stableMs) return lastUrl; + } + return lastUrl; +} + +async function safeEvaluate(page, pageFunction, args = [], maxAttempts = 4) { + let lastErr = null; + for (let attempt = 1; attempt <= maxAttempts; attempt++) { + try { + return await page.evaluate(pageFunction, ...args); + } catch (e) { + lastErr = e; + const msg = String(e?.message || e || ''); + const isContextDestroyed = + msg.includes('Execution context was destroyed') || + msg.includes('Cannot find context') || + msg.includes('Target closed') || + msg.includes('Session closed') || + msg.includes('Most likely the page has been closed') || + msg.includes('Navigating frame was detached') || + msg.includes('frame was detached'); + + if (!isContextDestroyed) throw e; + + try { + await delay(300 * attempt); + await Promise.race([ + page.waitForNavigation({ waitUntil: 'domcontentloaded', timeout: 8000 }).catch(() => null), + waitForStableUrl(page, 1400, 12000) + ]); + } catch (e2) {} + } + } + throw lastErr || new Error('safeEvaluate failed'); +} + +async function createBrowser() { + const executablePath = getExecutablePath(); + if (!executablePath) { + console.error('Chrome/Edge executable not found.'); + process.exit(1); + } + + return await puppeteer.launch({ + executablePath, + headless: false, + defaultViewport: null, + protocolTimeout: PUPPETEER_PROTOCOL_TIMEOUT_MS, + // userDataDir: 'chrome_data_pdd_fresh_v36', + userDataDir: 'chrome_data_pdd_persistent', // Use fixed directory to keep session alive + args: [ + '--no-sandbox', + '--disable-setuid-sandbox', + '--disable-infobars', + '--window-position=0,0', + '--ignore-certificate-errors', + '--ignore-certificate-errors-spki-list', + '--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36', + '--lang=zh-CN,zh' + ] + }); +} + +async function autoScroll(page) { + await page.evaluate(async () => { + await new Promise((resolve) => { + let totalHeight = 0; + const distance = 100; + const timer = setInterval(() => { + const scrollHeight = document.body.scrollHeight; + window.scrollBy(0, distance); + totalHeight += distance; + if (totalHeight >= 600) { + clearInterval(timer); + resolve(); + } + }, 100); + }); + }); +} + +async function run() { + console.log('[Start] Initializing Pinduoduo Scraper (Click-and-Scrape Mode)...'); + + // Ask for URL or use predefined + console.log('----------------------------------------------------'); + let urlInput = ''; + + // Check if CATEGORY_URL is already set in the code (length > 10) + if (CATEGORY_URL && CATEGORY_URL.length > 10) { + urlInput = CATEGORY_URL; + console.log('Using predefined CATEGORY_URL from script.'); + } else if (process.argv[2]) { + urlInput = process.argv[2]; + } else { + urlInput = await askQuestion('Enter the Pinduoduo Category URL to scrape: '); + } + + urlInput = urlInput.trim(); + if (!urlInput.startsWith('http')) { + console.error('❌ Error: Invalid URL provided. The URL must start with "http" or "https".'); + console.error('You entered:', urlInput); + console.log('Please restart the script and paste the correct URL.'); + process.exit(1); + } + + // const urlInput = "https://mobile.pinduoduo.com/catgoods.html?refer_page_name=index&opt_id=25667&opt_name=%E4%B8%8A%E8%A1%A3%E5%A4%96%E5%A5%97&opt_type=2&goods_id=836596630021&refer_page_id=10002_1770945474906_zhvvkggy6l&refer_page_sn=10002"; + console.log('Using URL:', urlInput); + console.log('----------------------------------------------------'); + CATEGORY_URL = urlInput.trim(); + + let browser = await createBrowser(); + console.log('Browser launched'); + let page = await browser.newPage(); + console.log('Page created'); + + // Enable console log forwarding from the browser to the terminal + page.on('console', msg => { + const type = msg.type(); + const text = msg.text(); + // Filter out some noise if needed, but user wants logs so keep most + if (!text.includes('ERR_BLOCKED_BY_CLIENT')) { + console.log(`[Browser Console] ${type.toUpperCase()}: ${text}`); + } + }); + + page.on('pageerror', err => { + console.log(`[Browser Error]: ${err.toString()}`); + }); + + await applyPageTimeouts(page); + + // --- STEALTH MEASURES --- + + // 1. Set Mobile Viewport (Android) + // await page.setViewport({ width: 360, height: 800, isMobile: true, hasTouch: true }); + + // Switch to Desktop Viewport + await page.setViewport({ width: 1366, height: 768 }); + + // 2. Override Navigator Properties to mimic Android + await page.evaluateOnNewDocument(() => { + // Force language to Chinese + Object.defineProperty(navigator, 'language', { get: () => 'zh-CN' }); + Object.defineProperty(navigator, 'languages', { get: () => ['zh-CN', 'zh'] }); + + // Add minimal mouse movement to simulate human + window.addEventListener('load', () => { + document.body.addEventListener('mousemove', () => {}); + document.body.addEventListener('touchstart', () => {}); + }); + }); + + // 4. Load cookies if exist + try { + const cookiePath = path.join(__dirname, 'pdd_cookies.json'); + if (fs.existsSync(cookiePath)) { + const cookies = JSON.parse(fs.readFileSync(cookiePath, 'utf8')); + if (cookies.length > 0) { + console.log(`Loading ${cookies.length} saved cookies...`); + await page.setCookie(...cookies); + } + } + } catch (err) { + console.error('Failed to load cookies:', err.message); + } + + // 5. Perform Login DIRECTLY on the target Category Page + // Why? Navigating from Home -> Category often triggers "Drifting" or "Bot Detection". + // It's better to just go straight to the category, log in there if needed, and then start scraping. + + // FORCE LOGIN NAVIGATION IF NOT LOGGED IN + console.log('Visiting Login URL first to ensure valid session...'); + try { + await page.goto('https://mobile.pinduoduo.com/login.html', { waitUntil: 'domcontentloaded', timeout: PAGE_LOAD_TIMEOUT }); + } catch(e) { console.log('Login goto error (might be redirect):', e.message); } + + console.log('Login page loaded (or redirected).'); + + console.log('================================================================'); + console.log(' PAUSING FOR MANUAL LOGIN (30 seconds)'); + console.log(' 1. Please login manually using SMS/Phone.'); + console.log(' 2. Once logged in, you should see the home page.'); + console.log(' 3. The script will then redirect to the category page.'); + console.log('================================================================'); + await delay(30000); + + // CLEAN CATEGORY URL to remove tracking params + let cleanUrl = CATEGORY_URL; + try { + const u = new URL(CATEGORY_URL); + const searchKey = u.searchParams.get('search_key'); + const catId = u.searchParams.get('cat_id'); + const optId = u.searchParams.get('opt_id'); + + // Construct a clean URL + if (searchKey) { + cleanUrl = `https://mobile.pinduoduo.com/search_result.html?search_key=${encodeURIComponent(searchKey)}&search_type=goods`; + } else if (catId) { + cleanUrl = `https://mobile.pinduoduo.com/catgoods.html?cat_id=${catId}&opt_id=${optId || catId}`; + } else if (optId) { + cleanUrl = `https://mobile.pinduoduo.com/catgoods.html?opt_id=${optId}`; + } + + console.log('Original URL:', CATEGORY_URL); + console.log('Cleaned URL:', cleanUrl); + } catch(e) { + console.log('Error cleaning URL:', e.message); + cleanUrl = CATEGORY_URL; // Fallback + } + + console.log('Visiting Clean Category URL:', cleanUrl); + await page.goto(cleanUrl, { waitUntil: 'domcontentloaded', timeout: PAGE_LOAD_TIMEOUT }); + console.log('Category page loaded.'); + + // SWITCH TO MOBILE VIEWPORT AFTER LOGIN & NAVIGATION + console.log('Switching to Mobile Viewport for scraping...'); + await page.setViewport({ width: 360, height: 800, isMobile: true, hasTouch: true }); + await delay(2000); + + /* + console.log('Visiting Category URL (and performing login check there):', CATEGORY_URL); + await page.goto(CATEGORY_URL, { waitUntil: 'domcontentloaded', timeout: PAGE_LOAD_TIMEOUT }); + console.log('Goto done'); + + console.log('================================================================'); + console.log(' PAUSING FOR MANUAL LOGIN / CHECK (40 seconds)'); + console.log(' 1. If you see a login screen, please log in.'); + console.log(' 2. If you see "Sold Out", try refreshing manually.'); + console.log(' 3. Make sure you see the product list before this timer ends.'); + console.log('================================================================'); + console.log('Starting delay...'); + await delay(40000); + console.log('Delay finished. Resuming...'); + */ + + // SAVE COOKIES AFTER LOGIN + try { + const cookies = await page.cookies(); + const cookiePath = path.join(__dirname, 'pdd_cookies.json'); + fs.writeFileSync(cookiePath, JSON.stringify(cookies, null, 2)); + console.log('✅ Login cookies saved to pdd_cookies.json'); + } catch (err) { + console.error('Failed to save cookies:', err.message); + } + + // Wait extra time for the page to fully stabilize + console.log('Waiting 5s for page stabilization...'); + await delay(5000); + + // --- SCROLL PAST HEADER --- + console.log('Scrolling down to bypass header/category icons...'); + + try { + // Scroll down one full screen height + a bit more + await page.evaluate(async () => { + const viewportHeight = window.innerHeight; + window.scrollBy(0, viewportHeight + 200); + await new Promise(r => setTimeout(r, 1000)); + }); + } catch (e) { + console.warn('⚠️ Scroll error (ignoring):', e.message); + // If execution context destroyed, it usually means page refreshed or navigated. + // We can just wait a bit and proceed. + await delay(1000); + } + + await humanDelay(2000, 3000); + + // 3. Click and Scrape Loop + console.log('[Phase 1] Starting Click-and-Scrape Loop...'); + + // STRATEGY CHANGE: Blind Click in Center-Right + // Since element detection is being blocked or misled by PDD's anti-bot structure, + // we will simulate a human tapping on a likely product location. + // On mobile view (375x667 approx), products are usually in a 2-column grid. + // A tap at roughly (75% width, 50% height) should hit the right-side product. + + let products = []; + try { + if (fs.existsSync(OUTPUT_FILE)) { + products = JSON.parse(fs.readFileSync(OUTPUT_FILE)); + } + } catch(e) {} + + // Main Loop + // User requested infinite loop until manually stopped + while (isRunning) { + + // --- VALIDATE CURRENT URL --- + // Ensure we are still on the category page or search result page we started with. + // If we drifted to home or another category, go back. + const currentUrlBeforeScroll = page.url(); + const isHomePage = currentUrlBeforeScroll === 'https://mobile.pinduoduo.com/' || currentUrlBeforeScroll.includes('page_id=10002'); + // Simple check: if we are not on the category URL and not on a product page (which we shouldn't be here), go back. + // Better: Check if the URL contains key parts of our CATEGORY_URL + // Extract 'search_key' from CATEGORY_URL if it exists + let requiredParam = ''; + try { + const catUrlObj = new URL(CATEGORY_URL); + if (catUrlObj.searchParams.has('search_key')) { + requiredParam = 'search_key=' + encodeURIComponent(catUrlObj.searchParams.get('search_key')); + } else if (catUrlObj.searchParams.has('cat_id')) { + requiredParam = 'cat_id=' + catUrlObj.searchParams.get('cat_id'); + } + } catch(e) {} + + // DISABLE AUTO-REDIRECT for now - it's causing loops if the URL format changes slightly + // if (isHomePage || (requiredParam && !currentUrlBeforeScroll.includes(decodeURIComponent(requiredParam)) && !currentUrlBeforeScroll.includes(requiredParam))) { + // console.log('WARNING: Drifted away from category page. Redirecting back to:', CATEGORY_URL); + // await page.goto(CATEGORY_URL, { waitUntil: 'domcontentloaded', timeout: PAGE_LOAD_TIMEOUT }); + // await humanDelay(3000, 5000); + // } + + + // --- 4-POINT BLIND CLICK STRATEGY --- + console.log('Scrolling down to find new batch of products...'); + + // 1. Scroll down one screen size + a bit + try { + await page.evaluate(async () => { + // Random scroll + const viewportHeight = window.innerHeight; + const distance = viewportHeight + 100 + Math.floor(Math.random() * 200); + window.scrollBy(0, distance); + await new Promise(r => setTimeout(r, 1000)); + }); + } catch (e) { + console.warn('⚠️ Scroll error in loop (recovering):', e.message); + // Wait and reload context if needed + await delay(2000); + if (page.isClosed()) break; + continue; // Skip this iteration + } + + await humanDelay(2000, 3000); + + // Define the 4 click points (percentages of viewport) + // Adjust for Mobile Viewport in Desktop Browser + const clickPoints = [ + { name: "Top-Right", xPct: 0.75, yPct: 0.30 }, + { name: "Top-Left", xPct: 0.25, yPct: 0.30 }, + { name: "Bot-Left", xPct: 0.25, yPct: 0.70 }, + { name: "Bot-Right", xPct: 0.75, yPct: 0.70 } + ]; + + for (const point of clickPoints) { + if (!isRunning) break; + // if (products.length >= TARGET_PRODUCT_COUNT) break; // Removed limit as per request + + console.log(`Preparing to click: ${point.name}...`); + + const clickCoordinates = await page.evaluate((pt) => { + const width = window.innerWidth; + const height = window.innerHeight; + + // Add randomization (+/- 15px) + const randomX = Math.floor(Math.random() * 30) - 15; + const randomY = Math.floor(Math.random() * 30) - 15; + + return { + x: Math.floor(width * pt.xPct) + randomX, + y: Math.floor(height * pt.yPct) + randomY + }; + }, point); + + console.log(`Clicking at (${clickCoordinates.x}, ${clickCoordinates.y})...`); + + // Listen for new target + const newTargetPromise = new Promise(resolve => browser.once('targetcreated', resolve)); + const currentUrl = page.url(); + + try { + // Use evaluating touchstart for mobile simulation if mouse click fails + await page.mouse.click(clickCoordinates.x, clickCoordinates.y); + } catch (e) { + console.log('Click failed:', e.message); + } + + // Wait for navigation + let newPage = null; + let navigationHappened = false; + + try { + const target = await Promise.race([ + newTargetPromise, + delay(3000).then(() => null) + ]); + + if (target && target.type() === 'page') { + console.log('New tab detected.'); + newPage = await target.page(); + + // ENABLE CONSOLE LOGS FOR NEW TAB + newPage.on('console', msg => { + const type = msg.type(); + const text = msg.text(); + if (!text.includes('ERR_BLOCKED_BY_CLIENT')) { + console.log(`[Browser NewPage] ${type.toUpperCase()}: ${text}`); + } + }); + + await applyPageTimeouts(newPage); + + // STEALTH: Ensure new page looks like it came from the main page + await newPage.bringToFront(); + + // IMPORTANT: Set viewport for the new tab too! + await newPage.setViewport({ width: 360, height: 800, isMobile: true, hasTouch: true }); + + try { + await newPage.setExtraHTTPHeaders({ + 'Referer': currentUrl, + // 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8' // Already handled by args + }); + } catch(e) {} + } else { + console.log('No new tab. Checking if current page navigated...'); + await delay(2000); + if (page.url() !== currentUrl && !page.url().includes('catgoods')) { + console.log('Current page navigated. Treating as product page.'); + newPage = page; + navigationHappened = true; + await applyPageTimeouts(newPage); + } else { + console.log('Click did not trigger navigation. Moving to next point.'); + // Just continue to next point in loop + continue; + } + } + } catch (e) { + console.log('Target detection error:', e.message); + continue; + } + + if (!newPage) continue; + + // --- SCRAPE PRODUCT PAGE --- + try { + await newPage.waitForLoadState ? newPage.waitForLoadState('domcontentloaded') : newPage.waitForSelector('body', { timeout: 15000 }); + await humanDelay(2000, 4000); + await waitForStableUrl(newPage, 1200, 12000); + + // CHECK FOR "SOLD OUT" STATE + const isLogin = await safeEvaluate(newPage, () => { + const t = (document.body && document.body.innerText) ? document.body.innerText : ''; + const s = String(t || ''); + return s.includes('登录') && (s.includes('扫码登录') || s.includes('同意服务协议') || s.includes('隐私政策')); + }, [], 12); + + if (isLogin) { + console.log('⚠️ Hit login page. Skipping product and returning to listing...'); + if (!navigationHappened && newPage.close) await newPage.close(); + else { + try { + await newPage.goBack({ waitUntil: 'domcontentloaded', timeout: PAGE_LOAD_TIMEOUT }); + } catch (e) { + try { + await newPage.goto(currentUrl || CATEGORY_URL, { waitUntil: 'domcontentloaded', timeout: PAGE_LOAD_TIMEOUT }); + } catch (e2) {} + } + } + continue; + } + + const isSoldOut = await safeEvaluate(newPage, () => { + const text = document.body.innerText; + return text.includes('商品已售罄') || text.includes('已售完') || text.includes('下架'); + }); + + if (isSoldOut) { + console.log('⚠️ Product is SOLD OUT (or Anti-Bot triggered). Skipping...'); + console.log(' -> Hint: If this happens for ALL products, try deleting pdd_cookies.json and re-login.'); + if (!navigationHappened) await newPage.close(); + else await newPage.goBack(); + continue; + } + + const productUrl = newPage.url(); + console.log(`Scraping Product URL: ${productUrl}`); + + // --- ROBUST DEDUPLICATION --- + try { + const urlObj = new URL(productUrl); + const goodsId = urlObj.searchParams.get('goods_id'); + + if (goodsId) { + // 1. Check if already in current session (in-memory) + const alreadyScrapedInSession = products.some(p => p.url && p.url.includes(goodsId)); + if (alreadyScrapedInSession) { + console.log(`Product already scraped in THIS SESSION. Skipping: ${goodsId}`); + if (!navigationHappened) await newPage.close(); + else await newPage.goBack(); + continue; + } + + // 2. Check Database + const existingProduct = await prisma.product.findFirst({ + where: { + purchaseUrl: { + contains: goodsId + } + } + }); + + if (existingProduct) { + console.log(`Product already in DB (ID: ${existingProduct.id}). Skipping: ${goodsId}`); + if (!navigationHappened) await newPage.close(); + else await newPage.goBack(); + continue; + } + } + } catch (dbCheckError) { + console.error('Error checking DB for duplicate:', dbCheckError.message); + } + + // Deduplicate by URL (Fallback) + if (products.some(p => p.url === productUrl)) { + console.log('Duplicate product URL. Skipping.'); + if (!navigationHappened) await newPage.close(); + else await newPage.goBack(); + continue; + } + + // --- WAIT FOR PAGE LOAD --- + // Ensure the page is fully loaded before scraping + try { + await newPage.waitForLoadState ? newPage.waitForLoadState('domcontentloaded') : newPage.waitForSelector('body', { timeout: 15000 }); + await humanDelay(2000, 4000); + } catch (e) { + console.log('Page load timeout, attempting scrape anyway...'); + } + + /* + // --- RANDOM MOVES ON PRODUCT PAGE (Anti-Detection) --- + console.log('Performing random moves on product page...'); + try { + await newPage.evaluate(async () => { + const wait = (ms) => new Promise(r => setTimeout(r, ms)); + const height = document.body.scrollHeight; + + // Scroll down a bit + window.scrollBy(0, 300 + Math.random() * 200); + await wait(1000 + Math.random() * 1000); + + // Scroll up a bit + window.scrollBy(0, -100); + await wait(500 + Math.random() * 500); + + // Maybe scroll to bottom + if (Math.random() > 0.5) { + window.scrollTo(0, height * 0.7); + await wait(1000); + } + }); + + // Stay on page for 5-10 seconds + const stayTime = 5000 + Math.random() * 5000; + console.log(`Staying on product page for ${(stayTime/1000).toFixed(1)}s...`); + await delay(stayTime); + } catch(e) { + console.log('Random moves failed:', e.message); + } + */ + + const openOptionsModalIfNeeded = async (page) => { + const modalSelector = '.HidQ9ROd, div[role="dialog"][aria-modal="true"], div[role="dialog"]'; + + const hasVisibleSkuModal = async () => { + return await page.evaluate((sel) => { + const visible = (el) => { + if (!el) return false; + if (el.getAttribute && el.getAttribute('aria-hidden') === 'true') return false; + const style = window.getComputedStyle(el); + if (!style) return false; + if (style.display === 'none' || style.visibility === 'hidden') return false; + const opacity = parseFloat(style.opacity || '1'); + if (!Number.isNaN(opacity) && opacity <= 0.02) return false; + const r = el.getBoundingClientRect(); + if (!r || r.width < 40 || r.height < 40) return false; + const intersects = + r.bottom > 0 && + r.right > 0 && + r.top < window.innerHeight && + r.left < window.innerWidth; + if (!intersects) return false; + const x = Math.floor(Math.min(window.innerWidth - 2, Math.max(1, r.left + r.width * 0.5))); + const y = Math.floor(Math.min(window.innerHeight - 2, Math.max(1, r.top + r.height * 0.5))); + const top = document.elementFromPoint(x, y); + if (top && (el === top || el.contains(top))) return true; + return false; + }; + + const isSku = (m) => { + try { + if (m && m.matches && m.matches('.HidQ9ROd')) return true; + } catch (e) {} + if (m && m.querySelector && m.querySelector('.iW4aEGbb')) return false; + const t = String(m?.innerText || m?.textContent || ''); + if (t.includes('已选') || t.includes('请选择') || t.includes('规格')) return true; + if (m.querySelector('.O7pEFvHR') || m.querySelector('.bIhLWVqm') || m.querySelector('li.TpUpcNRp') || m.querySelector('div._8gg8ho2u')) return true; + return false; + }; + + const modals = Array.from(document.querySelectorAll(sel)); + return modals.some(m => visible(m) && isSku(m)); + }, modalSelector).catch(() => false); + }; + + if (await hasVisibleSkuModal()) { + console.log('[PDD] Options modal already open'); + return true; + } + + const tryClickAndWaitModal = async (x, y, modalWaitMs = 2500) => { + let before = ''; + try { before = page.url(); } catch (e) { before = ''; } + + try { + try { await page.mouse.move(Math.max(1, x - 18), Math.max(1, y - 18)); } catch (e) {} + await humanDelay(700, 1200); + await page.mouse.click(x, y); + } catch (e) { + return false; + } + + await humanDelay(1200, 2200); + const ok = await page.waitForFunction( + (sel) => { + const visible = (el) => { + if (!el) return false; + if (el.getAttribute && el.getAttribute('aria-hidden') === 'true') return false; + const style = window.getComputedStyle(el); + if (!style) return false; + if (style.display === 'none' || style.visibility === 'hidden') return false; + const opacity = parseFloat(style.opacity || '1'); + if (!Number.isNaN(opacity) && opacity <= 0.02) return false; + const r = el.getBoundingClientRect(); + if (!r || r.width < 40 || r.height < 40) return false; + const intersects = + r.bottom > 0 && + r.right > 0 && + r.top < window.innerHeight && + r.left < window.innerWidth; + if (!intersects) return false; + const x = Math.floor(Math.min(window.innerWidth - 2, Math.max(1, r.left + r.width * 0.5))); + const y = Math.floor(Math.min(window.innerHeight - 2, Math.max(1, r.top + r.height * 0.5))); + const top = document.elementFromPoint(x, y); + if (top && (el === top || el.contains(top))) return true; + return false; + }; + + const isSku = (m) => { + try { + if (m && m.matches && m.matches('.HidQ9ROd')) return true; + } catch (e) {} + if (m && m.querySelector && m.querySelector('.iW4aEGbb')) return false; + const t = String(m?.innerText || m?.textContent || ''); + if (t.includes('已选') || t.includes('请选择') || t.includes('规格')) return true; + if (m.querySelector('.O7pEFvHR') || m.querySelector('.bIhLWVqm') || m.querySelector('li.TpUpcNRp') || m.querySelector('div._8gg8ho2u')) return true; + return false; + }; + + const modals = Array.from(document.querySelectorAll(sel)); + return modals.some(m => visible(m) && isSku(m)); + }, + { timeout: modalWaitMs }, + modalSelector + ).catch(() => null); + if (ok) return true; + + let after = ''; + try { after = page.url(); } catch (e) { after = before; } + if (after.includes('/order_checkout.html') || after.includes('order_checkout.html')) { + try { + await page.goBack({ waitUntil: 'domcontentloaded', timeout: PAGE_LOAD_TIMEOUT }); + await waitForStableUrl(page, 1400, 15000); + } catch (e) {} + } + + return false; + }; + + await waitForStableUrl(page, 1200, 15000); + + const getViewport = async () => { + const vp = (page.viewport && page.viewport()) ? page.viewport() : null; + if (vp && vp.width && vp.height) return { width: vp.width, height: vp.height }; + const ev = await page.evaluate(() => ({ width: window.innerWidth, height: window.innerHeight })).catch(() => null); + return { width: ev?.width || 360, height: ev?.height || 800 }; + }; + + const tryOpenViaBottomRight = async (modalWaitMs = 9000) => { + const vp = await getViewport(); + const clamp = (v, min, max) => Math.max(min, Math.min(max, v)); + const maxX = Math.floor(vp.width - 2); + const maxY = Math.floor(vp.height - 2); + const marginX = 3 + Math.floor(Math.random() * 9); + const marginY = 1 + Math.floor(Math.random() * 6); + + const x = clamp(maxX - marginX, 1, maxX); + const y = clamp(maxY - marginY, 1, maxY); + + console.log(`[PDD] Trying to open options via bottom-right click (x=${x},y=${y})`); + return await tryClickAndWaitModal(x, y, modalWaitMs); + }; + + for (let attempt = 0; attempt < 5; attempt++) { + if (attempt > 0) await humanDelay(1400, 2600); + const ok = await tryOpenViaBottomRight(9000); + if (ok) return true; + } + + return false; + }; + + const clickO7pEFvHRAndWait = async (page, scopeSelectors = null) => { + const closeIfIwwPopupOpened = async () => { + const pt = await page.evaluate(() => { + const popup = document.querySelector('.iW4aEGbb'); + if (!popup) return null; + const close = + popup.querySelector('div[role="button"][aria-label*="关闭"]') || + popup.querySelector('button[aria-label*="关闭"]') || + popup.querySelector('div[role="button"][aria-label="关闭弹窗"]') || + popup.querySelector('div[role="button"][aria-label="关闭"]') || + popup.querySelector('button') || + null; + const el = close || popup; + const r = el.getBoundingClientRect(); + if (!r || r.width < 4 || r.height < 4) return { x: Math.floor(window.innerWidth / 2), y: Math.floor(window.innerHeight * 0.2) }; + const x = Math.floor(r.left + r.width * 0.5); + const y = Math.floor(r.top + r.height * 0.5); + return { x, y }; + }).catch(() => null); + + if (!pt?.x || !pt?.y) return false; + + try { + for (let i = 0; i < 2; i++) { + try { await page.mouse.move(Math.max(1, pt.x - 16), Math.max(1, pt.y - 16)); } catch (e) {} + await humanDelay(450, 900); + await page.mouse.click(pt.x, pt.y); + await humanDelay(650, 1200); + const still = await page.$('.iW4aEGbb').catch(() => null); + if (!still) return true; + } + } catch (e) {} + return false; + }; + + const clickNormalizedPoint = async (nx, ny) => { + const vp = (page.viewport && page.viewport()) ? page.viewport() : null; + const width = (vp && vp.width) ? vp.width : 360; + const height = (vp && vp.height) ? vp.height : 800; + const clamp = (v, min, max) => Math.max(min, Math.min(max, v)); + const x = clamp(Math.floor((Number(nx) / 1000) * width), 1, Math.floor(width - 2)); + const y = clamp(Math.floor((Number(ny) / 1000) * height), 1, Math.floor(height - 2)); + try { + try { await page.mouse.move(Math.max(1, x - 18), Math.max(1, y - 18)); } catch (e) {} + await humanDelay(650, 1200); + await page.mouse.click(x, y); + return true; + } catch (e) { + return false; + } + }; + + const clickCenterLeft = async () => { + const pt = await page.evaluate(() => { + const clamp = (v, min, max) => Math.max(min, Math.min(max, v)); + const modal = document.querySelector('.HidQ9ROd') || document.querySelector('div[role="dialog"][aria-modal="true"]') || document.querySelector('div[role="dialog"]'); + if (modal) { + const r = modal.getBoundingClientRect(); + if (r && r.width > 40 && r.height > 40) { + const x = clamp(Math.floor(r.left + r.width * 0.25), 1, Math.floor(window.innerWidth - 2)); + const y = clamp(Math.floor(r.top + r.height * 0.5), 1, Math.floor(window.innerHeight - 2)); + return { x, y }; + } + } + const x = clamp(Math.floor(window.innerWidth * 0.25), 1, Math.floor(window.innerWidth - 2)); + const y = clamp(Math.floor(window.innerHeight * 0.5), 1, Math.floor(window.innerHeight - 2)); + return { x, y }; + }).catch(() => null); + + if (!pt?.x || !pt?.y) return false; + try { + try { await page.mouse.move(Math.max(1, pt.x - 18), Math.max(1, pt.y - 18)); } catch (e) {} + await humanDelay(650, 1200); + await page.mouse.click(pt.x, pt.y); + return true; + } catch (e) { + return false; + } + }; + + const nudgeModalScroll = async () => { + if (!scopeSelectors) return; + const did = await page.evaluate(() => { + const modal = document.querySelector('.HidQ9ROd') || document.querySelector('div[role="dialog"][aria-modal="true"]') || document.querySelector('div[role="dialog"]'); + if (!modal) return false; + const all = [modal, ...Array.from(modal.querySelectorAll('*'))]; + const scroller = all.find(el => { + try { + return el.scrollHeight > el.clientHeight + 80; + } catch (e) { + return false; + } + }); + if (!scroller) return false; + const max = Math.max(0, scroller.scrollHeight - scroller.clientHeight); + if (max <= 0) return false; + const next = Math.min(max, scroller.scrollTop + Math.floor(scroller.clientHeight * 0.6)); + scroller.scrollTop = next; + return true; + }).catch(() => false); + if (did) await humanDelay(650, 1200); + }; + + const waitForOptionsList = async (timeoutMs = 6000) => { + const fast = await page.waitForSelector('li.TpUpcNRp, div._8gg8ho2u', { timeout: Math.min(2500, timeoutMs) }).catch(() => null); + if (fast) return true; + const ok = await page.waitForFunction(() => { + const modal = document.querySelector('.HidQ9ROd') || document.querySelector('div[role="dialog"][aria-modal="true"]') || document.querySelector('div[role="dialog"]'); + const root = modal || document; + const groupCount = root.querySelectorAll('.bIhLWVqm').length; + const optionCount = root.querySelectorAll('.bIhLWVqm .F7sZG3xe, .bIhLWVqm .s1O5M5fO .F7sZG3xe, .s1O5M5fO .F7sZG3xe').length; + if (groupCount > 0 && optionCount >= 2) return true; + const nodes = Array.from(root.querySelectorAll('li, div[role="button"], button, a')); + let count = 0; + for (const el of nodes) { + const t = String(el.innerText || el.textContent || '').replace(/\s+/g, ' ').trim(); + if (!t) continue; + if (!t.includes('¥') && !t.includes('¥')) continue; + const r = el.getBoundingClientRect(); + if (!r || r.width < 40 || r.height < 16 || r.height > 140) continue; + count++; + if (count >= 2) return true; + } + return false; + }, { timeout: timeoutMs }).catch(() => null); + return !!ok; + }; + + if (scopeSelectors) { + console.log('[PDD] Trying normalized click to open thumbnails/options (x=159,y=447)'); + const ok = await clickNormalizedPoint(159, 447); + if (ok) { + await closeIfIwwPopupOpened(); + await nudgeModalScroll(); + const hasAfter = await waitForOptionsList(7000); + if (hasAfter) { + console.log('[PDD] Options detected after normalized click'); + return true; + } + } + } + + const pickClickable = async (selector) => { + const handles = await page.$$(selector).catch(() => []); + for (const h of handles) { + const box = await h.boundingBox().catch(() => null); + if (!box) continue; + if (box.width < 3 || box.height < 3) continue; + return { handle: h, box }; + } + return null; + }; + + const clickByBox = async (box) => { + const x = Math.floor(box.x + box.width * 0.5); + const y = Math.floor(box.y + box.height * 0.5); + try { await page.mouse.move(Math.max(1, x - 18), Math.max(1, y - 18)); } catch (e) {} + await humanDelay(550, 1100); + await page.mouse.click(x, y); + }; + + const selectors = []; + if (!scopeSelectors) { + selectors.push('.O7pEFvHR', '.O7pEFvHR img'); + } else { + const scopes = Array.isArray(scopeSelectors) ? scopeSelectors : [scopeSelectors]; + for (const s of scopes) { + selectors.push(`${s} .O7pEFvHR`, `${s} .O7pEFvHR img`); + } + } + + console.log(`[PDD] Trying to click O7pEFvHR via ${selectors.length} selectors`); + let target = null; + let usedSelector = ''; + for (const sel of selectors) { + const picked = await pickClickable(sel); + if (picked) { + target = picked; + usedSelector = sel; + break; + } + } + + if (!target) { + if (!scopeSelectors) { + console.log('[PDD] O7pEFvHR not found/clickable (no modal scope); skipping heuristic click'); + return false; + } + + console.log('[PDD] O7pEFvHR not found/clickable; trying heuristic click inside SKU popup'); + + const scopes = scopeSelectors + ? (Array.isArray(scopeSelectors) ? scopeSelectors : [scopeSelectors]) + : []; + const pt = await page.evaluate((scopeSelList) => { + const clamp = (v, min, max) => Math.max(min, Math.min(max, v)); + const toPt = (r) => { + const x = clamp(Math.floor(r.left + r.width * 0.5), 1, Math.floor(window.innerWidth - 2)); + const y = clamp(Math.floor(r.top + r.height * 0.5), 1, Math.floor(window.innerHeight - 2)); + return { x, y }; + }; + + const visibleRect = (r) => { + if (!r || r.width < 12 || r.height < 12) return false; + if (r.bottom < 0 || r.right < 0) return false; + if (r.top > window.innerHeight || r.left > window.innerWidth) return false; + return true; + }; + + const isGoodSrc = (src) => { + const s = String(src || ''); + if (!s) return false; + if (!s.startsWith('http')) return false; + if (s.includes('avatar') || s.includes('icon') || s.includes('coupon')) return false; + return true; + }; + + const areas = []; + const roots = []; + if (scopeSelList && scopeSelList.length > 0) { + for (const sel of scopeSelList) { + const el = document.querySelector(sel); + if (el) roots.push(el); + } + } + if (roots.length === 0) roots.push(document); + + for (const root of roots) { + const imgs = Array.from(root.querySelectorAll('img')); + for (const img of imgs) { + if (img.closest && img.closest('.iW4aEGbb')) continue; + const r = img.getBoundingClientRect(); + if (!visibleRect(r)) continue; + if (!isGoodSrc(img.currentSrc || img.src)) continue; + const score = r.width * r.height; + areas.push({ score, rect: r }); + } + const divs = Array.from(root.querySelectorAll('div[role="button"], button')); + for (const el of divs) { + if (el.closest && el.closest('.iW4aEGbb')) continue; + const t = String(el.innerText || el.textContent || '').replace(/\s+/g, ' ').trim(); + if (!t) continue; + if (!t.includes('图') && !t.includes('图片')) continue; + const r = el.getBoundingClientRect(); + if (!visibleRect(r)) continue; + const score = r.width * r.height * 0.6; + areas.push({ score, rect: r }); + } + } + + areas.sort((a, b) => b.score - a.score); + const best = areas[0]; + if (!best) return null; + return toPt(best.rect); + }, scopes).catch(() => null); + + if (!pt?.x || !pt?.y) return false; + + try { + try { await page.mouse.move(Math.max(1, pt.x - 18), Math.max(1, pt.y - 18)); } catch (e) {} + await humanDelay(600, 1200); + await page.mouse.click(pt.x, pt.y); + console.log('[PDD] Heuristic click executed'); + await closeIfIwwPopupOpened(); + await nudgeModalScroll(); + } catch (e) { + return false; + } + } + + if (target) { + console.log(`[PDD] Clicking O7pEFvHR using: ${usedSelector}`); + try { + await page.evaluate((sel) => { + const el = document.querySelector(sel); + if (el && el.scrollIntoView) el.scrollIntoView({ block: 'center', inline: 'center' }); + }, usedSelector).catch(() => null); + await humanDelay(500, 900); + const pt = await page.evaluate((sel) => { + const el = document.querySelector(sel); + if (!el) return null; + const r = el.getBoundingClientRect(); + if (!r || r.width < 4 || r.height < 4) return null; + const clamp = (v, min, max) => Math.max(min, Math.min(max, v)); + const xs = [0.5, 0.35, 0.65, 0.2, 0.8].map(p => Math.floor(r.left + r.width * p)); + const ys = [0.5, 0.35, 0.65, 0.2, 0.8].map(p => Math.floor(r.top + r.height * p)); + for (const y of ys) { + for (const x of xs) { + const xx = clamp(x, 1, Math.floor(window.innerWidth - 2)); + const yy = clamp(y, 1, Math.floor(window.innerHeight - 2)); + const top = document.elementFromPoint(xx, yy); + if (top && (el === top || el.contains(top))) return { x: xx, y: yy }; + } + } + return null; + }, usedSelector).catch(() => null); + + if (pt?.x && pt?.y) { + try { await page.mouse.move(Math.max(1, pt.x - 18), Math.max(1, pt.y - 18)); } catch (e) {} + await humanDelay(550, 1100); + await page.mouse.click(pt.x, pt.y); + } else { + const refreshed = await pickClickable(usedSelector); + if (refreshed?.box) target = refreshed; + await clickByBox(target.box); + } + console.log('[PDD] Clicked O7pEFvHR'); + await closeIfIwwPopupOpened(); + await nudgeModalScroll(); + } catch (e) { + console.log(`[PDD] O7pEFvHR click failed: ${e?.message || e}`); + return false; + } + } + + const has = await waitForOptionsList(7000); + if (has) { + console.log('[PDD] Options list detected'); + return true; + } + + console.log('[PDD] Options list not detected; trying center-left click inside modal'); + try { + const ok = await clickCenterLeft(); + if (ok) { + await closeIfIwwPopupOpened(); + await nudgeModalScroll(); + const hasAfter = await waitForOptionsList(7000); + if (hasAfter) { + console.log('[PDD] Options list detected after center-left click'); + return true; + } + } + } catch (e) {} + + const fallbackCounts = await page.evaluate(() => { + const modal = document.querySelector('.HidQ9ROd') || document.querySelector('div[role="dialog"][aria-modal="true"]') || document.querySelector('div[role="dialog"]'); + const root = modal || document; + const li = root.querySelectorAll('li').length; + const buttons = root.querySelectorAll('button, div[role="button"]').length; + const groups = root.querySelectorAll('.bIhLWVqm').length; + const opts = root.querySelectorAll('.bIhLWVqm .F7sZG3xe, .s1O5M5fO .F7sZG3xe').length; + return { li, buttons, groups, opts }; + }).catch(() => ({ li: 0, buttons: 0 })); + console.log(`[PDD] Options list not detected (li=${fallbackCounts.li}, buttons=${fallbackCounts.buttons}, groups=${fallbackCounts.groups || 0}, opts=${fallbackCounts.opts || 0})`); + return false; + }; + + console.log('[PDD] Opening options popup before clicking O7pEFvHR'); + const optionsModalOpened = await openOptionsModalIfNeeded(newPage); + let hasOptionsList = false; + if (optionsModalOpened) { + hasOptionsList = await clickO7pEFvHRAndWait(newPage, [ + '.HidQ9ROd', + 'div[role="dialog"][aria-modal="true"]', + 'div[role="dialog"]' + ]); + } else { + console.log('[PDD] Could not open options modal'); + } + if (hasOptionsList) { + const liCount = await newPage.$$eval('li.TpUpcNRp', els => els.length).catch(() => 0); + const cardCount = await newPage.$$eval('div._8gg8ho2u', els => els.length).catch(() => 0); + console.log(`[PDD] Options elements found: li.TpUpcNRp=${liCount}, div._8gg8ho2u=${cardCount}`); + } else { + console.log('[PDD] Options list not found; continuing without selecting any options'); + } + + await waitForStableUrl(newPage, 1400, 15000); + + console.log('[Main] Starting main product data extraction (safeEvaluate)...'); + const data = await safeEvaluate(newPage, async () => { + const wait = (ms) => new Promise(r => setTimeout(r, ms)); + + // HELPER: Strict Price Extraction from User Target + const getTargetPrice = (root) => { + const r = (root && typeof root.querySelector === 'function') ? root : document; + const targetDiv = r.querySelector('.ujEqGzEB') || document.querySelector('.ujEqGzEB'); + if (targetDiv) { + // Try aria-label first (e.g. "首件¥29.88") + const imgSpan = targetDiv.querySelector('span[role="img"]'); + if (imgSpan && imgSpan.getAttribute('aria-label')) { + const label = imgSpan.getAttribute('aria-label'); + const match = label.match(/¥\s*(\d+(\.\d+)?)/); + if (match) return '¥' + match[1]; + } + // Fallback to text content + const text = targetDiv.innerText; + const match = text.match(/¥\s*(\d+(\.\d+)?)/); + if (match) return match[0]; + } + + const altPriceEl = + r.querySelector('div.kYzukoxf') || + r.querySelector('.Ngfn6pTR .kYzukoxf') || + document.querySelector('div.kYzukoxf') || + document.querySelector('.Ngfn6pTR .kYzukoxf'); + if (altPriceEl) { + const text = altPriceEl.innerText.replace(/\n/g, ' ').trim(); + const match = text.match(/¥\s*(\d+(\.\d+)?)/); + if (match) return match[0]; + } + + return null; + }; + + const waitForPriceAfterClick = async (prevPriceStr, root) => { + const start = Date.now(); + let last = null; + let stable = 0; + while (Date.now() - start < 7000) { + const cur = getTargetPrice(root); + if (cur) { + if (cur === last) stable++; + else { + last = cur; + stable = 0; + } + const changed = prevPriceStr ? (cur !== prevPriceStr) : true; + if (changed && stable >= 1) return cur; + if (!prevPriceStr && stable >= 1) return cur; + } + await wait(120); + } + return getTargetPrice(root) || last || null; + }; + + // 1. Title Extraction (User specific selector) + let title = ''; + const titleEl = document.querySelector('.tLYIg_Ju span') || + document.querySelector('.KlGVpw3u span') || + document.querySelector('.goods-name'); + if (titleEl) title = titleEl.innerText.trim(); + if (!title) title = document.title; + + // 2. Price Extraction (Initial fallback) + let price = getTargetPrice(document); + const priceEl = document.querySelector('.goods-price, [class*="price-info"], [class*="goods-price"]'); + if (!price && priceEl) { + price = priceEl.innerText.trim(); + } + if (!price) { + const bodyText = document.body.innerText; + const priceMatch = bodyText.match(/¥\s*(\d+(\.\d+)?)/); + if (priceMatch) price = priceMatch[0]; + } + + // 3. Description & Details + let description = ''; + let productDetails = {}; + + // Extract key-value details from .jvsKAdEs > .iUUH2sOQ + // Structure: .iUUH2sOQ -> .rMnkPxwx (Key) + .KjtdjVU2 (Value) + const detailItems = document.querySelectorAll('.iUUH2sOQ'); + detailItems.forEach(item => { + const key = item.querySelector('.rMnkPxwx')?.innerText.trim(); + const val = item.querySelector('.KjtdjVU2')?.innerText.trim(); + if (key && val) { + productDetails[key] = val; + description += `${key}: ${val}\n`; // Append to text description as well + } + }); + + // Fallback description if details are empty + if (!description) { + description = document.querySelector('.goods-details, [class*="detail-desc"]')?.innerText.trim() || ''; + } + + // 4. Variant & Price Extraction from Modal + let variants = {}; + let skuMap = {}; // Store price for each combination + let variantImages = {}; // Map color -> imageUrl + let skuThumbMap = {}; // Map optionKey -> imageUrl (per SKU or per single option) + let lowestVariantPrice = null; // Track lowest price found in variants + + try { + const extractOptionCardsFromRoot = () => { + const liEls = Array.from(document.querySelectorAll('li.TpUpcNRp')); + const containerEls = liEls.length > 0 + ? liEls.map(li => li.querySelector('div._8gg8ho2u') || li).filter(Boolean) + : Array.from(document.querySelectorAll('div._8gg8ho2u')); + const items = []; + const seen = new Set(); + + for (const c of containerEls) { + const nameEl = c?.querySelector?.('.RITrraU3 span.U63Kdv8C') || c?.querySelector?.('.RITrraU3 span') || c?.querySelector?.('span.U63Kdv8C'); + const textRaw = nameEl?.innerText || nameEl?.textContent || ''; + const text = String(textRaw || '').replace(/\s+/g, ' ').trim(); + + const priceEl = c?.querySelector?.('.nvN5jV0G') || c?.querySelector?.('[class*="nvN5jV0G"]'); + const priceRaw = priceEl?.innerText || priceEl?.textContent || ''; + const pm = String(priceRaw || '').match(/(\d+(\.\d+)?)/); + const priceStr = pm ? (`¥${pm[1]}`) : null; + + const imgEl = + c.querySelector('.PQoZYCec img') || + c.querySelector('.PQoZYCec img[data-src]') || + c.querySelector('.PQoZYCec img[data-lazy-src]') || + c.querySelector('.PQoZYCec img[data-original]') || + c.querySelector('img'); + const rawSrc = + imgEl?.getAttribute('src') || + imgEl?.getAttribute('data-src') || + imgEl?.getAttribute('data-lazy-src') || + imgEl?.getAttribute('data-original') || + imgEl?.src || + ''; + let thumb = rawSrc ? rawSrc.split('?')[0] : null; + if (!thumb) { + const pq = c.querySelector('.PQoZYCec') || c; + const styleBg = pq?.style?.backgroundImage || ''; + let bg = styleBg; + if (!bg) { + try { bg = window.getComputedStyle(pq).backgroundImage || ''; } catch (e) {} + } + const m = String(bg || '').match(/url\((['"]?)(.*?)\1\)/i); + const url = m?.[2] || ''; + thumb = url ? url.split('?')[0] : null; + } + + if (text && priceStr) { + const k = `${text}||${priceStr}||${thumb || ''}`; + if (seen.has(k)) continue; + seen.add(k); + items.push({ text, priceStr, thumb }); + } + } + + return items; + }; + + const cardsOnPage = extractOptionCardsFromRoot(); + if (cardsOnPage.length > 0) { + for (const card of cardsOnPage) { + skuMap[card.text] = card.priceStr; + if (card.thumb) skuThumbMap[card.text] = card.thumb; + } + } + + const modal = document.querySelector('.HidQ9ROd') || document.querySelector('div[role="dialog"][aria-modal="true"]') || document.querySelector('div[role="dialog"]'); + if (modal) { + const waitForOptionCards = async (timeoutMs = 2500) => { + const start = Date.now(); + while (Date.now() - start < timeoutMs) { + const hasLi = document.querySelectorAll('li.TpUpcNRp').length > 0; + const hasCards = document.querySelectorAll('div._8gg8ho2u').length > 0; + if (hasLi || hasCards) return true; + await wait(120); + } + return false; + }; + + const host = modal.querySelector('.O7pEFvHR'); + if (host) { + try { + host.scrollIntoView({ block: 'center', inline: 'center' }); + } catch (e) {} + try { + host.click(); + } catch (e) {} + await waitForOptionCards(3000); + const cardsAfterHostClick = extractOptionCardsFromRoot(); + if (cardsAfterHostClick.length > 0) { + for (const card of cardsAfterHostClick) { + skuMap[card.text] = card.priceStr; + if (card.thumb) skuThumbMap[card.text] = card.thumb; + } + } + } + + const getModalThumb = () => { + const img = modal.querySelector('.O7pEFvHR img'); + const raw = + img?.getAttribute?.('src') || + img?.getAttribute?.('data-src') || + img?.getAttribute?.('data-lazy-src') || + img?.currentSrc || + img?.src || + ''; + if (raw) return String(raw).split('?')[0]; + + const host = modal.querySelector('.O7pEFvHR'); + if (host) { + const styleBg = host.style?.backgroundImage || ''; + let bg = styleBg; + if (!bg) { + try { bg = window.getComputedStyle(host).backgroundImage || ''; } catch (e) {} + } + const m = String(bg || '').match(/url\((['"]?)(.*?)\1\)/i); + const url = m?.[2] || ''; + if (url) return url.split('?')[0]; + } + return null; + }; + + // Extract basic variants list first + const groups = Array.from(modal.querySelectorAll('.bIhLWVqm')); + let specKeys = []; + let specValues = []; + + groups.forEach(group => { + const keyEl = group.querySelector('.sku-specs-key'); + const valContainer = group.querySelector('.s1O5M5fO'); + + if (keyEl && valContainer) { + const key = keyEl.innerText.trim(); + const vals = Array.from(valContainer.querySelectorAll('.F7sZG3xe')) // Get the clickables + .map(el => ({ + text: el.querySelector('span.J109_25J')?.innerText.trim(), + element: el + })) + .filter(v => v.text); + variants[key] = vals.map(v => v.text); + specKeys.push(key); + specValues.push(vals); + } + }); + + if (specValues.length === 0) { + console.error('CRITICAL: Modal opened but no variants found. Structure might have changed.'); + } + + const isDisabledOption = (el) => { + if (!el) return true; + const ariaDisabled = el.getAttribute('aria-disabled'); + if (ariaDisabled && ariaDisabled.toLowerCase() === 'true') return true; + if (el.hasAttribute('disabled')) return true; + const cls = String(el.className || '').toLowerCase(); + if (cls.includes('disabled')) return true; + return false; + }; + + const getOptionText = (el) => { + return el?.querySelector('span.J109_25J')?.innerText.trim() || el?.innerText.trim() || ''; + }; + + const safeClick = async (el) => { + if (!el) return false; + try { el.scrollIntoView({ block: 'center', inline: 'center' }); } catch(e) {} + try { el.click(); return true; } catch(e) {} + try { + el.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window })); + return true; + } catch(e) {} + return false; + }; + + const getGroupOptions = (groupEl) => { + const valContainer = groupEl?.querySelector('.s1O5M5fO'); + if (!valContainer) return []; + return Array.from(valContainer.querySelectorAll('.F7sZG3xe')) + .map(el => ({ text: getOptionText(el), element: el })) + .filter(v => v.text && !isDisabledOption(v.element)); + }; + + const getGroup1 = () => Array.from(modal.querySelectorAll('.bIhLWVqm'))[0] || null; + const getGroup2 = () => Array.from(modal.querySelectorAll('.bIhLWVqm'))[1] || null; + + const isSelectedOption = (el) => { + if (!el) return false; + const clsRaw = String(el.className || ''); + const cls = clsRaw.toLowerCase(); + if (cls.includes('hr353bdx')) return true; + if (cls.includes('kv0lnch3')) return true; + const ariaChecked = el.getAttribute('aria-checked'); + if (ariaChecked && ariaChecked.toLowerCase() === 'true') return true; + const ariaSelected = el.getAttribute('aria-selected'); + if (ariaSelected && ariaSelected.toLowerCase() === 'true') return true; + const ariaPressed = el.getAttribute('aria-pressed'); + if (ariaPressed && ariaPressed.toLowerCase() === 'true') return true; + const dataState = el.getAttribute('data-state'); + if (dataState && (dataState === 'checked' || dataState === 'selected')) return true; + const dataSelected = el.getAttribute('data-selected'); + if (dataSelected && dataSelected.toLowerCase() === 'true') return true; + if (el.querySelector && el.querySelector('[aria-checked="true"], [aria-selected="true"]')) return true; + if (cls.includes('selected') || cls.includes('active') || cls.includes('checked') || cls.includes('current') || cls.includes('cur') || cls.includes('on')) return true; + return false; + }; + + const getGroupOptionElements = (groupEl) => { + const valContainer = groupEl?.querySelector('.s1O5M5fO'); + if (!valContainer) return []; + return Array.from(valContainer.querySelectorAll('.F7sZG3xe')) + .filter(el => !isDisabledOption(el) && !!getOptionText(el)); + }; + + const getOptionStyleKey = (el) => { + try { + const s = window.getComputedStyle(el); + const bg = s.backgroundColor || ''; + const border = s.borderColor || ''; + const color = s.color || ''; + const fw = s.fontWeight || ''; + const outline = s.outlineColor || ''; + return `${bg}|${border}|${color}|${fw}|${outline}`; + } catch (e) { + return ''; + } + }; + + const getSelectedOptionEl = (groupEl) => { + const optionEls = getGroupOptionElements(groupEl); + if (optionEls.length === 0) return null; + + const ariaSelectedEl = optionEls.find(isSelectedOption) || null; + if (ariaSelectedEl) return ariaSelectedEl; + + const keyCounts = new Map(); + for (const el of optionEls) { + const key = getOptionStyleKey(el); + keyCounts.set(key, (keyCounts.get(key) || 0) + 1); + } + + let bestEl = null; + let bestCount = Infinity; + for (const el of optionEls) { + const key = getOptionStyleKey(el); + const c = keyCounts.get(key) || 0; + if (c > 0 && c < bestCount) { + bestCount = c; + bestEl = el; + } + } + + if (bestEl && bestCount < optionEls.length) return bestEl; + return null; + }; + + const getSelectedOptionText = (groupEl) => { + const selectedEl = getSelectedOptionEl(groupEl); + return selectedEl ? getOptionText(selectedEl) : null; + }; + + const findOptionElByText = (groupEl, text) => { + if (!groupEl) return null; + const valContainer = groupEl.querySelector('.s1O5M5fO'); + if (!valContainer) return null; + const optionEls = Array.from(valContainer.querySelectorAll('.F7sZG3xe')); + for (const el of optionEls) { + if (isDisabledOption(el)) continue; + if (getOptionText(el) === text) return el; + } + return null; + }; + + const waitFor = async (predicate, timeoutMs = 2500, intervalMs = 120) => { + const start = Date.now(); + while (Date.now() - start < timeoutMs) { + try { + if (predicate()) return true; + } catch (e) {} + await wait(intervalMs); + } + return false; + }; + + const waitForStableTargetPrice = async (root, timeoutMs = 5000, intervalMs = 150, stableTicks = 2) => { + const start = Date.now(); + let last = null; + let stable = 0; + while (Date.now() - start < timeoutMs) { + const cur = getTargetPrice(root); + if (cur) { + if (cur === last) stable++; + else { + last = cur; + stable = 0; + } + if (stable >= stableTicks) return cur; + } + await wait(intervalMs); + } + return getTargetPrice(root) || last || null; + }; + + const waitForStableModalThumb = async (prevThumb, timeoutMs = 5000, intervalMs = 150, stableTicks = 2) => { + const start = Date.now(); + let last = getModalThumb(); + let stable = 0; + while (Date.now() - start < timeoutMs) { + const cur = getModalThumb(); + if (cur) { + if (cur !== last) { + last = cur; + stable = 0; + } else { + stable++; + } + if (prevThumb && cur !== prevThumb && stable >= stableTicks) return cur; + if (!prevThumb && stable >= stableTicks) return cur; + } + await wait(intervalMs); + } + return getModalThumb() || last || null; + }; + + const recordSku = (key, priceStr, thumb) => { + if (!key || !priceStr) return; + skuMap[key] = priceStr; + if (thumb) { + skuThumbMap[key] = thumb; + } + const pMatch = String(priceStr || '').match(/(\d+(\.\d+)?)/); + if (pMatch) { + const pVal = parseFloat(pMatch[1]); + if (Number.isFinite(pVal)) { + if (lowestVariantPrice === null || pVal < lowestVariantPrice) { + lowestVariantPrice = pVal; + price = `¥${pMatch[1]}`; + } + } + } + }; + + if (Object.keys(skuMap).length === 0 && Array.isArray(specValues) && specValues.length > 0) { + const startedAt = Date.now(); + const timeBudgetMs = 65000; + const group1 = specValues[0] || []; + const group2 = specValues[1] || []; + const group1Opts = group1.filter(v => v?.text && v?.element && !isDisabledOption(v.element)); + const group2Opts = group2.filter(v => v?.text && v?.element && !isDisabledOption(v.element)); + + if (group1Opts.length > 0 && group2Opts.length === 0) { + for (const o1 of group1Opts) { + if (Date.now() - startedAt > timeBudgetMs) break; + const prevPrice = getTargetPrice(document); + const prevThumb = getModalThumb(); + await safeClick(o1.element); + await wait(180); + const priceStr = await waitForPriceAfterClick(prevPrice, document); + const thumb = await waitForStableModalThumb(prevThumb, 4500, 160, 2); + if (thumb) variantImages[o1.text] = thumb; + recordSku(o1.text, priceStr || prevPrice || priceStr, thumb); + } + } else if (group1Opts.length > 0 && group2Opts.length > 0) { + for (const o1 of group1Opts) { + if (Date.now() - startedAt > timeBudgetMs) break; + const prevThumbColor = getModalThumb(); + await safeClick(o1.element); + await wait(220); + const colorThumb = await waitForStableModalThumb(prevThumbColor, 4500, 160, 2); + if (colorThumb) variantImages[o1.text] = colorThumb; + + for (const o2 of group2Opts) { + if (Date.now() - startedAt > timeBudgetMs) break; + const prevPrice = getTargetPrice(document); + const prevThumb = getModalThumb(); + await safeClick(o2.element); + await wait(200); + const priceStr = await waitForPriceAfterClick(prevPrice, document); + const thumb = await waitForStableModalThumb(prevThumb, 4500, 160, 2); + const key = `${o1.text}__SEP__${o2.text}`; + recordSku(key, priceStr || prevPrice || priceStr, thumb || colorThumb); + } + } + } + } + + const extractCardTextPrice = (c) => { + const nameEl = c?.querySelector?.('.RITrraU3 span.U63Kdv8C') || c?.querySelector?.('.RITrraU3 span') || c?.querySelector?.('span.U63Kdv8C'); + let textRaw = nameEl?.innerText || nameEl?.textContent || ''; + let text = String(textRaw || '').replace(/\s+/g, ' ').trim(); + if (!text) { + const spans = Array.from(c?.querySelectorAll?.('span') || []); + for (const s of spans) { + const t = String(s?.innerText || s?.textContent || '').replace(/\s+/g, ' ').trim(); + if (!t) continue; + if (t.includes('¥') || t.includes('¥')) continue; + if (t.includes('已选') || t.includes('请选择')) continue; + if (t.length > 80) continue; + text = t; + break; + } + } + + const priceEl = c?.querySelector?.('.nvN5jV0G') || c?.querySelector?.('[class*="nvN5jV0G"]'); + let priceRaw = priceEl?.innerText || priceEl?.textContent || ''; + if (!priceRaw) { + const t = String(c?.innerText || c?.textContent || ''); + const m = t.match(/[¥¥]\s*(\d+(\.\d+)?)/); + if (m) priceRaw = m[0]; + } + const pm = String(priceRaw || '').match(/(\d+(\.\d+)?)/); + const priceStr = pm ? (`¥${pm[1]}`) : null; + + return { text, priceStr }; + }; + + const extractCardThumb = (c) => { + const imgEl = c.querySelector('.PQoZYCec img') || c.querySelector('.PQoZYCec img[data-src]') || c.querySelector('.PQoZYCec img[data-lazy-src]') || c.querySelector('.PQoZYCec img[data-original]') || c.querySelector('img'); + const rawSrc = + imgEl?.getAttribute('src') || + imgEl?.getAttribute('data-src') || + imgEl?.getAttribute('data-lazy-src') || + imgEl?.getAttribute('data-original') || + imgEl?.src || + ''; + if (rawSrc) return rawSrc.split('?')[0]; + + const pq = c.querySelector('.PQoZYCec') || c; + const styleBg = pq?.style?.backgroundImage || ''; + let bg = styleBg; + if (!bg) { + try { bg = window.getComputedStyle(pq).backgroundImage || ''; } catch (e) {} + } + const m = String(bg || '').match(/url\((['"]?)(.*?)\1\)/i); + const url = m?.[2] || ''; + return url ? url.split('?')[0] : null; + }; + + const scanThumbsViaO7pEFvHR = async (group1Texts, group2Texts, maxSwipes = 28) => { + const out = {}; + const seenKeys = new Set(); + const host = modal.querySelector('.O7pEFvHR') || modal.querySelector('.O7pEFvHR img'); + if (!host) return out; + + const getSelectedSummaryText = () => { + const el = modal.querySelector('.xJDS9NLo .Mbx2m60G') || modal.querySelector('.Mbx2m60G'); + const t = el?.innerText || el?.textContent || ''; + return String(t || '').replace(/\s+/g, ' ').trim(); + }; + + const normalizeSelectedSummary = (t) => { + return String(t || '').replace(/^已选\s*[::]\s*/g, '').trim(); + }; + + const pickComboKey = (summary) => { + const s = String(summary || ''); + const v1 = (group1Texts || []).find(t => t && s.includes(t)) || null; + const v2 = (group2Texts || []).find(t => t && s.includes(t)) || null; + if (v1 && v2) return `${v1}__SEP__${v2}`; + return summary || null; + }; + + const swipeLeft = async () => { + try { + const r = host.getBoundingClientRect(); + const startX = Math.floor(r.left + r.width * 0.78); + const endX = Math.floor(r.left + r.width * 0.22); + const y = Math.floor(r.top + r.height * 0.5); + const touchStart = new Touch({ identifier: Date.now(), target: host, clientX: startX, clientY: y }); + const touchEnd = new Touch({ identifier: Date.now(), target: host, clientX: endX, clientY: y }); + host.dispatchEvent(new TouchEvent('touchstart', { touches: [touchStart], bubbles: true })); + host.dispatchEvent(new TouchEvent('touchmove', { touches: [touchEnd], bubbles: true })); + host.dispatchEvent(new TouchEvent('touchend', { changedTouches: [touchEnd], bubbles: true })); + await wait(380); + return true; + } catch (e) { + try { + const r = host.getBoundingClientRect(); + const startX = Math.floor(r.left + r.width * 0.78); + const endX = Math.floor(r.left + r.width * 0.22); + const y = Math.floor(r.top + r.height * 0.5); + host.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, cancelable: true, clientX: startX, clientY: y })); + host.dispatchEvent(new MouseEvent('mousemove', { bubbles: true, cancelable: true, clientX: endX, clientY: y })); + host.dispatchEvent(new MouseEvent('mouseup', { bubbles: true, cancelable: true, clientX: endX, clientY: y })); + await wait(380); + return true; + } catch (e2) {} + } + return false; + }; + + let stagnation = 0; + let lastKey = null; + for (let i = 0; i < maxSwipes; i++) { + const summary = normalizeSelectedSummary(getSelectedSummaryText()); + const key = pickComboKey(summary); + const thumb = getModalThumb(); + if (key && thumb) out[key] = thumb; + + if (key && key === lastKey) stagnation++; + else stagnation = 0; + lastKey = key || lastKey; + + if (key) seenKeys.add(key); + if (seenKeys.size >= 6 && stagnation >= 2) break; + + const didSwipe = await swipeLeft(); + if (!didSwipe) break; + } + + return out; + }; + + const extractOptionCards = (root) => { + const scope = (root || document); + const liEls = Array.from(scope.querySelectorAll('li.TpUpcNRp')); + const containerEls = liEls.length > 0 + ? liEls.map(li => li.querySelector('div._8gg8ho2u')).filter(Boolean) + : Array.from(scope.querySelectorAll('div._8gg8ho2u')); + const items = []; + const seen = new Set(); + const addFromContainer = (c) => { + const thumb = extractCardThumb(c); + const { text, priceStr } = extractCardTextPrice(c); + + if (text && priceStr) { + const k = `${text}||${priceStr}||${thumb || ''}`; + if (seen.has(k)) return; + seen.add(k); + items.push({ text, priceStr, thumb }); + } + }; + + for (const c of containerEls) addFromContainer(c); + + if (items.length === 0) { + const priceEls = Array.from(scope.querySelectorAll('.nvN5jV0G, [class*="nvN5jV0G"]')); + const candidates = []; + const uniq = new Set(); + for (const p of priceEls) { + const t = String(p?.innerText || p?.textContent || '').replace(/\s+/g, ' ').trim(); + if (!t || (!t.includes('¥') && !t.includes('¥'))) continue; + const c = p.closest('li') || p.closest('div') || p.parentElement; + if (!c) continue; + const key = c === scope ? null : (c.getAttribute?.('class') || '') + '::' + (c.innerText || '').slice(0, 60); + if (key && uniq.has(key)) continue; + if (key) uniq.add(key); + candidates.push(c); + if (candidates.length >= 40) break; + } + for (const c of candidates) addFromContainer(c); + } + + return items; + }; + + const cards = extractOptionCards(modal); + if (cards.length > 0) { + for (const card of cards) { + skuMap[card.text] = card.priceStr; + if (card.thumb) skuThumbMap[card.text] = card.thumb; + + const pMatch = card.priceStr.match(/(\d+(\.\d+)?)/); + if (pMatch) { + const pVal = parseFloat(pMatch[1]); + if (lowestVariantPrice === null || pVal < lowestVariantPrice) { + lowestVariantPrice = pVal; + price = card.priceStr; + } + } + } + } + } + } catch (e) { + console.log('Variant extraction failed:', e.message); + } + + // 5. Image Extraction with Slider Logic + let images = []; + + // Helper to capture current visible images + const captureImages = () => { + // STRICT SLIDER SELECTOR: Only target images within the known slider container classes + // .goods-slider, .swiper-slide, or specific top containers + // We avoid #main > div img as it is too broad and catches header icons/text + const sliderSelectors = [ + '.goods-slider img', + '.swiper-slide img', + '.swiper-container img', + '.banner-slider img', + '#main > div > div:first-child img', // Often the first div is the slider + '.slick-slide img' + ]; + + const imgs = document.querySelectorAll(sliderSelectors.join(', ')); + + imgs.forEach(img => { + if (img.src && img.src.startsWith('http') && img.naturalWidth > 400) { + // Clean the URL + let cleanSrc = img.src.split('?')[0]; + + // Filter out video snapshots, avatars, icons, and coupons + if (cleanSrc.includes('video-snapshot') || + cleanSrc.includes('avatar') || + cleanSrc.includes('icon') || + cleanSrc.includes('coupon') || + cleanSrc.includes('.slim.png')) return; + + // ASPECT RATIO CHECK: Exclude wide banners or tiny strips + // Product images are usually 1:1 or 3:4. + // Banners are usually > 2:1. + if (img.naturalHeight > 0) { + const aspect = img.naturalWidth / img.naturalHeight; + if (aspect > 2.2 || aspect < 0.4) { + // console.log(`Skipping image due to aspect ratio ${aspect.toFixed(2)}: ${cleanSrc}`); + return; + } + } + + images.push(cleanSrc); + } + }); + + // FALLBACK: If strict slider extraction failed (empty), try slightly broader but still top-area + if (images.length === 0) { + // Get images from the top 50% of the page only + const allImgs = document.querySelectorAll('img'); + allImgs.forEach(img => { + const rect = img.getBoundingClientRect(); + if (rect.top < window.innerHeight * 0.6 && img.naturalWidth > 400) { + let cleanSrc = img.src.split('?')[0]; + if (cleanSrc.startsWith('http') && + !cleanSrc.includes('avatar') && + !cleanSrc.includes('icon') && + !cleanSrc.includes('coupon')) { + + // Aspect Ratio Check for Fallback too + if (img.naturalHeight > 0) { + const aspect = img.naturalWidth / img.naturalHeight; + if (aspect > 2.2 || aspect < 0.4) return; + } + + images.push(cleanSrc); + } + } + }); + } + }; + + // Initial capture + captureImages(); + + // Attempt to slide right (swipe left gesture) to reveal more images + const sliderContainer = document.querySelector('#main > div') || document.body; + + if (sliderContainer) { + for (let i = 0; i < 5; i++) { // Swipe 5 times + try { + // Simulate touch swipe left SAFE + // Some environments (Headless) might not support Touch constructor directly or it behaves oddly + // Use a simpler dispatch if possible, or wrap in try/catch + if (typeof Touch !== 'undefined' && typeof TouchEvent !== 'undefined') { + const touchStart = new Touch({ identifier: Date.now(), target: sliderContainer, clientX: 300, clientY: 200 }); + const touchEnd = new Touch({ identifier: Date.now(), target: sliderContainer, clientX: 50, clientY: 200 }); + + sliderContainer.dispatchEvent(new TouchEvent('touchstart', { touches: [touchStart], bubbles: true })); + sliderContainer.dispatchEvent(new TouchEvent('touchmove', { touches: [touchEnd], bubbles: true })); + sliderContainer.dispatchEvent(new TouchEvent('touchend', { changedTouches: [touchEnd], bubbles: true })); + } + } catch (e) { + // console.log('Swipe simulation failed (non-fatal):', e.message); + } + + await wait(800); // Wait for animation + captureImages(); + } + } + + // --- MAIN IMAGE FIX: Prioritize Images from Specific Picture Div --- + // User Request: "set the first main img is the imgs shows in that the picture div" + // This usually refers to the main gallery or a specific container that holds the high-res images + + // 1. Try to find the specific "Picture Div" (often .goods-slider or .slick-slider) + // If we found images in the slider, we should prioritize them. + // The `images` array already collects them, but let's make sure they are unique and ordered correctly. + + images = [...new Set(images)]; // Deduplicate first + + // If we have slider images, they are already at the top. + // But if the user meant the "Details" images (which are sometimes high res), we should be careful. + // Usually "Main Image" is the first one in the slider. + + // Let's verify if there's a specific container the user might be referring to. + // Often in Pinduoduo mobile, the main image is in a swiper at the top. + // We already target that. + + // However, sometimes "other pictures" (like description images) get mixed in if we use broad selectors. + // Our `captureImages` is already quite strict. + + // Let's double check if we can be even stricter for the FIRST image. + // Look for the absolute first image in the slider container + let firstSliderImg = document.querySelector('.goods-slider img') || + document.querySelector('.swiper-slide-active img') || + document.querySelector('.slick-current img') || + document.querySelector('#main > div > div:first-child img'); + + // Validation: If first image is a banner (wide), ignore it + if (firstSliderImg) { + if (firstSliderImg.naturalHeight > 0) { + const aspect = firstSliderImg.naturalWidth / firstSliderImg.naturalHeight; + if (aspect > 2.0 || aspect < 0.5) { + // console.log('First slider image rejected due to aspect ratio:', aspect); + firstSliderImg = null; + } + } + } + + // Fallback: If no slider image found, find the largest image in the top 500px + if (!firstSliderImg) { + const allImgs = Array.from(document.querySelectorAll('img')); + let maxArea = 0; + let bestImg = null; + + allImgs.forEach(img => { + const rect = img.getBoundingClientRect(); + if (rect.top < 600 && rect.height > 100 && rect.width > 100) { + const area = rect.width * rect.height; + const aspect = rect.width / rect.height; + + // Only consider reasonable aspect ratios + if (aspect > 0.5 && aspect < 2.0) { + if (area > maxArea) { + maxArea = area; + bestImg = img; + } + } + } + }); + if (bestImg) firstSliderImg = bestImg; + } + + if (firstSliderImg && firstSliderImg.src) { + const mainSrc = firstSliderImg.src.split('?')[0]; + // Move this image to the front of the array if it exists + images = images.filter(img => img !== mainSrc); + images.unshift(mainSrc); + } else if (images.length > 0) { + // If we couldn't pinpoint the slider element but captured images, + // ensure the first one in the captured list stays first. + // (Already handled by array order, but good to be explicit) + } + + + // 6. Description Images Extraction + let product_desc_imgs = []; + + console.log('Starting description image extraction sequence...'); + await wait(5000); + try { + for (let i = 0; i < 2; i++) { + const x = Math.floor(window.innerWidth / 2); + const y = 12; + const el = document.elementFromPoint(x, y); + if (el) el.click(); + await wait(220); + } + const backBtn = document.querySelector('div[role="button"][aria-label*="返回"]') || + document.querySelector('div[role="button"][aria-label*="后退"]') || + document.querySelector('div[role="button"][aria-label*="关闭"]'); + if (backBtn) { + backBtn.click(); + await wait(600); + } + } catch (e) {} + await wait(5000); + + // Step A: Close the variant modal explicitly + try { + // User mentioned: "hit the exit button" (likely the X button) + // Selector hints: div[role="button"][aria-label="关闭弹窗"] OR .pD0kR4N1 + const closeBtn = document.querySelector('div[role="button"][aria-label="关闭弹窗"]') || + document.querySelector('.pD0kR4N1') || + document.querySelector('div[role="button"] .pD0kR4N1')?.parentElement; + + if (closeBtn) { + // console.log('Closing variant modal...'); + closeBtn.click(); + await wait(1000); + } else { + // Try clicking the overlay/mask + const mask = document.querySelector('.ReactModal__Overlay, [class*="overlay"], [class*="mask"]'); + if (mask) { + mask.click(); + await wait(1000); + } + } + } catch(e) { + // console.log('Error closing modal:', e.message); + } + + // STOPPING ACTIONS AS REQUESTED + console.log('[Reviews] Stopping all previous actions and stabilizing page before review scraping...'); + // User requested 5 seconds wait after options closed + await wait(5000); + + // Review Scraping Logic (User Request) + let reviews = []; + try { + console.log(`[Reviews] Enriching: 商品评价...`); + console.log(`[Reviews] Checking for reviews (商品评价) at ${new Date().toISOString()}...`); + + // Optimization: Use XPath to find the button efficiently without triggering reflows on all elements + let reviewBtn = null; + try { + console.log('[Reviews] executing XPath search for review button...'); + const xpath = "//*[contains(text(), '商品评价')]"; + const result = document.evaluate(xpath, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); + console.log(`[Reviews] XPath found ${result.snapshotLength} candidate elements.`); + + for (let i = 0; i < result.snapshotLength; i++) { + const el = result.snapshotItem(i); + // Check if it's a button-like element (short text) + if (el.textContent && el.textContent.length < 20) { + // Double check visibility/text + if (el.innerText && el.innerText.includes('商品评价')) { + reviewBtn = el; + console.log(`[Reviews] XPath candidate ${i} accepted: ${el.tagName} (Text: ${el.innerText})`); + break; + } + } + } + } catch(e) { console.log('[Reviews] XPath search failed, falling back...', e.message); } + + // Fallback if XPath failed + if (!reviewBtn) { + console.log('[Reviews] XPath failed or returned nothing. Starting DOM scan fallback...'); + const allElements = Array.from(document.querySelectorAll('div, span, p')); + reviewBtn = allElements.find(el => el.innerText && el.innerText.includes('商品评价') && el.innerText.length < 20); + if (reviewBtn) console.log(`[Reviews] DOM scan found button: ${reviewBtn.tagName}`); + } + + if (reviewBtn) { + console.log(`[Reviews] Found review button, preparing to click at ${new Date().toISOString()}...`); + + // Get count BEFORE clicking to avoid stale element issues + let reviewCount = 0; + const countMatch = reviewBtn.innerText.match(/(\d+)/); + if (countMatch) reviewCount = parseInt(countMatch[1]); + + reviewBtn.click(); + console.log(`[Reviews] Clicked button at ${new Date().toISOString()}. Waiting for 5 seconds load...`); + + // Wait in chunks to show progress - EXACTLY 5 SECONDS + for (let w = 0; w < 10; w++) { + await wait(500); + if (w % 2 === 0) console.log(`[Reviews] Waiting... ${(w+1)*0.5}s`); + } + console.log(`[Reviews] Wait finished at ${new Date().toISOString()}. Checking scroll need...`); + + // "if the comments are less like 5 reviews you don't need to force going down 4 screens." + const shouldScroll = reviewCount === 0 || reviewCount > 5; + + if (shouldScroll) { + console.log(`[Reviews] Starting scroll sequence (Count: ${reviewCount}) at ${new Date().toISOString()}...`); + for (let i = 0; i < 4; i++) { + console.log(`[Reviews] Scrolling screen ${i + 1}/4 at ${new Date().toISOString()}...`); + window.scrollBy(0, window.innerHeight); + await wait(800 + Math.random() * 400); // 0.8s - 1.2s + } + console.log(`[Reviews] Finished scrolling at ${new Date().toISOString()}.`); + } else { + console.log(`[Reviews] Skipping deep scroll (Count: ${reviewCount})`); + await wait(1000); + } + + // Extract Review Images & Content + // Strategy: Group elements by class name to find review items + console.log(`[Reviews] Starting data extraction at ${new Date().toISOString()}...`); + const divs = Array.from(document.querySelectorAll('div')); + const classCounts = {}; + divs.forEach(d => { + if (d.className && typeof d.className === 'string') { + const c = d.className; + if (!classCounts[c]) classCounts[c] = []; + classCounts[c].push(d); + } + }); + + let bestClass = null; + let maxCount = 0; + + // Find the class that represents review items + // Criteria: > 2 items, contains text, contains images (optional but preferred for photo reviews) + for (const [cls, items] of Object.entries(classCounts)) { + if (items.length > 1) { + const first = items[0]; + const text = first.innerText.trim(); + const imgs = first.querySelectorAll('img'); + const hasValidImg = Array.from(imgs).some(img => img.naturalWidth > 50 && !img.src.includes('avatar')); + + if (text.length > 5 && hasValidImg) { + if (items.length > maxCount) { + maxCount = items.length; + bestClass = cls; + } + } + } + } + + if (bestClass) { + console.log(`[Reviews] Found review items with class: ${bestClass} (Count: ${maxCount})`); + const items = classCounts[bestClass]; + items.forEach(item => { + const text = item.innerText.trim(); + const imgs = Array.from(item.querySelectorAll('img')) + .filter(img => img.naturalWidth > 50 && !img.src.includes('avatar') && !img.src.includes('icon')) + .map(img => img.src.split('?')[0]); + + if (text && imgs.length > 0) { + const lines = text.split('\n').map(l => l.trim()).filter(l => l); + // Heuristic: Name is usually short and at the top. Comment is longer. + let name = 'Pinduoduo Shopper'; + let comment = text; + + if (lines.length > 1 && lines[0].length < 20) { + name = lines[0]; + comment = lines.slice(1).join(' '); + } + + reviews.push({ name, comment, photos: [...new Set(imgs)] }); + } + }); + } else { + console.log('[Reviews] Could not detect review structure by class. Using fallback image extraction.'); + // Fallback: Extract all images and create generic reviews + const visibleImgs = Array.from(document.querySelectorAll('img')) + .filter(img => img.naturalWidth > 100 && !img.src.includes('avatar') && !img.src.includes('icon')) + .map(img => img.src.split('?')[0]); + + const uniqueImgs = [...new Set(visibleImgs)]; + console.log(`[Reviews] Fallback found ${uniqueImgs.length} images.`); + + // Group images into chunks of 3 to create fake "reviews" + for (let i = 0; i < uniqueImgs.length; i += 3) { + const chunk = uniqueImgs.slice(i, i + 3); + reviews.push({ + name: 'Pinduoduo Shopper', + comment: 'صور من تقييمات العملاء', + photos: chunk + }); + } + } + + console.log(`[Reviews] Extracted ${reviews.length} reviews.`); + + // Go Back + console.log(`[Reviews] Going back to product page at ${new Date().toISOString()}...`); + const backBtn = document.querySelector('div[role="button"][aria-label*="返回"]') || + document.querySelector('div[role="button"][aria-label*="后退"]') || + document.querySelector('.pdd-go-back') || + document.querySelector('[data-testid="back-button"]'); + + if (backBtn) { + backBtn.click(); + } else { + console.log('[Reviews] No back button found, using history.back()'); + window.history.back(); + } + await wait(2000); // Wait for product page to restore + console.log('[Main] Back on product page. Starting description scroll...'); + } else { + console.log('No review button found, skipping reviews.'); + } + } catch (e) { + console.log(`[Reviews] Error scraping reviews: ${e.message} at ${new Date().toISOString()}`); + } + + // Step B: Slow Scroll to trigger lazy loading (Anti-detection & Image Loading) + // User: "first you have to slowly scroll down so it won't be detected" + console.log('[Main] Starting description scroll sequence...'); + const moreProductsDiv = document.querySelector('.mP10ZXCw'); + + // Calculate target position (either more products div or bottom of body) + const targetTop = moreProductsDiv ? moreProductsDiv.getBoundingClientRect().top + window.scrollY : document.body.scrollHeight; + const startScroll = window.scrollY; + const distance = targetTop - startScroll; + const steps = 30; // Number of steps + const stepSize = distance / steps; + + // Perform slow scroll + for (let i = 0; i < steps; i++) { + window.scrollBy(0, stepSize); + // Random wait between 100ms and 300ms + await wait(100 + Math.random() * 200); + } + await wait(2000); // Final wait for images to render + + // Step C: Extract images STRICTLY from specific nested path + // Priority 1: User-identified container "Blmqu2TV" + const blmContainer = document.querySelector('.Blmqu2TV') || document.querySelector('div[class*="Blmqu2TV"]'); + let foundDescImages = false; + + if (blmContainer) { + console.log('[PDD] Found Blmqu2TV container for description images'); + const imgs = Array.from(blmContainer.querySelectorAll('img')); + + imgs.forEach(img => { + // STRICT EXCLUSION + if (img.closest('a[href*="goods_id"]')) return; + if (img.closest('.recommend-goods')) return; + + // User provided example: data-src is primary + let src = img.getAttribute('data-src') || img.getAttribute('src') || img.src; + + if (src && !src.startsWith('data:')) { + src = src.split('?')[0]; + if (src.startsWith('//')) src = 'https:' + src; + + if (src.startsWith('http') && !src.includes('avatar') && !src.includes('icon') && !src.includes('video-snapshot') && !src.includes('coupon') && !src.includes('.slim.png')) { + // Optional: Check for size if possible, but data-src usually implies main content + product_desc_imgs.push(src); + } + } + }); + + if (product_desc_imgs.length > 0) foundDescImages = true; + } + + // Priority 2: Old strict selector if Blmqu2TV failed + if (!foundDescImages) { + // User hint: #main > div > div.GNrMaxlJ > div:nth-child(19) > div + const descContainer = document.querySelector('#main > div > div.GNrMaxlJ > div:nth-child(19) > div'); + + if (descContainer) { + // console.log('Found description container, extracting nested images...'); + // Re-query children after scroll + const nestedDivs = Array.from(descContainer.querySelectorAll('div')); + + // If we fell back to main container, just get all images directly too + const directImages = Array.from(descContainer.querySelectorAll('img')); + + const processImg = (img) => { + let src = img.src || img.dataset.src; + if (src && !src.startsWith('data:') && img.naturalWidth > 400) { + // Check for lazy loaded attributes often used in PDD + if (src.includes('blank.gif') || src.includes('loading')) { + if (img.dataset.src) src = img.dataset.src; + } + + // STRICT EXCLUSION: Suggested/Recommended Products + // If the image is inside a link to another product, skip it + if (img.closest('a[href*="goods_id"]')) return; + if (img.closest('.recommend-goods')) return; + + if (src && !src.includes('avatar') && !src.includes('icon') && !src.includes('video-snapshot') && !src.includes('coupon') && !src.includes('.slim.png')) { + product_desc_imgs.push(src.split('?')[0]); + } + } + }; + + nestedDivs.forEach(div => { + const imgs = div.querySelectorAll('img'); + imgs.forEach(processImg); + }); + + directImages.forEach(processImg); + if (product_desc_imgs.length > 0) foundDescImages = true; + } + } + + if (!foundDescImages) { + // STRICT FALLBACK: If specific container not found, try to find the "Details" section specifically + // Pinduoduo usually has a "Goods Details" or "Graphic Details" header + // We look for a container that has many large images and is NOT the slider + console.log('Specific container not found, attempting strict fallback...'); + const potentialContainers = Array.from(document.querySelectorAll('.GNrMaxlJ > div')); + // Usually the description is near the bottom, often the last or second to last div + // We can also look for a div that contains mostly images + + for (const div of potentialContainers) { + const imgs = div.querySelectorAll('img'); + if (imgs.length > 2) { + // Check if images are large + let largeImgs = 0; + imgs.forEach(img => { if (img.naturalWidth > 400) largeImgs++; }); + if (largeImgs > 2) { + imgs.forEach(img => { + if (img.naturalWidth > 400) { + let src = img.src || img.dataset.src; + if (src && !src.includes('avatar') && !src.includes('icon') && !src.includes('video-snapshot') && !src.includes('coupon')) { + product_desc_imgs.push(src.split('?')[0]); + } + } + }); + break; // Found one good container, stop + } + } + } + } + + return { title, price, description, images: [...new Set(images)], variants, skuMap, skuThumbMap, productDetails, product_desc_imgs: [...new Set(product_desc_imgs)], variantImages, reviews }; + }, [], 12); + + // Enrich + console.log(`Enriching: ${data.title.substring(0, 20)}...`); + + let general_price = 0; + if (data.price) { + const match = data.price.match(/(\d+(\.\d+)?)/); + if (match) general_price = parseFloat(match[1]) * 200; + } + + // --- EDIBLE CHECK (KEYWORD PRE-FILTER) --- + const preCheck = isEdiblePreCheck(data.title, data.description); + if (preCheck.isEdible) { + console.log(`Skipping product (EDIBLE KEYWORD DETECTED: ${preCheck.keyword}): ${data.title.substring(0, 30)}...`); + if (!navigationHappened) await newPage.close(); + else await newPage.goBack(); + continue; + } + + const aiData = await enrichWithAI(data.title, data.description, data.price); + + // CHECK: Did AI fail completely? + if (aiData.shouldSkip) { + console.error(`Skipping product due to AI translation failure: ${aiData.reason}`); + if (!navigationHappened) await newPage.close(); + else await newPage.goBack(); + continue; + } + + // CHECK: Is it edible (AI Detection)? + if (aiData.is_edible) { + console.log(`Skipping product (AI DETECTED EDIBLE): ${data.title.substring(0, 30)}...`); + if (!navigationHappened) await newPage.close(); + else await newPage.goBack(); + continue; + } + + // --- GENERATE OPTIONS FROM SKU MAP (WITH TRANSLATION) --- + let generated_options = []; + const variantImages = data.variantImages || {}; + const skuThumbMap = data.skuThumbMap || {}; + + if (data.skuMap && Object.keys(data.skuMap).length > 0) { + const rawVariantEntries = Object.entries(data.skuMap || {}); + console.log(`Variant prices BEFORE translation (${rawVariantEntries.length})`); + const rawPreviewLimit = 80; + rawVariantEntries.slice(0, rawPreviewLimit).forEach(([k, v]) => { + const m = String(v || '').match(/(\d+(\.\d+)?)/); + const p = m ? Math.round(parseFloat(m[1]) * 200) : 0; + console.log(` ${k} => ${v} (${p} IQD)`); + }); + if (rawVariantEntries.length > rawPreviewLimit) { + console.log(` ... truncated ${rawVariantEntries.length - rawPreviewLimit} more`); + } + + // Helper to translate color/size via AI if possible, or simple mapping + // Since we want strict Arabic, we might need a quick AI pass or just use the aiData logic + // For now, let's process the structure first, then maybe translate the labels + + const resolveThumbnail = (optionKey, colorStr) => { + if (optionKey && skuThumbMap[optionKey]) return skuThumbMap[optionKey]; + if (!colorStr) return null; + if (variantImages[colorStr]) return variantImages[colorStr]; + const keys = Object.keys(variantImages || {}); + const matchingKey = keys.find(k => k && (k.includes(colorStr) || colorStr.includes(k))); + return matchingKey ? variantImages[matchingKey] : null; + }; + + for (const [key, priceStr] of rawVariantEntries) { + let color = key; + let size = null; + + if (key.includes('__SEP__')) { + const parts = key.split('__SEP__'); + color = parts[0]; + size = parts[1]; + } + + let priceVal = 0; + const match = String(priceStr || '').match(/(\d+(\.\d+)?)/); + if (match) priceVal = parseFloat(match[1]) * 200; + + color = String(color || '') + .replace(/\n.*$/, '') + .replace(/【.*?】/g, '') + .replace(/\s+/g, ' ') + .trim(); + + if (size) { + size = String(size || ''); + size = size.replace(/(\d+(\.\d+)?)\s*[-~]\s*(\d+(\.\d+)?)\s*斤/g, (m, p1, p2, p3) => { + const start = parseFloat(p1) / 2; + const end = parseFloat(p3) / 2; + return `${start}-${end}kg`; + }); + size = size.replace(/(\d+(\.\d+)?)\s*斤/g, (m, p1) => `${parseFloat(p1) / 2}kg`); + size = size.replace(/\n.*$/, '').replace(/【.*?】/g, '').replace(/\s+/g, ' ').trim(); + if (!size) size = null; + } + + generated_options.push({ + color, + sizes: size ? [size] : [], + price: priceVal, + thumbnail: resolveThumbnail(key, color) + }); + } + + console.log(`Generated options from SKU map (${generated_options.length})`); + + // --- TRANSLATE OPTIONS IF AI IS AVAILABLE --- + if (aiClient && generated_options.length > 0) { + console.log(`Translating ${generated_options.length} options via AI (chunked)...`); + + const translateChunk = async (chunk) => { + const optionsText = JSON.stringify(chunk.map(o => ({ c: o.color, s: (o.sizes && o.sizes[0]) ? o.sizes[0] : "" }))); + const transPrompt = ` + Translate these product options to Arabic. + Input: ${optionsText} + + IMPORTANT: + - Return ONLY a JSON array. Do not include any conversational text like "Here is the JSON" or markdown code blocks. + - Keep the number of items EXACTLY the same as input. + - Keep the order EXACTLY the same as input. + - Each output item must be {"c": "...", "s": "..."}. + - If the input contains "kg" (kilograms), KEEP "kg" in the translation (e.g. "80kg" -> "80kg" or "80 كغم"). + - Do NOT convert numbers back to original units. + - Remove any Chinese characters or marketing text like "快要断码", "图片色" (Image Color), "高质量", "建议", "斤". + - "图片色" or "默认" should be translated as "كما في الصورة" (As shown in image) or "اللون الافتراضي" (Default Color). + - Remove any newlines or extra whitespace. + - Return pure, clean Arabic names for colors and sizes. + - TRANSLATE COLORS TO ARABIC (e.g. "Black" -> "أسود", "红色" -> "أحمر"). + - TRANSLATE "建议" (Recommended) to "مقترح" or remove it if just a label. + - STRICTLY REMOVE any "return policy", "refund", "replacement" (e.g. "包退", "包换") text from option names. + `; + + const translate = async (model) => { + return await aiClient.chat.completions.create({ + model, + messages: [{ role: "user", content: transPrompt }], + temperature: 0.3, + max_tokens: 2048 + }); + }; + + let transRes; + try { + transRes = await translate(AI_PRIMARY_MODEL); + } catch (e) { + if (isTimeoutError(e)) { + throw e; + } + if (isModelBusyError(e)) { + console.log(`AI busy on ${AI_PRIMARY_MODEL}. Falling back to ${AI_BUSY_FALLBACK_MODEL} for options translation...`); + transRes = await translate(AI_BUSY_FALLBACK_MODEL); + } else if (AI_FALLBACK_MODEL && AI_FALLBACK_MODEL !== AI_PRIMARY_MODEL) { + console.log(`AI error on ${AI_PRIMARY_MODEL}. Falling back to ${AI_FALLBACK_MODEL} for options translation...`); + transRes = await translate(AI_FALLBACK_MODEL); + } else { + throw e; + } + } + + let transJson = transRes.choices[0].message.content.replace(/```json/g, '').replace(/```/g, '').trim(); + const startIdx = transJson.indexOf('['); + const endIdx = transJson.lastIndexOf(']'); + if (startIdx !== -1 && endIdx !== -1) transJson = transJson.substring(startIdx, endIdx + 1); + + const transArr = JSON.parse(transJson); + if (!Array.isArray(transArr) || transArr.length !== chunk.length) { + throw new Error(`Translation length mismatch (${Array.isArray(transArr) ? transArr.length : 'invalid'} vs ${chunk.length})`); + } + return transArr; + }; + + const applyTranslation = (chunk, transArr) => { + for (let i = 0; i < chunk.length; i++) { + const opt = chunk[i]; + const t = transArr[i] || {}; + if (t.c) opt.color = String(t.c).trim().replace(/\s+/g, ' '); + if (Array.isArray(opt.sizes) && opt.sizes.length > 0) { + if (t.s !== undefined && t.s !== null) { + const nextSize = String(t.s).trim().replace(/\s+/g, ' '); + if (nextSize) opt.sizes[0] = nextSize; + } + } + } + }; + + const baseChunkSize = Number(process.env.AI_OPTIONS_TRANSLATE_CHUNK_SIZE) > 0 ? Number(process.env.AI_OPTIONS_TRANSLATE_CHUNK_SIZE) : 25; + const queue = []; + for (let i = 0; i < generated_options.length; i += baseChunkSize) { + queue.push([i, Math.min(i + baseChunkSize, generated_options.length)]); + } + + while (queue.length > 0) { + const [start, end] = queue.shift(); + const chunk = generated_options.slice(start, end); + let ok = false; + let attempts = 0; + const maxAttempts = 3; + while (!ok && attempts < maxAttempts) { + attempts++; + try { + const transArr = await translateChunk(chunk); + applyTranslation(chunk, transArr); + ok = true; + } catch (e) { + if (attempts >= maxAttempts) break; + await delay(700); + } + } + if (!ok) { + if (chunk.length <= 1) continue; + const mid = start + Math.floor((end - start) / 2); + queue.unshift([mid, end]); + queue.unshift([start, mid]); + } + } + + console.log('Options translation applied (chunked best-effort).'); + } else { + console.log('Skipping options translation (AI not ready or no options).'); + } + + console.log(`Variant prices AFTER translation (${generated_options.length})`); + const postLines = []; + for (const opt of generated_options) { + const s = (opt.sizes && opt.sizes[0]) ? opt.sizes[0] : ''; + postLines.push(`${opt.color}${s ? `__SEP__${s}` : ''} => ${opt.price} IQD`); + } + const postPreviewLimit = 120; + postLines.slice(0, postPreviewLimit).forEach(l => console.log(` ${l}`)); + if (postLines.length > postPreviewLimit) console.log(` ... truncated ${postLines.length - postPreviewLimit} more`); + } + + const enrichedProduct = { + product_name: aiData.product_name_ar || 'اسم غير متوفر', + // original_name: data.title, // REMOVED as per request + main_images: data.images.slice(0, 5), + url: productUrl, + // product_details: data.productDetails, // REMOVED as per request + product_details: aiData.product_details_ar, // Use Arabic details as main 'product_details' + // product_details_ar: aiData.product_details_ar, // REMOVED redundancy + product_desc_imgs: data.product_desc_imgs || [], // Description Images + general_price: general_price, + generated_options: generated_options, // New Field + scrapedReviews: data.reviews || [], // Store reviews at top level (renamed from reviews) + aiMetadata: { ...(aiData.aiMetadata || {}) }, // Removed reviews from here + isAirRestricted: aiData.isAirRestricted || false, // New Field + // variants: data.variants, // REMOVED as per request + // skuMap: data.skuMap // REMOVED as per request + }; + + // Calculate Final Price with 15% Profit + const calculateFinalPrice = (base) => { + const price = Number(base) || 0; + if (price <= 0) return 0; + // Formula: (BaseIQD + Domestic) * 1.15 / 10 * 10 (ceil) + // Assuming domestic shipping is 0 or handled separately in cart logic, + // but usually scraper stores the inclusive price. + // Let's stick to the basic profit margin here. + return Math.ceil((price * 1.15) / 10) * 10; + }; + + const finalPrice = calculateFinalPrice(general_price); + + // CHECK: Skip product if price is too low (<= 250 IQD) + // This usually indicates a failed price extraction or a dummy product + if (finalPrice <= 250) { + console.log(`Skipping product: Price too low (Final: ${finalPrice}, Base: ${general_price}). URL: ${productUrl}`); + if (!navigationHappened) await newPage.close(); + else await newPage.goBack(); + continue; + } + + products.push(enrichedProduct); + console.log(`Scraped successfully. Total: ${products.length}`); + + fs.writeFileSync(OUTPUT_FILE, JSON.stringify(products, null, 2)); + + // --- DATABASE INSERTION --- + console.log('Inserting into Database...'); + try { + // 1. Create Product + const newProduct = await prisma.product.create({ + data: { + name: enrichedProduct.product_name, + price: finalPrice, // Store FINAL price with profit + basePriceIQD: enrichedProduct.general_price || 0, // Store BASE price (Cost) + image: enrichedProduct.main_images[0] || '', + purchaseUrl: enrichedProduct.url, + specs: JSON.stringify(enrichedProduct.product_details || {}), + aiMetadata: enrichedProduct.aiMetadata || {}, + scrapedReviews: enrichedProduct.scrapedReviews || [], // Save reviews to DB + isAirRestricted: enrichedProduct.isAirRestricted || false, // Save to DB + status: "PUBLISHED", + isActive: true, + } + }); + console.log(`Product created: ID ${newProduct.id}`); + + // 2. Create Product Images (Gallery) + if (enrichedProduct.main_images && enrichedProduct.main_images.length > 0) { + await prisma.productImage.createMany({ + data: enrichedProduct.main_images.map((url, i) => ({ + productId: newProduct.id, + url: url, + order: i, + type: "GALLERY" + })) + }); + } + + // 3. Create Description Images + if (enrichedProduct.product_desc_imgs && enrichedProduct.product_desc_imgs.length > 0) { + await prisma.productImage.createMany({ + data: enrichedProduct.product_desc_imgs.map((url, i) => ({ + productId: newProduct.id, + url: url, + order: i + 100, // Offset to keep them after gallery + type: "DESCRIPTION" + })) + }); + } + + // 4. Create Product Options (Color & Size) - VALIDATED + const colors = new Set(); + const sizes = new Set(); + + // Filter out Chinese characters from options + const containsChinese = (str) => /[\u4e00-\u9fa5]/.test(str); + + // Filter out invalid/suspicious options (Custom orders, deposits, etc.) + const invalidKeywords = [ + '定制', '专拍', '补差', '邮费', '不发货', '联系客服', // Chinese + 'تخصيص', 'اتصال', 'رابط', 'فرق', 'إيداع', 'لا يرسل', 'خدمة العملاء', 'مخصص' // Arabic + ]; + + enrichedProduct.generated_options = enrichedProduct.generated_options.filter(opt => { + const text = (opt.color || '') + ' ' + (opt.sizes ? opt.sizes.join(' ') : ''); + const hasInvalidKeyword = invalidKeywords.some(kw => text.includes(kw)); + + if (hasInvalidKeyword) { + console.log(`Skipping invalid/suspicious option: ${text} (Price: ${opt.price})`); + return false; + } + return true; + }); + + enrichedProduct.generated_options.forEach(opt => { + // Skip entire option if color is Chinese + if (opt.color && !containsChinese(opt.color)) { + colors.add(opt.color); + } else if (opt.color) { + // RETRY TRANSLATION FOR SINGLE OPTION + // We do a synchronous-like blocking call here or just use it as is if critical? + // User said: "try to translate it again if you can't then use it, don't skip generated options" + console.log(`Chinese color detected: ${opt.color}. Attempting fallback translation/usage...`); + colors.add(opt.color); // Add it anyway, don't skip + } + + if (opt.sizes && Array.isArray(opt.sizes)) { + opt.sizes.forEach(s => { + if (!containsChinese(s)) { + sizes.add(s); + } else { + console.log(`Chinese size detected: ${s}. Using it anyway.`); + sizes.add(s); + } + }); + } + }); + + // Only create options if we have valid values + if (colors.size > 0) { + await prisma.productOption.create({ + data: { + productId: newProduct.id, + name: "اللون", + values: JSON.stringify(Array.from(colors)) + } + }); + } + + if (sizes.size > 0) { + await prisma.productOption.create({ + data: { + productId: newProduct.id, + name: "المقاس", + values: JSON.stringify(Array.from(sizes)) + } + }); + } + + // 5. Create Variants - VALIDATED + const variantsData = []; + const normalizeVariantBasePrice = (basePrice) => { + let p = Number(basePrice) || 0; + if (p > 0 && p < 100) { + console.log(`Warning: Suspiciously low price (${p}). Assuming RMB and multiplying by 200.`); + p = p * 200; + } else if (p > 0 && p < 1000 && enrichedProduct.general_price > 5000) { + console.log(`Warning: Variant price ${p} vs Main ${enrichedProduct.general_price}. Assuming RMB.`); + p = p * 200; + } + return p; + }; + for (const opt of enrichedProduct.generated_options) { + // SKIP if color is Chinese (DISABLED: User wants to keep them) + // if (containsChinese(opt.color)) continue; + + const color = opt.color; + const fallbackBasePrice = normalizeVariantBasePrice(opt.price || enrichedProduct.general_price || 0); + const variantImg = opt.thumbnail || enrichedProduct.main_images[0] || ''; + + if (opt.sizes && Array.isArray(opt.sizes) && opt.sizes.length > 0) { + for (const size of opt.sizes) { + const variantBasePrice = fallbackBasePrice; + const variantFinalPrice = calculateFinalPrice(variantBasePrice); + const combinationObj = { + "اللون": color, + "المقاس": size + }; + variantsData.push({ + productId: newProduct.id, + combination: JSON.stringify(combinationObj), + price: variantFinalPrice, + basePriceIQD: variantBasePrice, + image: variantImg + }); + } + } else { + const variantBasePrice = fallbackBasePrice; + const variantFinalPrice = calculateFinalPrice(variantBasePrice); + const combinationObj = { "اللون": color }; + variantsData.push({ + productId: newProduct.id, + combination: JSON.stringify(combinationObj), + price: variantFinalPrice, + basePriceIQD: variantBasePrice, + image: variantImg + }); + } + } + + if (variantsData.length > 0) { + await prisma.productVariant.createMany({ + data: variantsData + }); + } + console.log('Database insertion complete.'); + + // Generate and save embedding for new product + if (newProduct && newProduct.id) { + try { + console.log('Triggers the embedding...'); + await processProductEmbedding(newProduct.id); + } catch (embedErr) { + console.error(`Embedding generation failed for product ${newProduct.id} (non-fatal):`, embedErr.message); + } + } + + } catch (dbErr) { + console.error('Database Insertion Failed:', dbErr.message); + } + + // --- SKIP DB INSERTION (Local Mode) --- + // console.log('Skipping Database Insertion (Local Mode)'); + + } catch (scrapeErr) { + console.error('Scrape error:', scrapeErr.message); + } + + // Clean up + if (!navigationHappened) { + await newPage.close(); + } else { + console.log('Going back to category page...'); + await page.goBack({ waitUntil: 'domcontentloaded' }); + await humanDelay(2000, 3000); + } + + await humanDelay(2000, 5000); + + // Random Delay between 10-15 seconds before next item + const nextItemDelay = 10000 + Math.random() * 5000; + console.log(`Waiting ${(nextItemDelay/1000).toFixed(1)}s before next item...`); + await delay(nextItemDelay); + } // End of 4-click loop + + // Scroll down to load more items for next pass + console.log('Finished batch of 4 clicks. Scrolling for more items...'); + await autoScroll(page); + await humanDelay(3000, 5000); + } + + console.log('[End] Scraping Complete.'); + await browser.close(); + await prisma.$disconnect(); +} + +run().catch(err => console.error('Fatal Error:', err)); + +process.on('unhandledRejection', (reason, p) => { + console.error('Unhandled Rejection at:', p, 'reason:', reason); +}); + +// Force keep-alive +setInterval(() => { + try { + fs.appendFileSync('scraper_debug.log', `Tick: ${new Date().toISOString()}\n`); + } catch(e) {} +}, 5000); diff --git a/server/scripts/pinduoduo-scraper.js b/server/scripts/pinduoduo-scraper.js index 26505ea0a4ca8f6fe9063045167865cb68e80936..f1b8ab4337afe6584781045eb9b2466a7da0a63e 100644 --- a/server/scripts/pinduoduo-scraper.js +++ b/server/scripts/pinduoduo-scraper.js @@ -1,4 +1,4 @@ -import vanillaPuppeteer from 'puppeteer-core'; +import vanillaPuppeteer from 'puppeteer-core'; import puppeteerExtra from 'puppeteer-extra'; import StealthPlugin from 'puppeteer-extra-plugin-stealth'; @@ -12,29 +12,88 @@ import OpenAI from 'openai'; // Use OpenAI SDK for SiliconFlow import readline from 'readline'; import { fileURLToPath } from 'url'; import { PrismaClient } from '@prisma/client'; +import { processProductEmbedding } from '../services/aiService.js'; // Load .env const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); const envPath = path.join(__dirname, '..', '.env'); // server/.env dotenv.config({ path: envPath }); + +// --- FIX DATABASE CONNECTION POOL --- +// Enforce connection limit to prevent "MaxClientsInSessionMode" error +if (process.env.DATABASE_URL) { + try { + const url = new URL(process.env.DATABASE_URL); + // Use minimal connections (1) for this single-threaded scraper to avoid exhausting the pool + url.searchParams.set('connection_limit', '1'); + process.env.DATABASE_URL = url.toString(); + } catch (e) { + console.warn('Warning: Could not parse DATABASE_URL to set connection_limit'); + } +} + const prisma = new PrismaClient(); + +// --- DATABASE SCHEMA HEALING --- +async function ensureDatabaseSchema() { + // Skip schema check to save DB connections if flag is set or environment is production-like + if (process.env.SKIP_SCHEMA_CHECK === 'true') { + console.log('Skipping schema check (SKIP_SCHEMA_CHECK=true)'); + return; + } + + try { + console.log('Checking database schema...'); + // Retry logic for initial connection + let retries = 3; + while (retries > 0) { + try { + const columns = await prisma.$queryRawUnsafe(` + SELECT column_name + FROM information_schema.columns + WHERE table_name = 'Product' AND column_name = 'scrapedReviews'; + `); + + if (columns.length === 0) { + console.log('Adding missing "scrapedReviews" column...'); + await prisma.$executeRawUnsafe(`ALTER TABLE "Product" ADD COLUMN IF NOT EXISTS "scrapedReviews" JSONB;`); + console.log('Schema update attempted.'); + } else { + console.log('Schema OK: "scrapedReviews" column exists.'); + } + break; // Success + } catch (e) { + console.warn(`Schema check failed (attempt ${4-retries}/3): ${e.message}`); + retries--; + if (retries === 0) { + console.warn('Skipping schema check after multiple failures (non-fatal).'); + } else { + console.log(`Waiting 5s before retry (Attempt ${4-retries}/3)...`); + await new Promise(r => setTimeout(r, 5000)); + } + } + } + } catch (e) { + console.warn('Schema check/fix failed (non-fatal):', e.message); + } +} // const prisma = { $disconnect: async () => {} }; // --- EDIBLE ITEM FILTERING CONFIGURATION --- const EDIBLE_KEYWORDS = [ - "食品", "零食", "坚果", "罐头", "饮料", "糖果", "饼干", "调料", "茶", "酒", - "肉", "蛋", "奶", "油", "米", "面", "果冻", "巧克力", "咖啡", "food", "snack", + "é£ںه“پ", "é›¶é£ں", "ه‌ڑو‍œ", "ç½گه¤´", "饮و–™", "ç³–و‍œ", "饼ه¹²", "è°ƒو–™", "茶", "é…’", + "肉", "蛋", "ه¥¶", "و²¹", "ç±³", "é‌¢", "و‍œه†»", "ه·§ه…‹هٹ›", "ه’–ه•،", "food", "snack", "nut", "can", "drink", "candy", "biscuit", "seasoning", "tea", "wine", "meat", "egg", "milk", "oil", "rice", "noodle", "jelly", "chocolate", "coffee", - "吃", "喝", "味", "香", "甜", "辣", "咸", "酸", "苦" // General taste/eating words (use with caution or in combination) + "هگƒ", "ه–‌", "ه‘³", "香", "甜", "è¾£", "ه’¸", "é…¸", "苦" // General taste/eating words (use with caution or in combination) ]; // Stricter list for immediate rejection const STRICT_EDIBLE_KEYWORDS = [ - "食品", "零食", "坚果", "罐头", "饮料", "糖果", "饼干", "调料", "茶叶", "酒水", - "鲜肉", "鸡蛋", "牛奶", "食用油", "大米", "面粉", "果冻", "巧克力", "咖啡豆", - "保健品", "维生素", "钙片", "酵素", "益生菌" // Supplements + "é£ںه“پ", "é›¶é£ں", "ه‌ڑو‍œ", "ç½گه¤´", "饮و–™", "ç³–و‍œ", "饼ه¹²", "è°ƒو–™", "茶هڈ¶", "é…’و°´", + "鲜肉", "é¸،蛋", "牛ه¥¶", "é£ں用و²¹", "ه¤§ç±³", "é‌¢ç²‰", "و‍œه†»", "ه·§ه…‹هٹ›", "ه’–ه•،豆", + "ن؟‌هپ¥ه“پ", "ç»´ç”ںç´ ", "钙片", "酵素", "ç›ٹç”ںèڈŒ" // Supplements ]; function isEdiblePreCheck(title, description) { @@ -221,7 +280,7 @@ async function enrichWithAI(title, description, price) { - The "product_details_ar" field MUST be a JSON OBJECT (key-value pairs), NOT a string. - Example format for details: "product_details_ar": { - "المادة": "قماش كتّان", + "المادة": "قماش كتان", "الميزة": "ألوان متعددة", "التصميم": "إبداعي", "الاستخدام": "غرفة المعيشة" @@ -233,7 +292,7 @@ async function enrichWithAI(title, description, price) { - English text IS ALLOWED for Brand Names and Model Numbers. - Convert all prices and measurements to Arabic format if possible. - Return ONLY a valid JSON object with this structure (no markdown): + Return ONLY a valid JSON object with this structure (no markdown, no \`\`\`json blocks): { "product_name_ar": "Put Translated Name Here", "is_edible": false, @@ -259,7 +318,7 @@ async function enrichWithAI(title, description, price) { model, messages: [{ role: "user", content: prompt }], temperature: 0.2, - max_tokens: 900, + max_tokens: 1500, }); }; @@ -363,13 +422,13 @@ async function enrichWithAI(title, description, price) { // Ensure arrays are arrays if (!Array.isArray(parsed.aiMetadata.synonyms)) parsed.aiMetadata.synonyms = []; if (!Array.isArray(parsed.aiMetadata.market_tags)) parsed.aiMetadata.market_tags = []; - if (!parsed.aiMetadata.category_suggestion) parsed.aiMetadata.category_suggestion = "عام"; + if (!parsed.aiMetadata.category_suggestion) parsed.aiMetadata.category_suggestion = "ط¹ط§ظ…"; } else { // Fallback: Try to infer from parsed name if possible, otherwise use generic but marked as fallback parsed.aiMetadata = { synonyms: [parsed.product_name_ar], // Use the name itself as a synonym at least - market_tags: ["منتج مميز"], - category_suggestion: "أخرى" + market_tags: ["ظ…ظ†طھط¬ ظ…ظ…ظٹط²"], + category_suggestion: "ط£ط®ط±ظ‰" }; } @@ -496,6 +555,27 @@ async function safeEvaluate(page, pageFunction, args = [], maxAttempts = 4) { throw lastErr || new Error('safeEvaluate failed'); } +async function safeGoto(page, url, options = {}, maxRetries = 3) { + for (let i = 0; i < maxRetries; i++) { + try { + return await page.goto(url, options); + } catch (e) { + const msg = e.message || ''; + if (i === maxRetries - 1) throw e; + + if (msg.includes('ERR_CONNECTION_REFUSED') || + msg.includes('ERR_CONNECTION_RESET') || + msg.includes('Timeout') || + msg.includes('net::ERR_')) { + console.log(`[Navigation] Retry ${i+1}/${maxRetries} for ${url} (${msg})`); + await delay(2000 * (i + 1)); + } else { + throw e; + } + } + } +} + async function createBrowser() { const executablePath = getExecutablePath(); if (!executablePath) { @@ -542,6 +622,7 @@ async function autoScroll(page) { } async function run() { + await ensureDatabaseSchema(); console.log('[Start] Initializing Pinduoduo Scraper (Click-and-Scrape Mode)...'); // Ask for URL or use predefined @@ -560,7 +641,7 @@ async function run() { urlInput = urlInput.trim(); if (!urlInput.startsWith('http')) { - console.error('❌ Error: Invalid URL provided. The URL must start with "http" or "https".'); + console.error('â‌Œ Error: Invalid URL provided. The URL must start with "http" or "https".'); console.error('You entered:', urlInput); console.log('Please restart the script and paste the correct URL.'); process.exit(1); @@ -575,6 +656,21 @@ async function run() { console.log('Browser launched'); let page = await browser.newPage(); console.log('Page created'); + + // Enable console log forwarding from the browser to the terminal + page.on('console', msg => { + const type = msg.type(); + const text = msg.text(); + // Filter out some noise if needed, but user wants logs so keep most + if (!text.includes('ERR_BLOCKED_BY_CLIENT')) { + // console.log(`[Browser Console] ${type.toUpperCase()}: ${text}`); + } + }); + + page.on('pageerror', err => { + console.log(`[Browser Error]: ${err.toString()}`); + }); + await applyPageTimeouts(page); // --- STEALTH MEASURES --- @@ -619,7 +715,7 @@ async function run() { // FORCE LOGIN NAVIGATION IF NOT LOGGED IN console.log('Visiting Login URL first to ensure valid session...'); try { - await page.goto('https://mobile.pinduoduo.com/login.html', { waitUntil: 'domcontentloaded', timeout: PAGE_LOAD_TIMEOUT }); + await safeGoto(page, 'https://mobile.pinduoduo.com/login.html', { waitUntil: 'domcontentloaded', timeout: PAGE_LOAD_TIMEOUT }); } catch(e) { console.log('Login goto error (might be redirect):', e.message); } console.log('Login page loaded (or redirected).'); @@ -657,7 +753,7 @@ async function run() { } console.log('Visiting Clean Category URL:', cleanUrl); - await page.goto(cleanUrl, { waitUntil: 'domcontentloaded', timeout: PAGE_LOAD_TIMEOUT }); + await safeGoto(page, cleanUrl, { waitUntil: 'domcontentloaded', timeout: PAGE_LOAD_TIMEOUT }); console.log('Category page loaded.'); // SWITCH TO MOBILE VIEWPORT AFTER LOGIN & NAVIGATION @@ -667,7 +763,7 @@ async function run() { /* console.log('Visiting Category URL (and performing login check there):', CATEGORY_URL); - await page.goto(CATEGORY_URL, { waitUntil: 'domcontentloaded', timeout: PAGE_LOAD_TIMEOUT }); + await safeGoto(page, CATEGORY_URL, { waitUntil: 'domcontentloaded', timeout: PAGE_LOAD_TIMEOUT }); console.log('Goto done'); console.log('================================================================'); @@ -686,7 +782,7 @@ async function run() { const cookies = await page.cookies(); const cookiePath = path.join(__dirname, 'pdd_cookies.json'); fs.writeFileSync(cookiePath, JSON.stringify(cookies, null, 2)); - console.log('✅ Login cookies saved to pdd_cookies.json'); + console.log('✅ Login cookies saved to pdd_cookies.json'); } catch (err) { console.error('Failed to save cookies:', err.message); } @@ -706,7 +802,7 @@ async function run() { await new Promise(r => setTimeout(r, 1000)); }); } catch (e) { - console.warn('⚠️ Scroll error (ignoring):', e.message); + console.warn('âڑ ï¸ڈ Scroll error (ignoring):', e.message); // If execution context destroyed, it usually means page refreshed or navigated. // We can just wait a bit and proceed. await delay(1000); @@ -730,72 +826,97 @@ async function run() { } } catch(e) {} + // Track scroll position to restore it if we drift and reload + let accumulatedScrollY = 0; + // Main Loop // User requested infinite loop until manually stopped while (isRunning) { - // --- VALIDATE CURRENT URL --- - // Ensure we are still on the category page or search result page we started with. - // If we drifted to home or another category, go back. - const currentUrlBeforeScroll = page.url(); - const isHomePage = currentUrlBeforeScroll === 'https://mobile.pinduoduo.com/' || currentUrlBeforeScroll.includes('page_id=10002'); - // Simple check: if we are not on the category URL and not on a product page (which we shouldn't be here), go back. - // Better: Check if the URL contains key parts of our CATEGORY_URL - // Extract 'search_key' from CATEGORY_URL if it exists - let requiredParam = ''; + // --- STRICT DRIFT CHECK & RESTORE --- + const currentUrl = page.url(); + let isOnTargetCategory = true; + try { - const catUrlObj = new URL(CATEGORY_URL); - if (catUrlObj.searchParams.has('search_key')) { - requiredParam = 'search_key=' + encodeURIComponent(catUrlObj.searchParams.get('search_key')); - } else if (catUrlObj.searchParams.has('cat_id')) { - requiredParam = 'cat_id=' + catUrlObj.searchParams.get('cat_id'); + const targetUrlObj = new URL(CATEGORY_URL); + const currentUrlObj = new URL(currentUrl); + + // If current URL is a product page, we definitely drifted + if (currentUrl.includes('goods_id') || currentUrl.includes('goods.html') || currentUrl.includes('goods_detail')) { + isOnTargetCategory = false; + } else { + // Check key parameters to ensure we are on the same category/search context + const paramsToCheck = ['opt_id', 'cat_id', 'search_key', 'subjects_id']; + for (const param of paramsToCheck) { + const targetVal = targetUrlObj.searchParams.get(param); + if (targetVal) { + const currentVal = currentUrlObj.searchParams.get(param); + // If target has a param, current MUST have it and match + if (currentVal !== targetVal) { + console.log(`Drift Param Mismatch [${param}]: Expected ${targetVal}, Got ${currentVal}`); + isOnTargetCategory = false; + break; + } + } + } } - } catch(e) {} + } catch(e) { + // Fallback loose check + isOnTargetCategory = currentUrl.includes('catgoods') || currentUrl.includes('search_result') || currentUrl.includes('subjects'); + } - // DISABLE AUTO-REDIRECT for now - it's causing loops if the URL format changes slightly - // if (isHomePage || (requiredParam && !currentUrlBeforeScroll.includes(decodeURIComponent(requiredParam)) && !currentUrlBeforeScroll.includes(requiredParam))) { - // console.log('WARNING: Drifted away from category page. Redirecting back to:', CATEGORY_URL); - // await page.goto(CATEGORY_URL, { waitUntil: 'domcontentloaded', timeout: PAGE_LOAD_TIMEOUT }); - // await humanDelay(3000, 5000); - // } + if (!isOnTargetCategory) { + console.log('⚠️ Critical Drift Detected: Not on provided Category URL.'); + console.log(` Target: ${CATEGORY_URL}`); + console.log(` Current: ${currentUrl}`); + console.log(' -> Reloading Category Page and Restoring Scroll Position...'); + + try { + await safeGoto(page, CATEGORY_URL, { waitUntil: 'domcontentloaded', timeout: PAGE_LOAD_TIMEOUT }); + await humanDelay(2000, 3000); + + // Restore Scroll Position + if (accumulatedScrollY > 0) { + console.log(` -> Restoring scroll to Y=${accumulatedScrollY} (triggering lazy load)...`); + await page.evaluate(async (targetY) => { + const viewportHeight = window.innerHeight; + let currentY = 0; + // Scroll in steps to trigger lazy loading + while (currentY < targetY) { + window.scrollBy(0, viewportHeight); + currentY += viewportHeight; + // Wait a bit for content to load + await new Promise(r => setTimeout(r, 400)); + } + // Final adjustment + window.scrollTo(0, targetY); + }, accumulatedScrollY); + await humanDelay(1500, 2500); + console.log(' -> Scroll position restored.'); + } + } catch(e) { + console.log('Error returning to category:', e.message); + } + } - // --- 4-POINT BLIND CLICK STRATEGY --- - console.log('Scrolling down to find new batch of products...'); + // --- 3-POINT CLICK STRATEGY --- + // console.log('Starting search sequence...'); // Simplified log - // 1. Scroll down one screen size + a bit - try { - await page.evaluate(async () => { - // Random scroll - const viewportHeight = window.innerHeight; - const distance = viewportHeight + 100 + Math.floor(Math.random() * 200); - window.scrollBy(0, distance); - await new Promise(r => setTimeout(r, 1000)); - }); - } catch (e) { - console.warn('⚠️ Scroll error in loop (recovering):', e.message); - // Wait and reload context if needed - await delay(2000); - if (page.isClosed()) break; - continue; // Skip this iteration - } + // Removed initial scroll to prevent "going down immediately" - await humanDelay(2000, 3000); - - // Define the 4 click points (percentages of viewport) - // Adjust for Mobile Viewport in Desktop Browser + // Define the click points (percentages of viewport) const clickPoints = [ - { name: "Top-Right", xPct: 0.75, yPct: 0.30 }, - { name: "Top-Left", xPct: 0.25, yPct: 0.30 }, - { name: "Bot-Left", xPct: 0.25, yPct: 0.70 }, - { name: "Bot-Right", xPct: 0.75, yPct: 0.70 } + { name: "Top-Left", xPct: 0.25, yPct: 0.35 }, + { name: "Top-Right", xPct: 0.75, yPct: 0.35 }, + { name: "Bot-Right", xPct: 0.75, yPct: 0.70 }, + { name: "Bot-Left", xPct: 0.25, yPct: 0.70 } ]; for (const point of clickPoints) { if (!isRunning) break; - // if (products.length >= TARGET_PRODUCT_COUNT) break; // Removed limit as per request - console.log(`Preparing to click: ${point.name}...`); + console.log(`> Checking ${point.name}...`); const clickCoordinates = await page.evaluate((pt) => { const width = window.innerWidth; @@ -811,7 +932,7 @@ async function run() { }; }, point); - console.log(`Clicking at (${clickCoordinates.x}, ${clickCoordinates.y})...`); + // console.log(`Clicking at (${clickCoordinates.x}, ${clickCoordinates.y})...`); // Listen for new target const newTargetPromise = new Promise(resolve => browser.once('targetcreated', resolve)); @@ -821,7 +942,7 @@ async function run() { // Use evaluating touchstart for mobile simulation if mouse click fails await page.mouse.click(clickCoordinates.x, clickCoordinates.y); } catch (e) { - console.log('Click failed:', e.message); + // console.log('Click failed:', e.message); } // Wait for navigation @@ -835,8 +956,18 @@ async function run() { ]); if (target && target.type() === 'page') { - console.log('New tab detected.'); + // console.log('New tab detected.'); newPage = await target.page(); + + // ENABLE CONSOLE LOGS FOR NEW TAB + newPage.on('console', msg => { + const type = msg.type(); + const text = msg.text(); + if (!text.includes('ERR_BLOCKED_BY_CLIENT')) { + // console.log(`[Browser NewPage] ${type.toUpperCase()}: ${text}`); + } + }); + await applyPageTimeouts(newPage); // STEALTH: Ensure new page looks like it came from the main page @@ -852,15 +983,15 @@ async function run() { }); } catch(e) {} } else { - console.log('No new tab. Checking if current page navigated...'); + // console.log('No new tab. Checking navigation...'); await delay(2000); if (page.url() !== currentUrl && !page.url().includes('catgoods')) { - console.log('Current page navigated. Treating as product page.'); + console.log('Navigated in same tab.'); newPage = page; navigationHappened = true; await applyPageTimeouts(newPage); } else { - console.log('Click did not trigger navigation. Moving to next point.'); + // console.log('No navigation. Next...'); // Just continue to next point in loop continue; } @@ -882,11 +1013,11 @@ async function run() { const isLogin = await safeEvaluate(newPage, () => { const t = (document.body && document.body.innerText) ? document.body.innerText : ''; const s = String(t || ''); - return s.includes('登录') && (s.includes('扫码登录') || s.includes('同意服务协议') || s.includes('隐私政策')); + return s.includes('ç™»ه½•') && (s.includes('و‰«ç پç™»ه½•') || s.includes('هگŒو„ڈوœچهٹ،هچڈè®®') || s.includes('éڑگç§پو”؟ç­–')); }, [], 12); if (isLogin) { - console.log('⚠️ Hit login page. Skipping product and returning to listing...'); + console.log('âڑ ï¸ڈ Hit login page. Skipping product and returning to listing...'); if (!navigationHappened && newPage.close) await newPage.close(); else { try { @@ -902,11 +1033,11 @@ async function run() { const isSoldOut = await safeEvaluate(newPage, () => { const text = document.body.innerText; - return text.includes('商品已售罄') || text.includes('已售完') || text.includes('下架'); + return text.includes('ه•†ه“په·²ه”®ç½„') || text.includes('ه·²ه”®ه®Œ') || text.includes('ن¸‹و‍¶'); }); if (isSoldOut) { - console.log('⚠️ Product is SOLD OUT (or Anti-Bot triggered). Skipping...'); + console.log('âڑ ï¸ڈ Product is SOLD OUT (or Anti-Bot triggered). Skipping...'); console.log(' -> Hint: If this happens for ALL products, try deleting pdd_cookies.json and re-login.'); if (!navigationHappened) await newPage.close(); else await newPage.goBack(); @@ -1034,7 +1165,7 @@ async function run() { } catch (e) {} if (m && m.querySelector && m.querySelector('.iW4aEGbb')) return false; const t = String(m?.innerText || m?.textContent || ''); - if (t.includes('已选') || t.includes('请选择') || t.includes('规格')) return true; + if (t.includes('ه·²é€‰') || t.includes('请选و‹©') || t.includes('è§„و ¼')) return true; if (m.querySelector('.O7pEFvHR') || m.querySelector('.bIhLWVqm') || m.querySelector('li.TpUpcNRp') || m.querySelector('div._8gg8ho2u')) return true; return false; }; @@ -1093,7 +1224,7 @@ async function run() { } catch (e) {} if (m && m.querySelector && m.querySelector('.iW4aEGbb')) return false; const t = String(m?.innerText || m?.textContent || ''); - if (t.includes('已选') || t.includes('请选择') || t.includes('规格')) return true; + if (t.includes('ه·²é€‰') || t.includes('请选و‹©') || t.includes('è§„و ¼')) return true; if (m.querySelector('.O7pEFvHR') || m.querySelector('.bIhLWVqm') || m.querySelector('li.TpUpcNRp') || m.querySelector('div._8gg8ho2u')) return true; return false; }; @@ -1157,10 +1288,10 @@ async function run() { const popup = document.querySelector('.iW4aEGbb'); if (!popup) return null; const close = - popup.querySelector('div[role="button"][aria-label*="关闭"]') || - popup.querySelector('button[aria-label*="关闭"]') || - popup.querySelector('div[role="button"][aria-label="关闭弹窗"]') || - popup.querySelector('div[role="button"][aria-label="关闭"]') || + popup.querySelector('div[role="button"][aria-label*="ه…³é—­"]') || + popup.querySelector('button[aria-label*="ه…³é—­"]') || + popup.querySelector('div[role="button"][aria-label="ه…³é—­ه¼¹çھ—"]') || + popup.querySelector('div[role="button"][aria-label="ه…³é—­"]') || popup.querySelector('button') || null; const el = close || popup; @@ -1268,7 +1399,7 @@ async function run() { for (const el of nodes) { const t = String(el.innerText || el.textContent || '').replace(/\s+/g, ' ').trim(); if (!t) continue; - if (!t.includes('¥') && !t.includes('¥')) continue; + if (!t.includes('آ¥') && !t.includes('ï؟¥')) continue; const r = el.getBoundingClientRect(); if (!r || r.width < 40 || r.height < 16 || r.height > 140) continue; count++; @@ -1393,7 +1524,7 @@ async function run() { if (el.closest && el.closest('.iW4aEGbb')) continue; const t = String(el.innerText || el.textContent || '').replace(/\s+/g, ' ').trim(); if (!t) continue; - if (!t.includes('图') && !t.includes('图片')) continue; + if (!t.includes('ه›¾') && !t.includes('ه›¾ç‰‡')) continue; const r = el.getBoundingClientRect(); if (!visibleRect(r)) continue; const score = r.width * r.height * 0.6; @@ -1521,6 +1652,7 @@ async function run() { await waitForStableUrl(newPage, 1400, 15000); + console.log('[Main] Starting main product data extraction (safeEvaluate)...'); const data = await safeEvaluate(newPage, async () => { const wait = (ms) => new Promise(r => setTimeout(r, ms)); @@ -1529,16 +1661,16 @@ async function run() { const r = (root && typeof root.querySelector === 'function') ? root : document; const targetDiv = r.querySelector('.ujEqGzEB') || document.querySelector('.ujEqGzEB'); if (targetDiv) { - // Try aria-label first (e.g. "首件¥29.88") + // Try aria-label first (e.g. "首ن»¶آ¥29.88") const imgSpan = targetDiv.querySelector('span[role="img"]'); if (imgSpan && imgSpan.getAttribute('aria-label')) { const label = imgSpan.getAttribute('aria-label'); - const match = label.match(/¥\s*(\d+(\.\d+)?)/); - if (match) return '¥' + match[1]; + const match = label.match(/آ¥\s*(\d+(\.\d+)?)/); + if (match) return 'آ¥' + match[1]; } // Fallback to text content const text = targetDiv.innerText; - const match = text.match(/¥\s*(\d+(\.\d+)?)/); + const match = text.match(/آ¥\s*(\d+(\.\d+)?)/); if (match) return match[0]; } @@ -1549,7 +1681,7 @@ async function run() { document.querySelector('.Ngfn6pTR .kYzukoxf'); if (altPriceEl) { const text = altPriceEl.innerText.replace(/\n/g, ' ').trim(); - const match = text.match(/¥\s*(\d+(\.\d+)?)/); + const match = text.match(/آ¥\s*(\d+(\.\d+)?)/); if (match) return match[0]; } @@ -1593,7 +1725,7 @@ async function run() { } if (!price) { const bodyText = document.body.innerText; - const priceMatch = bodyText.match(/¥\s*(\d+(\.\d+)?)/); + const priceMatch = bodyText.match(/آ¥\s*(\d+(\.\d+)?)/); if (priceMatch) price = priceMatch[0]; } @@ -1642,7 +1774,7 @@ async function run() { const priceEl = c?.querySelector?.('.nvN5jV0G') || c?.querySelector?.('[class*="nvN5jV0G"]'); const priceRaw = priceEl?.innerText || priceEl?.textContent || ''; const pm = String(priceRaw || '').match(/(\d+(\.\d+)?)/); - const priceStr = pm ? (`¥${pm[1]}`) : null; + const priceStr = pm ? (`آ¥${pm[1]}`) : null; const imgEl = c.querySelector('.PQoZYCec img') || @@ -1958,7 +2090,7 @@ async function run() { if (Number.isFinite(pVal)) { if (lowestVariantPrice === null || pVal < lowestVariantPrice) { lowestVariantPrice = pVal; - price = `¥${pMatch[1]}`; + price = `آ¥${pMatch[1]}`; } } } @@ -2017,8 +2149,8 @@ async function run() { for (const s of spans) { const t = String(s?.innerText || s?.textContent || '').replace(/\s+/g, ' ').trim(); if (!t) continue; - if (t.includes('¥') || t.includes('¥')) continue; - if (t.includes('已选') || t.includes('请选择')) continue; + if (t.includes('آ¥') || t.includes('ï؟¥')) continue; + if (t.includes('ه·²é€‰') || t.includes('请选و‹©')) continue; if (t.length > 80) continue; text = t; break; @@ -2029,11 +2161,11 @@ async function run() { let priceRaw = priceEl?.innerText || priceEl?.textContent || ''; if (!priceRaw) { const t = String(c?.innerText || c?.textContent || ''); - const m = t.match(/[¥¥]\s*(\d+(\.\d+)?)/); + const m = t.match(/[آ¥ï؟¥]\s*(\d+(\.\d+)?)/); if (m) priceRaw = m[0]; } const pm = String(priceRaw || '').match(/(\d+(\.\d+)?)/); - const priceStr = pm ? (`¥${pm[1]}`) : null; + const priceStr = pm ? (`آ¥${pm[1]}`) : null; return { text, priceStr }; }; @@ -2073,7 +2205,7 @@ async function run() { }; const normalizeSelectedSummary = (t) => { - return String(t || '').replace(/^已选\s*[::]\s*/g, '').trim(); + return String(t || '').replace(/^ه·²é€‰\s*[:ï¼ڑ]\s*/g, '').trim(); }; const pickComboKey = (summary) => { @@ -2163,7 +2295,7 @@ async function run() { const uniq = new Set(); for (const p of priceEls) { const t = String(p?.innerText || p?.textContent || '').replace(/\s+/g, ' ').trim(); - if (!t || (!t.includes('¥') && !t.includes('¥'))) continue; + if (!t || (!t.includes('آ¥') && !t.includes('ï؟¥'))) continue; const c = p.closest('li') || p.closest('div') || p.parentElement; if (!c) continue; const key = c === scope ? null : (c.getAttribute?.('class') || '') + '::' + (c.innerText || '').slice(0, 60); @@ -2279,13 +2411,21 @@ async function run() { if (sliderContainer) { for (let i = 0; i < 5; i++) { // Swipe 5 times - // Simulate touch swipe left - const touchStart = new Touch({ identifier: Date.now(), target: sliderContainer, clientX: 300, clientY: 200 }); - const touchEnd = new Touch({ identifier: Date.now(), target: sliderContainer, clientX: 50, clientY: 200 }); - - sliderContainer.dispatchEvent(new TouchEvent('touchstart', { touches: [touchStart], bubbles: true })); - sliderContainer.dispatchEvent(new TouchEvent('touchmove', { touches: [touchEnd], bubbles: true })); - sliderContainer.dispatchEvent(new TouchEvent('touchend', { changedTouches: [touchEnd], bubbles: true })); + try { + // Simulate touch swipe left SAFE + // Some environments (Headless) might not support Touch constructor directly or it behaves oddly + // Use a simpler dispatch if possible, or wrap in try/catch + if (typeof Touch !== 'undefined' && typeof TouchEvent !== 'undefined') { + const touchStart = new Touch({ identifier: Date.now(), target: sliderContainer, clientX: 300, clientY: 200 }); + const touchEnd = new Touch({ identifier: Date.now(), target: sliderContainer, clientX: 50, clientY: 200 }); + + sliderContainer.dispatchEvent(new TouchEvent('touchstart', { touches: [touchStart], bubbles: true })); + sliderContainer.dispatchEvent(new TouchEvent('touchmove', { touches: [touchEnd], bubbles: true })); + sliderContainer.dispatchEvent(new TouchEvent('touchend', { changedTouches: [touchEnd], bubbles: true })); + } + } catch (e) { + // console.log('Swipe simulation failed (non-fatal):', e.message); + } await wait(800); // Wait for animation captureImages(); @@ -2367,177 +2507,581 @@ async function run() { } - // 6. Description Images Extraction - let product_desc_imgs = []; - - console.log('Starting description image extraction sequence...'); - await wait(5000); - try { - for (let i = 0; i < 2; i++) { - const x = Math.floor(window.innerWidth / 2); - const y = 12; - const el = document.elementFromPoint(x, y); - if (el) el.click(); - await wait(220); - } - const backBtn = document.querySelector('div[role="button"][aria-label*="返回"]') || - document.querySelector('div[role="button"][aria-label*="后退"]') || - document.querySelector('div[role="button"][aria-label*="关闭"]'); - if (backBtn) { - backBtn.click(); - await wait(600); - } - } catch (e) {} - await wait(10000); + // --- REORDERED LOGIC: Close Modal -> Reviews -> (Desc Images moved to Part 3) --- - // Step A: Close the variant modal explicitly + // 1. Close the variant modal explicitly (MOVED UP) try { - // User mentioned: "hit the exit button" (likely the X button) - // Selector hints: div[role="button"][aria-label="关闭弹窗"] OR .pD0kR4N1 const closeBtn = document.querySelector('div[role="button"][aria-label="关闭弹窗"]') || document.querySelector('.pD0kR4N1') || document.querySelector('div[role="button"] .pD0kR4N1')?.parentElement; if (closeBtn) { - // console.log('Closing variant modal...'); closeBtn.click(); await wait(1000); } else { - // Try clicking the overlay/mask const mask = document.querySelector('.ReactModal__Overlay, [class*="overlay"], [class*="mask"]'); if (mask) { mask.click(); await wait(1000); } } - } catch(e) { - // console.log('Error closing modal:', e.message); - } + } catch(e) {} + + // 2. Check for Reviews (MOVED UP) + console.log('[Reviews] Checking for reviews...'); + await wait(2000); - // Step B: Slow Scroll to trigger lazy loading (Anti-detection & Image Loading) - // User: "first you have to slowly scroll down so it won't be detected" - const moreProductsDiv = document.querySelector('.mP10ZXCw'); + let hasReviews = false; + let reviewCount = 0; + try { + const reviewText = String.fromCharCode(21830, 21697, 35780, 20215); // 商品评价 + const reviewTextShort = String.fromCharCode(35780, 20215); // 评价 + + let reviewBtn = null; + + // Strategy 1: XPath + try { + const xpath = `//*[contains(text(), '${reviewTextShort}')]`; + const result = document.evaluate(xpath, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); + console.log(`[Reviews] XPath found ${result.snapshotLength} candidates.`); + + for (let i = 0; i < result.snapshotLength; i++) { + const el = result.snapshotItem(i); + if (el.tagName === 'SCRIPT' || el.tagName === 'STYLE') continue; + const text = el.innerText || el.textContent; + if (text && text.length < 30) { + if (text.includes(reviewText) || text.includes(reviewTextShort)) { + if (text.includes(reviewText)) { + reviewBtn = el; + const m = text.match(/(\d+)/); + if (m) reviewCount = parseInt(m[1], 10); + console.log(`[Reviews] Found strict match: ${text} (Count: ${reviewCount})`); + break; + } + if (!reviewBtn) { + reviewBtn = el; + const m = text.match(/(\d+)/); + if (m) reviewCount = parseInt(m[1], 10); + console.log(`[Reviews] Found candidate: ${text} (Count: ${reviewCount})`); + } + } + } + } + } catch(e) { console.log('[Reviews] XPath error:', e.message); } + + // Strategy 2: DOM Scan + if (!reviewBtn) { + console.log('[Reviews] XPath failed, scanning DOM...'); + const allElements = Array.from(document.querySelectorAll('div, span, p, a, button')); + reviewBtn = allElements.find(el => { + const text = el.innerText || el.textContent || ''; + return (text.includes(reviewText) || text.includes(reviewTextShort)) && text.length < 20; + }); + if (reviewBtn) { + const text = reviewBtn.innerText || ''; + const m = text.match(/(\d+)/); + if (m) reviewCount = parseInt(m[1], 10); + } + } + + // Strategy 3: Regex + if (!reviewBtn) { + console.log('[Reviews] DOM scan failed, looking for regex match (Number + 评价)...'); + const allElements = Array.from(document.querySelectorAll('div, span, p')); + for (const el of allElements) { + const text = el.innerText || ''; + const m = text.match(/(\d+)\+?\s*[\u8bc4\u4ef7]/); + if (m && text.length < 15) { + reviewBtn = el; + reviewCount = parseInt(m[1], 10); + console.log(`[Reviews] Found regex match: ${text} (Count: ${reviewCount})`); + break; + } + } + } + + if (reviewBtn) { + console.log(`[Reviews] Found review button (Count: ${reviewCount}). Will click in separate step.`); + hasReviews = true; + } else { + console.log('[Reviews] No review button found.'); + } + } catch (e) { + console.log(`[Reviews] Error checking reviews: ${e.message}`); + } + + return { title, price, description, images: [...new Set(images)], variants, skuMap, skuThumbMap, productDetails, variantImages, hasReviews, reviewCount }; + }, [], 12); + + // --- PART 2A: CLICK REVIEWS (Separate Context) --- + if (data.hasReviews) { + console.log('[Reviews] Clicking review button (Separate Context)...'); + await safeEvaluate(newPage, async () => { + const wait = (ms) => new Promise(r => setTimeout(r, ms)); + console.log('[Reviews] Locating review button for click...'); + + try { + const reviewText = String.fromCharCode(21830, 21697, 35780, 20215); // 商品评价 + const reviewTextShort = String.fromCharCode(35780, 20215); // 评价 + let reviewBtn = null; + + // Strategy 1: XPath + try { + const xpath = `//*[contains(text(), '${reviewTextShort}')]`; + const result = document.evaluate(xpath, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); + for (let i = 0; i < result.snapshotLength; i++) { + const el = result.snapshotItem(i); + if (el.tagName === 'SCRIPT' || el.tagName === 'STYLE') continue; + const text = el.innerText || el.textContent; + if (text && text.length < 30 && (text.includes(reviewText) || text.includes(reviewTextShort))) { + reviewBtn = el; + console.log('[Reviews] Found button via XPath strategy.'); + break; + } + } + } catch(e) {} + + // Strategy 2: DOM Scan + if (!reviewBtn) { + const allElements = Array.from(document.querySelectorAll('div, span, p, a, button')); + reviewBtn = allElements.find(el => { + const text = el.innerText || el.textContent || ''; + return (text.includes(reviewText) || text.includes(reviewTextShort)) && text.length < 20; + }); + if (reviewBtn) console.log('[Reviews] Found button via DOM Scan strategy.'); + } + + // Strategy 3: Regex + if (!reviewBtn) { + const allElements = Array.from(document.querySelectorAll('div, span, p')); + for (const el of allElements) { + const text = el.innerText || ''; + if (text.match(/(\d+)\+?\s*[\u8bc4\u4ef7]/) && text.length < 15) { + reviewBtn = el; + console.log('[Reviews] Found button via Regex strategy.'); + break; + } + } + } + + if (reviewBtn) { + console.log(`[Reviews] Found button, clicking...`); + reviewBtn.scrollIntoView({ behavior: 'smooth', block: 'center' }); + await wait(800); + + try { + const touchStart = new Event('touchstart', { bubbles: true, cancelable: true }); + const touchEnd = new Event('touchend', { bubbles: true, cancelable: true }); + reviewBtn.dispatchEvent(touchStart); + reviewBtn.dispatchEvent(touchEnd); + await wait(100); + reviewBtn.click(); + } catch (err) { + reviewBtn.click(); + } + } else { + console.log('[Reviews] Button not found in Click step.'); + } + } catch (e) { + console.log(`[Reviews] Error clicking reviews: ${e.message}`); + } + }, [], 12); + + console.log('[Reviews] Click action completed. Waiting 5s for navigation...'); + await new Promise(r => setTimeout(r, 5000)); + } + + // --- PART 2B: EXTRACT REVIEWS (Separate Context) --- + let reviews = []; + if (data.hasReviews) { - // Calculate target position (either more products div or bottom of body) - const targetTop = moreProductsDiv ? moreProductsDiv.getBoundingClientRect().top + window.scrollY : document.body.scrollHeight; - const startScroll = window.scrollY; - const distance = targetTop - startScroll; - const steps = 30; // Number of steps - const stepSize = distance / steps; + console.log('[Reviews] Starting review extraction (New Context)...'); + // Pass scroll limit flag: if count < 5, don't scroll deeply + const shouldDeepScroll = !data.reviewCount || data.reviewCount > 5; - // Perform slow scroll - for (let i = 0; i < steps; i++) { - window.scrollBy(0, stepSize); - // Random wait between 100ms and 300ms - await wait(100 + Math.random() * 200); - } - await wait(2000); // Final wait for images to render + reviews = await safeEvaluate(newPage, async (shouldDeepScroll) => { + console.log('[Reviews] Inside safeEvaluate. Deep Scroll:', shouldDeepScroll); + const wait = (ms) => new Promise(r => setTimeout(r, ms)); + const extractedReviews = []; + try { + // Scroll Logic + const reviewContent = document.querySelector('.comment-item') || document.querySelector('img[src*="avatar"]'); + if (!reviewContent) { + console.log('[Reviews] Review content not immediately visible, waiting...'); + await wait(2000); + } - // Step C: Extract images STRICTLY from specific nested path - // Priority 1: User-identified container "Blmqu2TV" - const blmContainer = document.querySelector('.Blmqu2TV') || document.querySelector('div[class*="Blmqu2TV"]'); - let foundDescImages = false; + console.log(`[Reviews] Starting scroll sequence (Forced 8 screens)...`); + const scrollLoops = 8; // User requested fixed 8 screens down + + for (let i = 0; i < scrollLoops; i++) { + const startY = window.scrollY; + window.scrollBy(0, window.innerHeight); + await wait(1500 + Math.random() * 500); // Increased wait time for image loading + const endY = window.scrollY; + + // Check if scroll happened + if (Math.abs(endY - startY) < 10) { + console.log('[Reviews] Window scroll failed, trying container scroll...'); + + // OPTIMIZATION: Don't scan all divs. Look for likely containers. + // 1. Try finding a div with 'scroll' class or style + // 2. Or just pick the largest div + const likelyContainers = Array.from(document.querySelectorAll('div[class*="container"], div[class*="list"], div[class*="scroll"], .main, #main')); + + let scrollable = likelyContainers.find(d => { + const style = window.getComputedStyle(d); + return (style.overflowY === 'auto' || style.overflowY === 'scroll') && d.scrollHeight > d.clientHeight; + }); - if (blmContainer) { - console.log('[PDD] Found Blmqu2TV container for description images'); - const imgs = Array.from(blmContainer.querySelectorAll('img')); - - imgs.forEach(img => { - // STRICT EXCLUSION - if (img.closest('a[href*="goods_id"]')) return; - if (img.closest('.recommend-goods')) return; + // Fallback: If no obvious container, try the body or root element + if (!scrollable) { + const body = document.body; + if (body.scrollHeight > body.clientHeight) scrollable = body; + } - // User provided example: data-src is primary - let src = img.getAttribute('data-src') || img.getAttribute('src') || img.src; + if (scrollable) { + console.log('[Reviews] Found scrollable container:', scrollable.className); + scrollable.scrollBy(0, 500); + await wait(500); + } else { + console.log('[Reviews] No scrollable container found.'); + } + } + } + + console.log('[Reviews] Extracting reviews...'); - if (src && !src.startsWith('data:')) { - src = src.split('?')[0]; - if (src.startsWith('//')) src = 'https:' + src; + // Strategy 0: User-Provided Specific Selectors (Priority) + // Review Item: div.LFMbudEX + // Name: span.BQX0_Yxu + // Variant: span.X2uOYqB0 + // Comment: .dTH6vA6C + // Photos: div.db85mmgV + + const specificReviewItems = document.querySelectorAll('div.LFMbudEX'); + if (specificReviewItems && specificReviewItems.length > 0) { + console.log(`[Reviews] Found ${specificReviewItems.length} reviews using specific selector (div.LFMbudEX).`); + + specificReviewItems.forEach(item => { + try { + // Name + const nameEl = item.querySelector('span.BQX0_Yxu'); + const name = nameEl ? nameEl.innerText.trim() : 'Pinduoduo Shopper'; + + // Variant/Option + const variantEl = item.querySelector('span.X2uOYqB0'); + const variantText = variantEl ? variantEl.innerText.trim() : ''; + + // Comment + const commentEl = item.querySelector('.dTH6vA6C'); + let comment = commentEl ? commentEl.innerText.trim() : ''; + + // Append variant to comment if exists (so it's visible) + if (variantText) { + comment = comment ? `${comment}\n(Option: ${variantText})` : `(Option: ${variantText})`; + } + + // Photos: div.db85mmgV -> div.x0U3sYw6 -> img + const photoContainer = item.querySelector('div.db85mmgV'); + let photos = []; + if (photoContainer) { + // Check specifically for the image wrapper class provided by user + const photoWrappers = photoContainer.querySelectorAll('div.x0U3sYw6'); + + if (photoWrappers && photoWrappers.length > 0) { + photos = Array.from(photoWrappers) + .map(w => { + const img = w.querySelector('img'); + return img ? (img.getAttribute('data-src') || img.src) : null; + }) + .filter(src => src && !src.includes('avatar') && !src.startsWith('data:')) + .map(src => src.split('?')[0]); + } else { + // Fallback to direct image search if wrapper class changes + photos = Array.from(photoContainer.querySelectorAll('img')) + .filter(img => img.naturalWidth > 50 && !img.src.includes('avatar')) + .map(img => img.src.split('?')[0]); + } + } + + if (comment || photos.length > 0) { + extractedReviews.push({ name, comment, photos: [...new Set(photos)] }); + } + } catch (err) { + console.log('[Reviews] Error extracting specific review item:', err.message); + } + }); + } else { + console.log('[Reviews] Specific selector (div.LFMbudEX) not found. Trying fallback strategy...'); - if (src.startsWith('http') && !src.includes('avatar') && !src.includes('icon') && !src.includes('video-snapshot') && !src.includes('coupon') && !src.includes('.slim.png')) { - // Optional: Check for size if possible, but data-src usually implies main content - product_desc_imgs.push(src); + // Strategy 1: Group elements by class name (Fallback) + const candidates = Array.from(document.querySelectorAll('div')); + const classCounts = {}; + + // Limit candidates to first 2000 to avoid freezing + const limit = Math.min(candidates.length, 2000); + + for (let i=0; i 5) { + const c = d.className; + if (!classCounts[c]) classCounts[c] = []; + classCounts[c].push(d); + } + } + + let bestClass = null; + let maxCount = 0; + for (const [cls, items] of Object.entries(classCounts)) { + if (items.length > 1) { + const first = items[0]; + const text = first.innerText.trim(); + // Check for images inside + const imgs = first.querySelectorAll('img'); + const hasValidImg = Array.from(imgs).some(img => img.naturalWidth > 50 && !img.src.includes('avatar')); + + if (text.length > 5 && (hasValidImg || items.length > 3)) { + if (items.length > maxCount) { maxCount = items.length; bestClass = cls; } + } + } + } + + if (bestClass) { + console.log(`[Reviews] Best review class: ${bestClass} (Count: ${maxCount})`); + const items = classCounts[bestClass]; + items.forEach(item => { + const text = item.innerText.trim(); + const imgs = Array.from(item.querySelectorAll('img')).filter(img => img.naturalWidth > 50 && !img.src.includes('avatar')).map(img => img.src.split('?')[0]); + if (text && (imgs.length > 0 || text.length > 10)) { + const lines = text.split('\n').map(l => l.trim()).filter(l => l); + let name = 'Pinduoduo Shopper'; + let comment = text; + if (lines.length > 1 && lines[0].length < 20) { name = lines[0]; comment = lines.slice(1).join(' '); } + extractedReviews.push({ name, comment, photos: [...new Set(imgs)] }); + } + }); + } else { + console.log('[Reviews] No best class found. Fallback to image scan.'); + const visibleImgs = Array.from(document.querySelectorAll('img')).filter(img => img.naturalWidth > 100 && !img.src.includes('avatar')).map(img => img.src.split('?')[0]); + const uniqueImgs = [...new Set(visibleImgs)]; + for (let i = 0; i < uniqueImgs.length; i += 3) { + extractedReviews.push({ + name: 'Pinduoduo Shopper', + comment: '\u0635\u0648\u0631 \u0645\u0646 \u062a\u0642\u064a\u064a\u0645\u0627\u062a \u0627\u0644\u0639\u0645\u0644\u0627\u0621', // Photos from customer reviews + photos: uniqueImgs.slice(i, i+3) + }); + } } } - }); - - if (product_desc_imgs.length > 0) foundDescImages = true; - } - // Priority 2: Old strict selector if Blmqu2TV failed - if (!foundDescImages) { - // User hint: #main > div > div.GNrMaxlJ > div:nth-child(19) > div - const descContainer = document.querySelector('#main > div > div.GNrMaxlJ > div:nth-child(19) > div'); + console.log(`[Reviews] Extracted ${extractedReviews.length} reviews.`); + + // Go Back + console.log('[Reviews] Going back...'); + const backBtnText = String.fromCharCode(36820, 22238); // 返回 + const backBtn = document.querySelector(`div[role="button"][aria-label*="${backBtnText}"]`) || + document.querySelector('[data-testid="back-button"]') || + Array.from(document.querySelectorAll('div, span')).find(el => el.innerText === backBtnText); + + if (backBtn) backBtn.click(); + else window.history.back(); + + } catch (e) { console.log('Review error:', e.message); } + return extractedReviews; + }, [shouldDeepScroll], 12); - if (descContainer) { - // console.log('Found description container, extracting nested images...'); - // Re-query children after scroll - const nestedDivs = Array.from(descContainer.querySelectorAll('div')); + console.log(`[Reviews] Extracted ${reviews.length} reviews. Waiting 2s for back navigation...`); + await new Promise(r => setTimeout(r, 2000)); + } + data.reviews = reviews; + + // --- TRANSLATE REVIEWS (BATCHED) --- + if (data.reviews && data.reviews.length > 0 && aiClient) { + const reviewsToTranslate = data.reviews.slice(0, 15); // Top 15 + console.log(`[Reviews] Translating top ${reviewsToTranslate.length} reviews to Arabic...`); + + const reviewBatches = []; + // Reduced batch size to prevent token limit truncation + for (let i = 0; i < reviewsToTranslate.length; i += 3) { + reviewBatches.push(reviewsToTranslate.slice(i, i + 3)); + } + + const translatedReviews = []; + + for (const batch of reviewBatches) { + const batchContent = JSON.stringify(batch.map(r => ({ n: r.name, c: r.comment }))); + const prompt = ` + Translate these product reviews to Arabic (Iraqi dialect preferred for comments). + Input: ${batchContent} + + IMPORTANT: + - Return ONLY a raw JSON array. + - NO markdown blocks (do not use \`\`\`json). + - Keep the order EXACTLY the same. + - Each item: {"n": "Translated Name", "c": "Translated Comment"} + - "Pinduoduo Shopper" -> "متسوق" or similar. + - "Photos from customer reviews" -> "صور من تقييمات العملاء" + `; + + try { + const res = await aiClient.chat.completions.create({ + model: AI_PRIMARY_MODEL, + messages: [{ role: "user", content: prompt }], + temperature: 0.4, + max_tokens: 2500 // Increased to prevent truncation + }); + + let jsonStr = res.choices[0].message.content.replace(/```json/g, '').replace(/```/g, '').trim(); + const start = jsonStr.indexOf('['); + const end = jsonStr.lastIndexOf(']'); - // If we fell back to main container, just get all images directly too - const directImages = Array.from(descContainer.querySelectorAll('img')); + if (start !== -1) { + if (end !== -1 && end > start) { + jsonStr = jsonStr.substring(start, end + 1); + } else { + // No closing bracket found, or it's before start. Likely truncated. + // Keep from start to end of string to attempt repair later. + jsonStr = jsonStr.substring(start); + } + } else { + // If no array found, try to find single object and wrap in array + const startObj = jsonStr.indexOf('{'); + const endObj = jsonStr.lastIndexOf('}'); + if (startObj !== -1 && endObj !== -1) { + jsonStr = `[${jsonStr.substring(startObj, endObj + 1)}]`; + } + } - const processImg = (img) => { - let src = img.src || img.dataset.src; - if (src && !src.startsWith('data:') && img.naturalWidth > 400) { - // Check for lazy loaded attributes often used in PDD - if (src.includes('blank.gif') || src.includes('loading')) { - if (img.dataset.src) src = img.dataset.src; - } - - // STRICT EXCLUSION: Suggested/Recommended Products - // If the image is inside a link to another product, skip it - if (img.closest('a[href*="goods_id"]')) return; - if (img.closest('.recommend-goods')) return; - - if (src && !src.includes('avatar') && !src.includes('icon') && !src.includes('video-snapshot') && !src.includes('coupon') && !src.includes('.slim.png')) { - product_desc_imgs.push(src.split('?')[0]); + // Escape unescaped double quotes within string values + // This is a heuristic and might need refinement + // jsonStr = jsonStr.replace(/(? { - const imgs = div.querySelectorAll('img'); - imgs.forEach(processImg); - }); - - directImages.forEach(processImg); - if (product_desc_imgs.length > 0) foundDescImages = true; - } - } + } + + if (Array.isArray(transBatch) && transBatch.length > 0) { + batch.forEach((r, idx) => { + if (idx < transBatch.length) { + translatedReviews.push({ + ...r, + name: transBatch[idx].n || r.name, + comment: transBatch[idx].c || r.comment + }); + } else { + // Fallback for missing translations (truncated items) + console.log(`[Reviews] Item ${idx} missing translation (likely truncated). Using original.`); + translatedReviews.push(r); + } + }); + } else { + // Fallback: use original + console.log('[Reviews] Translation failed or invalid format. Using original reviews.'); + translatedReviews.push(...batch); + } + + } catch (e) { + console.log('[Reviews] Translation error:', e.message); + translatedReviews.push(...batch); + } + + // Rate Limit Buffer to avoid 429 + await new Promise(r => setTimeout(r, 1000)); + } + + data.reviews = translatedReviews; + console.log(`[Reviews] Translation complete. ${data.reviews.length} reviews ready.`); + } + + // --- ENSURE NAVIGATION BACK TO MAIN PAGE --- + try { + const isMainPage = await newPage.evaluate(() => { + // Check for common main page elements: Title, Price, or Bottom Bar buttons + return !!document.querySelector('.goods-details-title') || + !!document.querySelector('.enable-select') || // Price/Title area often has this + !!document.querySelector('div[aria-label="收藏"]') || // Favorite button + !!document.querySelector('div[aria-label="客服"]'); // Customer service + }); + + if (!isMainPage && data.hasReviews) { + console.log('[Reviews] Not on main page after review extraction. Forcing browser back navigation...'); + await newPage.goBack(); + await wait(3000); + } + } catch (e) { + console.log('[Reviews] Error checking page state:', e.message); + } + + // --- PART 3: DESCRIPTION IMAGES (Separate Context) --- + console.log('[Description] Starting description image extraction (New Context)...'); + const product_desc_imgs = await safeEvaluate(newPage, async () => { + const wait = (ms) => new Promise(r => setTimeout(r, ms)); + const imgs = []; - if (!foundDescImages) { - // STRICT FALLBACK: If specific container not found, try to find the "Details" section specifically - // Pinduoduo usually has a "Goods Details" or "Graphic Details" header - // We look for a container that has many large images and is NOT the slider - console.log('Specific container not found, attempting strict fallback...'); - const potentialContainers = Array.from(document.querySelectorAll('.GNrMaxlJ > div')); - // Usually the description is near the bottom, often the last or second to last div - // We can also look for a div that contains mostly images - - for (const div of potentialContainers) { - const imgs = div.querySelectorAll('img'); - if (imgs.length > 2) { - // Check if images are large - let largeImgs = 0; - imgs.forEach(img => { if (img.naturalWidth > 400) largeImgs++; }); - if (largeImgs > 2) { - imgs.forEach(img => { - if (img.naturalWidth > 400) { - let src = img.src || img.dataset.src; - if (src && !src.includes('avatar') && !src.includes('icon') && !src.includes('video-snapshot') && !src.includes('coupon')) { - product_desc_imgs.push(src.split('?')[0]); - } - } - }); - break; // Found one good container, stop - } + // Scroll + console.log('[Description] Scrolling...'); + const steps = 20; + const stepSize = document.body.scrollHeight / steps; + for (let i = 0; i < steps; i++) { + window.scrollBy(0, stepSize); + await wait(100); + } + await wait(2000); + + // Extract + const allImgs = Array.from(document.querySelectorAll('img')); + allImgs.forEach(img => { + let src = img.getAttribute('data-src') || img.src; + if (src && !src.startsWith('data:') && img.naturalWidth > 300) { + if (!src.includes('avatar') && !src.includes('icon')) { + imgs.push(src.split('?')[0]); } } - } - - return { title, price, description, images: [...new Set(images)], variants, skuMap, skuThumbMap, productDetails, product_desc_imgs: [...new Set(product_desc_imgs)], variantImages }; - }, [], 12); + }); + return [...new Set(imgs)]; + }); + data.product_desc_imgs = product_desc_imgs; // Enrich console.log(`Enriching: ${data.title.substring(0, 20)}...`); @@ -2582,16 +3126,8 @@ async function run() { if (data.skuMap && Object.keys(data.skuMap).length > 0) { const rawVariantEntries = Object.entries(data.skuMap || {}); - console.log(`Variant prices BEFORE translation (${rawVariantEntries.length})`); - const rawPreviewLimit = 80; - rawVariantEntries.slice(0, rawPreviewLimit).forEach(([k, v]) => { - const m = String(v || '').match(/(\d+(\.\d+)?)/); - const p = m ? Math.round(parseFloat(m[1]) * 200) : 0; - console.log(` ${k} => ${v} (${p} IQD)`); - }); - if (rawVariantEntries.length > rawPreviewLimit) { - console.log(` ... truncated ${rawVariantEntries.length - rawPreviewLimit} more`); - } + // console.log(`Variant prices BEFORE translation (${rawVariantEntries.length})`); + const rawPreviewLimit = 5; // Reduced limit // Helper to translate color/size via AI if possible, or simple mapping // Since we want strict Arabic, we might need a quick AI pass or just use the aiData logic @@ -2622,19 +3158,19 @@ async function run() { color = String(color || '') .replace(/\n.*$/, '') - .replace(/【.*?】/g, '') + .replace(/م€گ.*?م€‘/g, '') .replace(/\s+/g, ' ') .trim(); if (size) { size = String(size || ''); - size = size.replace(/(\d+(\.\d+)?)\s*[-~]\s*(\d+(\.\d+)?)\s*斤/g, (m, p1, p2, p3) => { + size = size.replace(/(\d+(\.\d+)?)\s*[-~]\s*(\d+(\.\d+)?)\s*و–¤/g, (m, p1, p2, p3) => { const start = parseFloat(p1) / 2; const end = parseFloat(p3) / 2; return `${start}-${end}kg`; }); - size = size.replace(/(\d+(\.\d+)?)\s*斤/g, (m, p1) => `${parseFloat(p1) / 2}kg`); - size = size.replace(/\n.*$/, '').replace(/【.*?】/g, '').replace(/\s+/g, ' ').trim(); + size = size.replace(/(\d+(\.\d+)?)\s*و–¤/g, (m, p1) => `${parseFloat(p1) / 2}kg`); + size = size.replace(/\n.*$/, '').replace(/م€گ.*?م€‘/g, '').replace(/\s+/g, ' ').trim(); if (!size) size = null; } @@ -2647,6 +3183,12 @@ async function run() { } console.log(`Generated options from SKU map (${generated_options.length})`); + + // LIMIT OPTIONS: If more than 50, limit to 50 + if (generated_options.length > 50) { + console.log(`[Options] Too many options (${generated_options.length}). Limiting to 50.`); + generated_options = generated_options.slice(0, 50); + } // --- TRANSLATE OPTIONS IF AI IS AVAILABLE --- if (aiClient && generated_options.length > 0) { @@ -2664,14 +3206,14 @@ async function run() { - Keep the order EXACTLY the same as input. - Each output item must be {"c": "...", "s": "..."}. - If the input contains "kg" (kilograms), KEEP "kg" in the translation (e.g. "80kg" -> "80kg" or "80 كغم"). - - Do NOT convert numbers back to original units. - - Remove any Chinese characters or marketing text like "快要断码", "图片色" (Image Color), "高质量", "建议", "斤". - - "图片色" or "默认" should be translated as "كما في الصورة" (As shown in image) or "اللون الافتراضي" (Default Color). - - Remove any newlines or extra whitespace. - - Return pure, clean Arabic names for colors and sizes. - - TRANSLATE COLORS TO ARABIC (e.g. "Black" -> "أسود", "红色" -> "أحمر"). - - TRANSLATE "建议" (Recommended) to "مقترح" or remove it if just a label. - - STRICTLY REMOVE any "return policy", "refund", "replacement" (e.g. "包退", "包换") text from option names. + - Do NOT convert numbers back to original units. + - Remove any Chinese characters or marketing text like "快要断码", "图片色" (Image Color), "高质量", "建议", "斤". + - "图片色" or "默认" should be translated as "كما في الصورة" (As shown in image) or "اللون الافتراضي" (Default Color). + - Remove any newlines or extra whitespace. + - Return pure, clean Arabic names for colors and sizes. + - TRANSLATE COLORS TO ARABIC (e.g. "Black" -> "أسود", "红色" -> "أحمر"). + - TRANSLATE "建议" (Recommended) to "مقترح" or remove it if just a label. + - STRICTLY REMOVE any "return policy", "refund", "replacement" (e.g. "包退", "包换") text from option names. `; const translate = async (model) => { @@ -2763,7 +3305,8 @@ async function run() { console.log('Skipping options translation (AI not ready or no options).'); } - console.log(`Variant prices AFTER translation (${generated_options.length})`); + // console.log(`Variant prices AFTER translation (${generated_options.length})`); + /* const postLines = []; for (const opt of generated_options) { const s = (opt.sizes && opt.sizes[0]) ? opt.sizes[0] : ''; @@ -2772,8 +3315,24 @@ async function run() { const postPreviewLimit = 120; postLines.slice(0, postPreviewLimit).forEach(l => console.log(` ${l}`)); if (postLines.length > postPreviewLimit) console.log(` ... truncated ${postLines.length - postPreviewLimit} more`); + */ + console.log(`> Processed ${generated_options.length} variants.`); } + + + // --- FIX: If general_price is 0 but we have options with prices, use the min option price --- + if (general_price <= 0 && generated_options.length > 0) { + const validOptionPrices = generated_options + .map(o => o.price) + .filter(p => p > 0); + + if (validOptionPrices.length > 0) { + general_price = Math.min(...validOptionPrices); + console.log(`[Price Fix] General price was 0, updated to ${general_price} from minimum option price.`); + } + } + const enrichedProduct = { product_name: aiData.product_name_ar || 'اسم غير متوفر', // original_name: data.title, // REMOVED as per request @@ -2785,7 +3344,8 @@ async function run() { product_desc_imgs: data.product_desc_imgs || [], // Description Images general_price: general_price, generated_options: generated_options, // New Field - aiMetadata: aiData.aiMetadata || {}, + scrapedReviews: data.reviews || [], // Store reviews at top level (renamed from reviews) + aiMetadata: { ...(aiData.aiMetadata || {}) }, // Removed reviews from here isAirRestricted: aiData.isAirRestricted || false, // New Field // variants: data.variants, // REMOVED as per request // skuMap: data.skuMap // REMOVED as per request @@ -2819,7 +3379,7 @@ async function run() { fs.writeFileSync(OUTPUT_FILE, JSON.stringify(products, null, 2)); // --- DATABASE INSERTION --- - console.log('Inserting into Database...'); + // console.log('Inserting into Database...'); try { // 1. Create Product const newProduct = await prisma.product.create({ @@ -2831,7 +3391,8 @@ async function run() { purchaseUrl: enrichedProduct.url, specs: JSON.stringify(enrichedProduct.product_details || {}), aiMetadata: enrichedProduct.aiMetadata || {}, - isAirRestricted: enrichedProduct.isAirRestricted, // Save to DB + scrapedReviews: enrichedProduct.scrapedReviews || [], // Save reviews to DB + isAirRestricted: enrichedProduct.isAirRestricted || false, // Save to DB status: "PUBLISHED", isActive: true, } @@ -2987,7 +3548,17 @@ async function run() { data: variantsData }); } - console.log('Database insertion complete.'); + // console.log('Database insertion complete.'); + + // Generate and save embedding for new product + if (newProduct && newProduct.id) { + try { + // console.log('Triggers the embedding...'); + await processProductEmbedding(newProduct.id); + } catch (embedErr) { + console.error(`Embedding generation failed for product ${newProduct.id} (non-fatal):`, embedErr.message); + } + } } catch (dbErr) { console.error('Database Insertion Failed:', dbErr.message); @@ -3002,24 +3573,71 @@ async function run() { // Clean up if (!navigationHappened) { - await newPage.close(); + try { + if (newPage && !newPage.isClosed()) await newPage.close(); + } catch(e) { console.log('Error closing tab:', e.message); } + try { await page.bringToFront(); } catch(e){} } else { console.log('Going back to category page...'); - await page.goBack({ waitUntil: 'domcontentloaded' }); + const previousUrl = page.url(); + try { + await page.goBack({ waitUntil: 'domcontentloaded', timeout: 15000 }); + } catch (e) { + console.log('goBack failed or timed out:', e.message); + } + await humanDelay(2000, 3000); - } - await humanDelay(2000, 5000); + // ROBUSTNESS CHECK: Did we actually go back? + const isCategoryUrl = (url) => { + if (!url) return false; + return url.includes('catgoods') || url.includes('search_result') || url.includes('subjects') || url.includes('search') || url.includes('opt'); + }; + const isProductUrl = (url) => { + if (!url) return false; + return url.includes('goods_id') || url.includes('goods.html') || url.includes('goods_detail'); + }; + + let currentUrl = page.url(); + let isCategoryPage = isCategoryUrl(currentUrl) && !isProductUrl(currentUrl); + + for (let attempt = 1; attempt <= 3 && !isCategoryPage; attempt++) { + console.log(`⚠️ Not back on category page yet. Going back again (${attempt}/3)...`); + try { + await page.goBack({ waitUntil: 'domcontentloaded', timeout: 15000 }); + } catch (e) { + console.log('goBack failed or timed out:', e.message); + } + await humanDelay(2000, 3000); + currentUrl = page.url(); + isCategoryPage = isCategoryUrl(currentUrl) && !isProductUrl(currentUrl); + if (currentUrl === previousUrl) break; + } + + if (!isCategoryPage) { + console.log('⚠️ Could not reach category page after back attempts.'); + } + } // Random Delay between 10-15 seconds before next item - const nextItemDelay = 10000 + Math.random() * 5000; + const fixedDelayMs = Number(process.env.PDD_NEXT_ITEM_DELAY_MS || 0); + const minDelayMs = Number(process.env.PDD_NEXT_ITEM_DELAY_MIN_MS || 10000); + const maxDelayMs = Number(process.env.PDD_NEXT_ITEM_DELAY_MAX_MS || 15000); + const nextItemDelay = fixedDelayMs > 0 ? fixedDelayMs : (minDelayMs + Math.random() * Math.max(0, (maxDelayMs - minDelayMs))); console.log(`Waiting ${(nextItemDelay/1000).toFixed(1)}s before next item...`); await delay(nextItemDelay); } // End of 4-click loop - // Scroll down to load more items for next pass - console.log('Finished batch of 4 clicks. Scrolling for more items...'); - await autoScroll(page); + console.log('Scrolling down one screen...'); + try { + await page.evaluate(() => window.scrollBy(0, window.innerHeight)); + // Update accumulatedScrollY for drift restoration + try { + accumulatedScrollY = await page.evaluate(() => window.scrollY); + } catch (e) {} + } catch (e) { + console.log('Scroll error:', e.message); + } await humanDelay(3000, 5000); } diff --git a/server/services/aiService.js b/server/services/aiService.js index c5aef7a818750d7ee2646ff552eb70ef60889472..17520c0bfd78441cc8b1f3dcd8a30d3052829723 100644 --- a/server/services/aiService.js +++ b/server/services/aiService.js @@ -40,7 +40,18 @@ function getClients() { baseURL: "https://api.siliconflow.cn/v1", apiKey: process.env.SILICONFLOW_API_KEY, }); + // Monkey-patch baseURL for detection later + siliconflow.baseURL = "https://api.siliconflow.cn/v1"; console.log(`[AI Debug] SiliconFlow initialized (OpenAI-compatible)`); + } else if (process.env.DEEPINFRA_API_KEY) { + // Fallback to DeepInfra if SiliconFlow is not set + siliconflow = new OpenAI({ + baseURL: "https://api.deepinfra.com/v1/openai", + apiKey: process.env.DEEPINFRA_API_KEY, + }); + // Monkey-patch baseURL for detection later (OpenAI client might hide it) + siliconflow.baseURL = "https://api.deepinfra.com/v1/openai"; + console.log(`[AI Debug] DeepInfra initialized (OpenAI-compatible)`); } else { siliconflow = null; } @@ -99,12 +110,28 @@ async function generateEmbedding(text) { const generateWithSiliconFlow = async () => { if (!siliconflow) return null; - const model = process.env.SILICONFLOW_EMBEDDING_MODEL || 'Qwen/Qwen3-Embedding-0.6B'; + + // Check if we are using DeepInfra + const isDeepInfra = siliconflow.baseURL === "https://api.deepinfra.com/v1/openai"; + + // Use user-requested model for DeepInfra or fallback to env/default + let model = process.env.SILICONFLOW_EMBEDDING_MODEL || 'Qwen/Qwen3-Embedding-0.6B'; + + if (isDeepInfra) { + model = process.env.DEEPINFRA_EMBEDDING_MODEL || 'google/embeddinggemma-300m'; + } + + console.log(`[AI Debug] Generating embedding with model: ${model} (Provider: ${isDeepInfra ? 'DeepInfra' : 'SiliconFlow'})`); + const rawDimensions = process.env.SILICONFLOW_EMBEDDING_DIMENSIONS; const dimensions = rawDimensions !== undefined && rawDimensions !== null && rawDimensions !== '' ? Number(rawDimensions) : undefined; const payload = { model, input: text }; - if (Number.isFinite(dimensions) && dimensions > 0) { + + // DeepInfra might not support 'dimensions' parameter for this model, or it might be fixed. + // Only send dimensions if not using DeepInfra or if explicitly tested. + // For now, let's omit dimensions for DeepInfra to be safe unless we know it's supported. + if (!isDeepInfra && Number.isFinite(dimensions) && dimensions > 0) { payload.dimensions = dimensions; } @@ -186,7 +213,7 @@ export async function processProductEmbedding(productId) { console.log(`[AI Debug] Successfully saved embedding for product ${productId}`); } catch (error) { console.error(`[AI Debug] Embedding-only processing failed for product ${productId}:`, error.message); - if (process.env.NODE_ENV !== 'production') { + if (process.env.NODE_ENV !== 'production' && !error.message.includes('API_KEY is not defined')) { console.error(error); } throw error; diff --git a/server/simple_check.js b/server/simple_check.js new file mode 100644 index 0000000000000000000000000000000000000000..8e2b15c178da3e83e6fa8224b60dd6cd83a43fe7 --- /dev/null +++ b/server/simple_check.js @@ -0,0 +1,4 @@ + +console.log('Node is working'); +const fs = require('fs'); +fs.writeFileSync('check.txt', 'Node worked'); diff --git a/server/simple_file_write.js b/server/simple_file_write.js new file mode 100644 index 0000000000000000000000000000000000000000..88ca759ed7465833085201a607f1822f888a3cb9 --- /dev/null +++ b/server/simple_file_write.js @@ -0,0 +1,9 @@ + +const fs = require('fs'); +console.log('Writing file...'); +try { + fs.writeFileSync('e:/mynewproject2/server/simple_write.txt', 'Hello World'); + console.log('File written successfully'); +} catch (e) { + console.error('Error writing file:', e); +} diff --git a/server/simple_node_check.js b/server/simple_node_check.js new file mode 100644 index 0000000000000000000000000000000000000000..4b45a688b179ccebe8d5b6bd5ae8d88cf1a2b54c --- /dev/null +++ b/server/simple_node_check.js @@ -0,0 +1,8 @@ + +const fs = require('fs'); +try { + fs.writeFileSync('simple_node_check.txt', 'Node is working and can write files.'); + console.log('File written successfully.'); +} catch (e) { + console.error('File write failed:', e); +} diff --git a/server/start_server.bat b/server/start_server.bat new file mode 100644 index 0000000000000000000000000000000000000000..df8b664e7fc7feca9f72dbc2c928d7af327684f4 --- /dev/null +++ b/server/start_server.bat @@ -0,0 +1,4 @@ +@echo off +set PORT=5001 +echo Starting server on port %PORT%... +node index.js \ No newline at end of file diff --git a/server/test.js b/server/test.js new file mode 100644 index 0000000000000000000000000000000000000000..bff03078151278198f6338029c161e7ee86e81a6 --- /dev/null +++ b/server/test.js @@ -0,0 +1 @@ +console.log("Hello Node"); \ No newline at end of file diff --git a/server/test_db_query.js b/server/test_db_query.js new file mode 100644 index 0000000000000000000000000000000000000000..5fb8537963fe010c41a9538f7e4f7fc534d8a203 --- /dev/null +++ b/server/test_db_query.js @@ -0,0 +1,46 @@ + +import prisma from './prismaClient.js'; +import fs from 'fs'; + +async function testQuery() { + try { + console.log('Testing Product query...'); + const products = await prisma.product.findMany({ + where: { + isActive: true, + status: 'PUBLISHED' + }, + select: { + id: true, + name: true, + price: true, + basePriceIQD: true, // Uncommented + image: true, + isFeatured: true, + domesticShippingFee: true, // Uncommented + deliveryTime: true, // Uncommented + variants: { + select: { + id: true, + combination: true, + price: true, + basePriceIQD: true, // Uncommented + image: true, + } + } + }, + take: 1, + orderBy: { updatedAt: 'desc' } + }); + + console.log('Query successful:', products.length, 'products found'); + fs.writeFileSync('e:/mynewproject2/server/query_result.json', JSON.stringify(products, null, 2)); + } catch (error) { + console.error('Query failed:', error); + fs.writeFileSync('e:/mynewproject2/server/query_error.txt', error.message + '\n' + error.stack); + } finally { + await prisma.$disconnect(); + } +} + +testQuery(); diff --git a/server/verify_and_fix_column.js b/server/verify_and_fix_column.js new file mode 100644 index 0000000000000000000000000000000000000000..195d2bfbc403230a647203d09abbc4c3ad5d8064 --- /dev/null +++ b/server/verify_and_fix_column.js @@ -0,0 +1,75 @@ + +import { PrismaClient } from '@prisma/client'; +import fs from 'fs'; + +const prisma = new PrismaClient(); + +async function main() { + const output = []; + const log = (msg) => { + console.log(msg); + output.push(String(msg)); + }; + + try { + // 1. Get current connection info (masked) + const url = process.env.DATABASE_URL || 'No URL found in env'; + log(`Connecting to: ${url.replace(/:[^:@]+@/, ':***@')}`); + + // 2. Check current columns + log('\n--- Checking Columns ---'); + const columns = await prisma.$queryRawUnsafe(` + SELECT column_name, data_type + FROM information_schema.columns + WHERE table_name = 'Product' + ORDER BY column_name; + `); + + const colNames = columns.map(c => c.column_name); + log(`Columns found (${colNames.length}): ${colNames.join(', ')}`); + + if (colNames.includes('scrapedReviews')) { + log('\n✅ "scrapedReviews" column ALREADY EXISTS.'); + } else { + log('\n❌ "scrapedReviews" column MISSING. Attempting to add...'); + + try { + await prisma.$executeRawUnsafe(`ALTER TABLE "Product" ADD COLUMN IF NOT EXISTS "scrapedReviews" JSONB;`); + log('ALTER TABLE command executed.'); + + // Verify again + const verify = await prisma.$queryRawUnsafe(` + SELECT column_name + FROM information_schema.columns + WHERE table_name = 'Product' AND column_name = 'scrapedReviews'; + `); + + if (verify.length > 0) { + log('✅ Column successfully added!'); + } else { + log('❌ FAILED to add column even after command.'); + } + } catch (e) { + log(`❌ Error adding column: ${e.message}`); + } + } + + // 3. Check for any other issues (e.g., conflicting migrations) + log('\n--- Checking Migration Status (via _prisma_migrations table if exists) ---'); + try { + const migrations = await prisma.$queryRawUnsafe(`SELECT migration_name, finished_at FROM _prisma_migrations ORDER BY finished_at DESC LIMIT 5;`); + log('Recent migrations:'); + migrations.forEach(m => log(`- ${m.migration_name} (${m.finished_at})`)); + } catch (e) { + log('Could not read _prisma_migrations (this is normal if not using migrate dev): ' + e.message); + } + + } catch (e) { + log(`\n❌ CRITICAL ERROR: ${e.message}`); + } finally { + await prisma.$disconnect(); + fs.writeFileSync('db_verify_output.txt', output.join('\n')); + } +} + +main(); diff --git a/server/verify_column_added.js b/server/verify_column_added.js new file mode 100644 index 0000000000000000000000000000000000000000..73886cccbc13e5210d6ac47b063e140d3019e59d --- /dev/null +++ b/server/verify_column_added.js @@ -0,0 +1,31 @@ + +import { PrismaClient } from '@prisma/client'; +import fs from 'fs'; + +const prisma = new PrismaClient(); + +async function main() { + try { + const result = await prisma.$queryRawUnsafe(` + SELECT column_name + FROM information_schema.columns + WHERE table_name = 'Product' AND column_name = 'scrapedReviews'; + `); + + let message = ''; + if (result.length > 0) { + message = 'SUCCESS: "scrapedReviews" column exists.'; + } else { + message = 'FAILURE: "scrapedReviews" column MISSING.'; + } + console.log(message); + fs.writeFileSync('db_check_result.txt', message); + } catch (e) { + console.error('Error checking column:', e); + fs.writeFileSync('db_check_result.txt', 'ERROR: ' + e.message); + } finally { + await prisma.$disconnect(); + } +} + +main(); diff --git a/server/verify_fix.js b/server/verify_fix.js new file mode 100644 index 0000000000000000000000000000000000000000..becbd1daf675559d99158de1d804c4942bd92c75 --- /dev/null +++ b/server/verify_fix.js @@ -0,0 +1,31 @@ + +import { PrismaClient } from '@prisma/client'; +import fs from 'fs'; + +const prisma = new PrismaClient(); + +async function main() { + const output = []; + try { + const result = await prisma.$queryRawUnsafe(` + SELECT column_name + FROM information_schema.columns + WHERE table_name = 'Product' AND column_name = 'scrapedReviews'; + `); + + output.push(JSON.stringify(result)); + + if (result.length > 0) { + output.push('VERIFIED: scrapedReviews column exists.'); + } else { + output.push('FAILED: scrapedReviews column missing.'); + } + } catch (e) { + output.push('ERROR: ' + e.message); + } finally { + await prisma.$disconnect(); + fs.writeFileSync('db_verify.txt', output.join('\n')); + } +} + +main(); diff --git a/src/components/product/ProductActionSheet.tsx b/src/components/product/ProductActionSheet.tsx index ca494d642141748d7cb19ca9f9fd72f2d1994a03..eec7e4aa39c161a53d75bef803c96dbed7508973 100644 --- a/src/components/product/ProductActionSheet.tsx +++ b/src/components/product/ProductActionSheet.tsx @@ -2,6 +2,7 @@ import React, { useEffect } from 'react'; import { motion, AnimatePresence } from 'framer-motion'; import { X, Plane, Ship, ZoomIn, ShoppingCart, RefreshCw } from 'lucide-react'; import ProductOptions from './ProductOptions'; +import { fixMojibake } from '../../utils/mojibakeFixer'; interface ProductActionSheetProps { isOpen: boolean; @@ -104,11 +105,11 @@ const ProductActionSheet: React.FC = ({

- {product?.name} + {fixMojibake(product?.name)}

{currentVariant && (

- المحدد: {Object.values(selectedOptions).join(' / ')} + المحدد: {Object.values(selectedOptions).map(v => fixMojibake(v)).join(' / ')}

)} diff --git a/src/components/product/ProductDescription.tsx b/src/components/product/ProductDescription.tsx index 08b4e722714cc29058160f346294dd5224ad4a00..ea18fc0a72b667d81816ebc3842df78bce921e9c 100644 --- a/src/components/product/ProductDescription.tsx +++ b/src/components/product/ProductDescription.tsx @@ -1,4 +1,5 @@ import React from 'react'; +import { fixMojibake } from '../../utils/mojibakeFixer'; interface ProductDescriptionProps { productName?: string; @@ -61,11 +62,11 @@ const ProductDescription: React.FC = ({ parsedSpecs = specsData.map(item => { if (typeof item === 'object' && item !== null) { return { - label: item.label || item.name || item.key || '', - value: String(item.value || item.val || '') + label: fixMojibake(item.label || item.name || item.key || ''), + value: fixMojibake(String(item.value || item.val || '')) }; } - return { label: '', value: String(item) }; + return { label: '', value: fixMojibake(String(item)) }; }).filter(item => item.value); } else if (typeof specsData === 'string') { parsedSpecs = specsData.split('\n') @@ -73,18 +74,18 @@ const ProductDescription: React.FC = ({ const parts = line.split(':'); if (parts.length >= 2) { return { - label: parts[0].trim(), - value: parts.slice(1).join(':').trim() + label: fixMojibake(parts[0].trim()), + value: fixMojibake(parts.slice(1).join(':').trim()) }; } - return { label: '', value: line.trim() }; + return { label: '', value: fixMojibake(line.trim()) }; }) .filter(item => item.value.length > 0); } else if (typeof specsData === 'object' && specsData !== null) { parsedSpecs = Object.entries(specsData) .map(([label, value]) => ({ - label, - value: typeof value === 'object' ? JSON.stringify(value) : String(value) + label: fixMojibake(label), + value: fixMojibake(typeof value === 'object' ? JSON.stringify(value) : String(value)) })); } } @@ -113,7 +114,7 @@ const ProductDescription: React.FC = ({
{showDescription && (
- {description} + {fixMojibake(description)}
)} diff --git a/src/components/product/ProductInfo.tsx b/src/components/product/ProductInfo.tsx index f8051591e2bc598aabd63c2866035b9f5a7bdc6d..e2d8ed30d839dee0bcb0851ed063fe947a8894b1 100644 --- a/src/components/product/ProductInfo.tsx +++ b/src/components/product/ProductInfo.tsx @@ -1,5 +1,6 @@ import React from 'react'; import { calculateInclusivePrice } from '../../utils/shipping'; +import { fixMojibake } from '../../utils/mojibakeFixer'; interface ProductInfoProps { price: number; @@ -51,13 +52,13 @@ const ProductInfo: React.FC = ({
{/* Price section removed as requested */} -

{name}

+

{fixMojibake(name)}

{deliveryTime && (
- وقت تجهيز البضاعة: {deliveryTime} يوم + وقت تجهيز البضاعة: {fixMojibake(deliveryTime)} يوم
)} diff --git a/src/components/product/ProductOptions.tsx b/src/components/product/ProductOptions.tsx index 8987513de7c1f40626cf4646b691991d59f45e13..06efe4f51e8cb26d9a9500b40a8813d66b0921a1 100644 --- a/src/components/product/ProductOptions.tsx +++ b/src/components/product/ProductOptions.tsx @@ -1,5 +1,6 @@ import React from 'react'; import LazyImage from '../LazyImage'; +import { fixMojibake } from '../../utils/mojibakeFixer'; interface Option { id: number; @@ -72,7 +73,9 @@ const ProductOptions: React.FC = ({ } }); - const label = values.join('، '); // Use Arabic comma + // Fix mojibake in values + const fixedValues = values.map(v => fixMojibake(v)); + const label = fixedValues.join('، '); // Use Arabic comma // SKIP duplicates if (seenLabels.has(label)) return null; @@ -128,20 +131,21 @@ const ProductOptions: React.FC = ({ return (

- {option.name} + {fixMojibake(option.name)} {!isInformational && values && values.length > 0 && (اختر واحد)}

{values && values.map((val: any) => { - const valString = typeof val === 'object' ? (val.value || val.name || JSON.stringify(val)) : String(val); + const rawValString = typeof val === 'object' ? (val.value || val.name || JSON.stringify(val)) : String(val); + const valString = fixMojibake(rawValString); return (
!isInformational && onOptionSelect(option.name, valString)} + key={rawValString} + onClick={() => !isInformational && onOptionSelect(option.name, rawValString)} className={`px-4 py-2 rounded-xl text-xs font-bold transition-all border-2 ${ isInformational ? 'bg-slate-50 dark:bg-slate-800/50 border-slate-100 dark:border-slate-700 text-slate-600 dark:text-slate-400' - : selectedOptions[option.name] === valString + : selectedOptions[option.name] === rawValString ? 'bg-primary border-primary text-white shadow-lg shadow-primary/20 scale-105 cursor-pointer' : 'bg-white dark:bg-slate-800 border-slate-100 dark:border-white/10 text-slate-600 dark:text-slate-300 hover:border-primary/50 cursor-pointer' }`} diff --git a/src/components/product/ProductSpecs.tsx b/src/components/product/ProductSpecs.tsx index 51c2c70712d7e384aaa0b6dd408a0f47c2be3a78..19bad163287d3137230595d7bf07164f0c6c02da 100644 --- a/src/components/product/ProductSpecs.tsx +++ b/src/components/product/ProductSpecs.tsx @@ -1,4 +1,5 @@ import React from 'react'; +import { fixMojibake } from '../../utils/mojibakeFixer'; interface ProductSpecsProps { specs?: string | Record; @@ -27,11 +28,11 @@ const ProductSpecs: React.FC = ({ specs }) => { parsedSpecs = specsData.map(item => { if (typeof item === 'object' && item !== null) { return { - label: item.label || item.name || item.key || '', - value: String(item.value || item.val || '') + label: fixMojibake(item.label || item.name || item.key || ''), + value: fixMojibake(String(item.value || item.val || '')) }; } - return { label: '', value: String(item) }; + return { label: '', value: fixMojibake(String(item)) }; }).filter(item => item.value && item.value.length > 0); } else if (typeof specsData === 'string') { parsedSpecs = specsData.split('\n') @@ -39,11 +40,11 @@ const ProductSpecs: React.FC = ({ specs }) => { const parts = line.split(':'); if (parts.length >= 2) { return { - label: parts[0].trim(), - value: parts.slice(1).join(':').trim() + label: fixMojibake(parts[0].trim()), + value: fixMojibake(parts.slice(1).join(':').trim()) }; } - return { label: '', value: line.trim() }; + return { label: '', value: fixMojibake(line.trim()) }; }) .filter(item => { const label = item.label.toLowerCase(); @@ -61,8 +62,8 @@ const ProductSpecs: React.FC = ({ specs }) => { label !== 'price_rmb'; }) .map(([label, value]) => ({ - label, - value: typeof value === 'object' ? JSON.stringify(value) : String(value) + label: fixMojibake(label), + value: fixMojibake(typeof value === 'object' ? JSON.stringify(value) : String(value)) })); } diff --git a/src/components/product/ReviewsSection.tsx b/src/components/product/ReviewsSection.tsx index fa808abe8e0fc0726fced50a2f3fd31c50da4e28..7a5a49705a26ddd7de214a47f2cd4e0ddfaafc19 100644 --- a/src/components/product/ReviewsSection.tsx +++ b/src/components/product/ReviewsSection.tsx @@ -52,8 +52,8 @@ const ReviewsSection: React.FC = ({ (reviewSummary.images && reviewSummary.images.length > 0) )); - const displayReviews = reviews.slice(0, 10); - const hasMoreReviews = reviews.length > 10; + const displayReviews = reviews.slice(0, 2); + const hasMoreReviews = reviews.length > 2; if (!hasRealReviews && loading) { return ( @@ -239,28 +239,32 @@ const ReviewsSection: React.FC = ({ {/* All Reviews Modal */} {isAllReviewsModalOpen && ( -
+
setIsAllReviewsModalOpen(false)}>
e.stopPropagation()} > {/* Modal Header */} -
+

جميع التقييمات

-

تجارب حقيقية من مشتري المنتج

+

+ {reviews.length} تقييم من عملاء حقيقيين +

{/* Modal Content */} -
- {reviews.map((review, idx) => renderReviewCard(review, idx))} +
+
+ {reviews.map((review, idx) => renderReviewCard(review, idx))} +
diff --git a/src/pages/AdminDashboard.tsx b/src/pages/AdminDashboard.tsx index b516aaa408647bcbfad2333d0a6617c3703fc829..5aa505ea875a6e4482c0837d55c7a1932b6084a2 100644 --- a/src/pages/AdminDashboard.tsx +++ b/src/pages/AdminDashboard.tsx @@ -10,7 +10,7 @@ import { TrendingUp as _TrendingUp, CheckCircle2, Clock, - ArrowRight, + ArrowLeft, Download, Calendar, Eye, diff --git a/src/pages/CheckoutPaymentAddress.tsx b/src/pages/CheckoutPaymentAddress.tsx index ad3d88065567d476fa23888ac47949a2aa66306f..520cd111e172dc1bd45afe7e63efbca29bc359cf 100644 --- a/src/pages/CheckoutPaymentAddress.tsx +++ b/src/pages/CheckoutPaymentAddress.tsx @@ -1,7 +1,6 @@ import React, { useState, useEffect, useCallback } from 'react'; import { useNavigate, Link } from 'react-router-dom'; import { - ArrowRight, MapPin, ChevronLeft, MapPinPlus, diff --git a/src/pages/ProductDetails.tsx b/src/pages/ProductDetails.tsx index 6aabf10a95f6649d69c5482a6150ff1c7e5b56a6..2d447f0d696172ebbb77eafd1fd0e61928beed27 100644 --- a/src/pages/ProductDetails.tsx +++ b/src/pages/ProductDetails.tsx @@ -12,7 +12,6 @@ import LazyImage from '../components/LazyImage'; import ProductHeader from '../components/product/ProductHeader'; import ImageGallery from '../components/product/ImageGallery'; import ProductInfo from '../components/product/ProductInfo'; -import ProductOptions from '../components/product/ProductOptions'; import ProductDescription from '../components/product/ProductDescription'; import ProductSpecs from '../components/product/ProductSpecs'; import ReviewsSection from '../components/product/ReviewsSection'; @@ -29,7 +28,7 @@ interface Review { images?: string[]; } -import { AlertCircle, Package, Plane, Ship } from 'lucide-react'; +import { AlertCircle, Package } from 'lucide-react'; const ProductDetails: React.FC = () => { const navigate = useNavigate(); diff --git a/src/pages/ShippingTracking.tsx b/src/pages/ShippingTracking.tsx index 55ea05173f17b75c215528b72d4fc6f241001731..5d248085850abddbb0b9d4914468b08449d201b6 100644 --- a/src/pages/ShippingTracking.tsx +++ b/src/pages/ShippingTracking.tsx @@ -837,4 +837,4 @@ const ShippingTracking: React.FC = () => { ); }; -export default ShippingTracking; \ No newline at end of file +export default ShippingTracking; diff --git a/src/utils/mojibakeFixer.ts b/src/utils/mojibakeFixer.ts new file mode 100644 index 0000000000000000000000000000000000000000..ba63e3bb7a6aaa8d01920942ff50ab8026cb7e88 --- /dev/null +++ b/src/utils/mojibakeFixer.ts @@ -0,0 +1,53 @@ + +const MOJIBAKE_MAP: Record = { + 'ط§ظ„ظ…ط§ط±ظƒط©': 'الماركة', + 'ط§ظ„ظ„ظˆظ†': 'اللون', + 'ط§ظ„ظ…ظ‚ط§ط³': 'المقاس', + 'ط§ظ„ظ…ط§ط¯ط©': 'المادة', + 'ط§ظ„ظ…ظٹط²ط©': 'الميزة', + 'ط§ظ„طھطµظ…ظٹظ…': 'التصميم', + 'ط§ظ„ط§ط³طھط®ط¯ط§ظ…': 'الاستخدام', + 'ط§ط³ظ… ط؛ظٹط± ظ…طھظˆظپط±': 'اسم غير متوفر', + 'ط§ظ„ظ„ظˆظ† ط§ظ„ط§ظپطھط±ط§ط¶ظٹ': 'اللون الافتراضي', + 'ظƒظ…ط§ ظپظٹ ط§ظ„طµظˆط±ط©': 'كما في الصورة', + 'طھط®طµظٹطµ': 'تخصيص', + 'ط§طھطµط§ظ„': 'اتصال', + 'ط±ط§ط¨ط·': 'رابط', + 'ظپط±ظ‚': 'فرق', + 'ط¥ظٹط¯ط§ط¹': 'إيداع', + 'ظ„ط§ ظٹط±ط³ظ„': 'لا يرسل', + 'ط®ط¯ظ…ط© ط§ظ„ط¹ظ…ظ„ط§ط،': 'خدمة العملاء', + 'ظ…ط®طµطµ': 'مخصص' +}; + +export const fixMojibake = (text: string | null | undefined): string => { + if (!text) return ''; + let fixedText = text; + + // 1. Try raw replacement + for (const [bad, good] of Object.entries(MOJIBAKE_MAP)) { + if (fixedText.includes(bad)) { + fixedText = fixedText.split(bad).join(good); + } + } + + // 2. Try normalized replacement (NFC) if raw failed or for safety + if (/[\u0620-\u064A]/.test(fixedText)) { + let normalizedText = fixedText.normalize('NFC'); + let updatedNormalized = false; + + for (const [bad, good] of Object.entries(MOJIBAKE_MAP)) { + const badNormalized = bad.normalize('NFC'); + if (normalizedText.includes(badNormalized)) { + normalizedText = normalizedText.split(badNormalized).join(good); + updatedNormalized = true; + } + } + + if (updatedNormalized) { + return normalizedText; + } + } + + return fixedText; +}; diff --git a/test_write.js b/test_write.js new file mode 100644 index 0000000000000000000000000000000000000000..843eb0c9f6f738dd4fa932ce49c76cb8db662e86 --- /dev/null +++ b/test_write.js @@ -0,0 +1,3 @@ +const fs = require('fs'); +fs.writeFileSync('test_node_write.txt', 'Hello from Node!'); +console.log('Done');