From 5bbd7b4652de9a85ef05eccbdd63965e779618d9 Mon Sep 17 00:00:00 2001 From: Thomas Leiter Date: Fri, 30 Oct 2026 11:10:11 +0100 Subject: [PATCH 1/3] Add search and locations commands, fix session refresh - Add `search` command for marketplace listings with price, state, seller, PayLivery, recency, sort and raw facet filters (no login needed) - Add `locations` command to look up location ids for a postcode - `publish` resolves locationId from postCode/location; drop incorrect location ids from the docs - Store the rotated refresh token on refresh so sessions stay alive, and report an expired session instead of failing with 401 - `whoami` shows whether the session is active - `get` and `categories` work without login - Centralize client headers and update to the Android 8.67.0 identity --- LLMS.md | 56 +++++----- README.md | 61 ++++++++--- docs/.vitepress/config.ts | 2 + docs/commands/get.md | 6 +- docs/commands/index.md | 9 +- docs/commands/locations.md | 42 +++++++ docs/commands/publish.md | 9 +- docs/commands/search.md | 98 +++++++++++++++++ docs/commands/whoami.md | 4 +- src/api/application-token.ts | 39 ++----- src/api/auth.ts | 4 + src/api/categories.ts | 4 +- src/api/client.ts | 154 +++++++++++++------------- src/api/headers.ts | 41 +++++++ src/api/listings.ts | 55 +++------- src/api/locations.ts | 80 ++++++++++++++ src/api/search.ts | 200 ++++++++++++++++++++++++++++++++++ src/cli/commands/auth.ts | 19 +++- src/cli/commands/listings.ts | 30 +++-- src/cli/commands/locations.ts | 38 +++++++ src/cli/commands/search.ts | 138 +++++++++++++++++++++++ src/cli/index.ts | 4 + src/types/index.ts | 7 +- 23 files changed, 888 insertions(+), 212 deletions(-) create mode 100644 docs/commands/locations.md create mode 100644 docs/commands/search.md create mode 100644 src/api/headers.ts create mode 100644 src/api/locations.ts create mode 100644 src/api/search.ts create mode 100644 src/cli/commands/locations.ts create mode 100644 src/cli/commands/search.ts diff --git a/LLMS.md b/LLMS.md index 5eef747..c4e5306 100644 --- a/LLMS.md +++ b/LLMS.md @@ -72,7 +72,6 @@ Create a JSON file with the listing details: "price": 25, "categoryPath": ["BOOKSFILMANDMUSIC", "NON_FICTION_BOOKS"], "postCode": "8010", - "locationId": 117458, "location": "Jakomini", "condition": "gebraucht", "delivery": ["PICKUP", "Versand"] @@ -88,13 +87,13 @@ Create a JSON file with the listing details: | `price` | number | Price in EUR (use 0 for "Zu verschenken") | | `categoryPath` | string[] | Category path codes from `categories list` | | `postCode` | string | Austrian postal code (e.g., "8010") | -| `locationId` | number | District ID (see Location IDs below) | -| `location` | string | District name | #### Optional Fields | Field | Type | Description | |-------|------|-------------| +| `location` | string | Location name, required if the postcode has several locations (see below) | +| `locationId` | number | Location id, looked up automatically from `postCode` + `location` | | `condition` | string | `"neu"`, `"gebraucht"`, or `"defekt"` | | `delivery` | string[] | `["PICKUP"]`, `["Versand"]`, or both | | `street` | string | Street address | @@ -102,29 +101,14 @@ Create a JSON file with the listing details: | `contactInfo.name` | string | Contact name override | | `skipValidation` | boolean | Skip client-side validation | -#### Common Location IDs (Graz) - -| District | locationId | postCode | -|----------|------------|----------| -| Innere Stadt | 117451 | 8010 | -| St. Leonhard | 117452 | 8010 | -| Geidorf | 117453 | 8010 | -| Lend | 117454 | 8020 | -| Gries | 117455 | 8020 | -| Jakomini | 117458 | 8010 | -| Liebenau | 117459 | 8041 | -| St. Peter | 117460 | 8042 | -| Waltendorf | 117461 | 8010 | -| Ries | 117462 | 8010 | -| Mariatrost | 117463 | 8043 | -| Andritz | 117464 | 8045 | -| Gösting | 117465 | 8051 | -| Eggenberg | 117466 | 8020 | -| Wetzelsdorf | 117467 | 8052 | -| Straßgang | 117468 | 8053 | -| Puntigam | 117469 | 8055 | - -For other cities, use the postCode and a general locationId for the area. +#### Locations + +`publish` resolves the location from `postCode`. If a postcode has several locations (e.g. the districts of Graz under 8010), set `location` to one of the names listed by: + +```bash +willhaben locations 8010 +willhaben locations 8010 --json +``` ### Step 3: Publish the Listing @@ -189,6 +173,25 @@ willhaben unreserve willhaben sold ``` +## Searching Listings + +Search works without login. Use it to check comparable prices before setting a price. + +```bash +willhaben search nintendo switch --json +willhaben search fahrrad --min 100 --max 300 --state steiermark --private --sort price-asc --json + +# List available filters (categories, condition, delivery, ...) with their url params +willhaben search fahrrad --facets --json +# Apply one with --filter = (repeatable), e.g. condition "Neu": +willhaben search fahrrad --filter treeAttributes=22 --json +``` + +`--category` takes the search category id from the `category` facet (`ATTRIBUTE_TREE`). These ids are not the `categoryPath` codes used for publishing. + +States: burgenland, kaernten, niederoesterreich, oberoesterreich, salzburg, steiermark, tirol, vorarlberg, wien. +Sort: newest, nearest, price-asc, price-desc, relevance. + ## Example: Complete Listing Creation Flow ```bash @@ -210,7 +213,6 @@ cat > listing.json << 'EOF' "price": 15, "categoryPath": ["BOOKSFILMANDMUSIC", "NON_FICTION_BOOKS"], "postCode": "8010", - "locationId": 117458, "location": "Jakomini", "condition": "gebraucht", "delivery": ["PICKUP", "Versand"] diff --git a/README.md b/README.md index 4197065..cad105c 100644 --- a/README.md +++ b/README.md @@ -46,6 +46,11 @@ - Republish expired listings - Bulk operations support +**Search** +- Search marketplace listings without logging in +- Filter by price, state, seller type, condition, delivery, and category +- Postcode to location lookup for listing templates + **Image Support** - Upload single or multiple images - View listing images @@ -135,8 +140,6 @@ Create a template file `my-item.json`: "description": "Selling my iPhone 14 Pro 256GB in excellent condition...", "price": 799, "postCode": "1010", - "locationId": 900, - "location": "Wien", "categoryPath": ["MOBILE_ELECTRONICS", "MOBILE_PHONES", "IPHONE"], "condition": "gebraucht", "delivery": ["PICKUP", "Versand"] @@ -166,7 +169,7 @@ willhaben publish my-item.json | Command | Description | |---------|-------------| | `willhaben list` | List all your listings | -| `willhaben get ` | Get details of a listing | +| `willhaben get ` | Get details of a listing (yours or any public one) | | `willhaben publish ` | Create a new listing from JSON | | `willhaben update ` | Update listing properties | | `willhaben delete ` | Delete a listing | @@ -176,6 +179,13 @@ willhaben publish my-item.json | `willhaben unreserve ` | Remove reservation | | `willhaben sold ` | Mark as sold | +### Search + +| Command | Description | +|---------|-------------| +| `willhaben search [keyword...]` | Search marketplace listings (no login required) | +| `willhaben locations ` | Look up location ids for a postcode | + ### Images | Command | Description | @@ -224,6 +234,32 @@ willhaben get 123456789 --cached willhaben get 123456789 --json ``` +### Search Listings + +```bash +# Keyword search +willhaben search nintendo switch + +# Filters: price range, state, private sellers only, newest first +willhaben search fahrrad --min 100 --max 300 --state steiermark --private --sort newest + +# Show the available filters (categories, condition, delivery, ...) with hit counts +willhaben search fahrrad --facets + +# Apply a filter from --facets, e.g. condition "Neu" +willhaben search fahrrad --filter treeAttributes=22 + +# Output as JSON +willhaben search iphone --rows 50 --json +``` + +### Look Up Locations + +```bash +# Find the location for a postcode (used by listing templates) +willhaben locations 8010 +``` + ### Update Listing ```bash @@ -269,14 +305,14 @@ willhaben upload-image 123456789 photo1.jpg photo2.jpg photo3.jpg | `description` | string | Detailed description | | `price` | number | Price in EUR | | `postCode` | string | Postal code (e.g., "8010") | -| `locationId` | number | Willhaben location ID | -| `location` | string | District/city name | | `categoryPath` | string[] | Category path from root to leaf | ### Optional Fields | Field | Type | Description | |-------|------|-------------| +| `location` | string | Location name from `willhaben locations `. Needed if the postcode has several locations | +| `locationId` | number | Location id. Looked up from `postCode` and `location` if omitted | | `street` | string | Street address | | `condition` | string | `"neu"`, `"gebraucht"`, or `"defekt"` | | `delivery` | string[] | `["PICKUP"]`, `["Versand"]`, or both | @@ -295,7 +331,6 @@ willhaben upload-image 123456789 photo1.jpg photo2.jpg photo3.jpg "description": "Verkaufe meinen HP LaserJet Pro Drucker...", "price": 120, "postCode": "8010", - "locationId": 117458, "location": "Jakomini", "categoryPath": [ "COMPUTER_SOFTWARE", @@ -321,8 +356,6 @@ willhaben upload-image 123456789 photo1.jpg photo2.jpg photo3.jpg "description": "DJI Mini 3 Pro mit allem Zubehör...", "price": 750, "postCode": "1010", - "locationId": 900, - "location": "Wien", "categoryPath": [ "LEISURE_INSTRUMENTS_CULINARY", "MODEL_MAKING", @@ -348,8 +381,6 @@ willhaben upload-image 123456789 photo1.jpg photo2.jpg photo3.jpg "description": "Buch in sehr gutem Zustand...", "price": 15, "postCode": "5020", - "locationId": 30501, - "location": "Salzburg", "categoryPath": [ "BOOKSFILMANDMUSIC", "NON_FICTION_BOOKS" @@ -497,11 +528,11 @@ The API was reverse-engineered from the willhaben mobile app using [mitmproxy](h
How do I find my locationId? -Location IDs can be found in the category tree response or by inspecting the willhaben app traffic. Common IDs: -- Vienna (Wien): 900 -- Graz: 117458 -- Salzburg: 30501 -- Linz: 40101 +You usually don't need it. `publish` looks it up from `postCode`, using `location` to pick one when a postcode has several locations (e.g. the districts of Graz under 8010). To see the options: + +```bash +willhaben locations 8010 +```
diff --git a/docs/.vitepress/config.ts b/docs/.vitepress/config.ts index f0e3217..0f8fca4 100644 --- a/docs/.vitepress/config.ts +++ b/docs/.vitepress/config.ts @@ -43,6 +43,8 @@ export default defineConfig({ { text: 'update', link: '/commands/update' }, { text: 'delete', link: '/commands/delete' }, { text: 'images', link: '/commands/images' }, + { text: 'search', link: '/commands/search' }, + { text: 'locations', link: '/commands/locations' }, { text: 'config', link: '/commands/config' }, ] } diff --git a/docs/commands/get.md b/docs/commands/get.md index 30096e1..486df51 100644 --- a/docs/commands/get.md +++ b/docs/commands/get.md @@ -1,6 +1,6 @@ # get -Get detailed information about a specific listing. +Get detailed information about a listing: one of yours, or any public listing (e.g. from [`search`](/commands/search)). ## Usage @@ -77,6 +77,6 @@ willhaben get 123456789 --json } ``` -## Requires Authentication +## Authentication -You must be logged in to use this command. +Works without login for public listings. When logged in, your session is used. diff --git a/docs/commands/index.md b/docs/commands/index.md index 9a2d857..ecdbc47 100644 --- a/docs/commands/index.md +++ b/docs/commands/index.md @@ -15,11 +15,18 @@ Quick reference for all willhaben-cli commands. | Command | Description | |---------|-------------| | [`list`](/commands/list) | List all your listings | -| [`get`](/commands/get) | Get listing details | +| [`get`](/commands/get) | Get listing details (yours or any public one) | | [`publish`](/commands/publish) | Create a new listing | | [`update`](/commands/update) | Update listing properties | | [`delete`](/commands/delete) | Delete a listing | +## Search + +| Command | Description | +|---------|-------------| +| [`search`](/commands/search) | Search marketplace listings (no login required) | +| [`locations`](/commands/locations) | Look up location ids for a postcode | + ## Listing Actions | Command | Description | diff --git a/docs/commands/locations.md b/docs/commands/locations.md new file mode 100644 index 0000000..998cc50 --- /dev/null +++ b/docs/commands/locations.md @@ -0,0 +1,42 @@ +# locations + +Look up the locations for an Austrian postcode. No login required. + +[`publish`](/commands/publish) does this automatically: it resolves `locationId` from `postCode`, and uses `location` to pick one when a postcode has several locations. + +## Usage + +```bash +willhaben locations [options] +``` + +## Options + +| Option | Description | +|--------|-------------| +| `--json` | Output as JSON | + +## Example + +```bash +willhaben locations 8010 + +# Locations for postcode 8010: +# +# 117464 Andritz +# 114906 Edelsbach bei Graz +# 117455 Geidorf +# 118001 Graz +# ... +``` + +Use the name in your template: + +```json +{ + "postCode": "8010", + "location": "Geidorf" +} +``` + +Postcodes with a single location (e.g. `1010`) only need `postCode`. diff --git a/docs/commands/publish.md b/docs/commands/publish.md index 36fcfec..b599f03 100644 --- a/docs/commands/publish.md +++ b/docs/commands/publish.md @@ -30,14 +30,14 @@ willhaben publish [options] | `description` | string | Detailed description | | `price` | number | Price in EUR | | `postCode` | string | Postal code (e.g., "1010") | -| `locationId` | number | Willhaben location ID | -| `location` | string | District/city name | | `categoryPath` | string[] | Category path from root to leaf | ### Optional Fields | Field | Type | Description | |-------|------|-------------| +| `location` | string | Location name from [`locations`](/commands/locations). Needed if the postcode has several locations | +| `locationId` | number | Location id. Looked up from `postCode` and `location` if omitted | | `condition` | string | `"neu"`, `"gebraucht"`, or `"defekt"` | | `delivery` | string[] | `["PICKUP"]`, `["Versand"]`, or both | | `attributes` | object | Category-specific attributes | @@ -52,8 +52,6 @@ Create `my-item.json`: "description": "Selling my iPhone 14 Pro 256GB in excellent condition. Always used with a case and screen protector.", "price": 799, "postCode": "1010", - "locationId": 900, - "location": "Wien", "categoryPath": ["MOBILE_ELECTRONICS", "MOBILE_PHONES", "IPHONE"], "condition": "gebraucht", "delivery": ["PICKUP", "Versand"] @@ -80,7 +78,6 @@ willhaben publish my-item.json "description": "Verkaufe meinen HP LaserJet Pro Drucker...", "price": 120, "postCode": "8010", - "locationId": 117458, "location": "Graz", "categoryPath": [ "COMPUTER_SOFTWARE", @@ -106,8 +103,6 @@ willhaben publish my-item.json "description": "Buch in sehr gutem Zustand...", "price": 15, "postCode": "5020", - "locationId": 30501, - "location": "Salzburg", "categoryPath": [ "BOOKSFILMANDMUSIC", "NON_FICTION_BOOKS" diff --git a/docs/commands/search.md b/docs/commands/search.md new file mode 100644 index 0000000..5eb931a --- /dev/null +++ b/docs/commands/search.md @@ -0,0 +1,98 @@ +# search + +Search marketplace listings. No login required. + +## Usage + +```bash +willhaben search [keyword...] [options] +``` + +## Options + +| Option | Description | +|--------|-------------| +| `-c, --category ` | Search category id (from `--facets`) | +| `--min ` | Minimum price | +| `--max ` | Maximum price | +| `--state ` | `burgenland`, `kaernten`, `niederoesterreich`, `oberoesterreich`, `salzburg`, `steiermark`, `tirol`, `vorarlberg`, `wien` | +| `--private` | Only private sellers | +| `--dealer` | Only dealers | +| `--paylivery` | Only listings with PayLivery (buyer protection and shipping) | +| `--days ` | Only listings published in the last n days | +| `--sort ` | `newest`, `nearest`, `price-asc`, `price-desc`, `relevance` | +| `-p, --page ` | Page number (default: 1) | +| `-n, --rows ` | Results per page (default: 30) | +| `-f, --filter ` | Raw search filter, repeatable (see `--facets`) | +| `--facets` | Show available filters with their hit counts | +| `--json` | Output as JSON | + +## Examples + +```bash +willhaben search nintendo switch --max 150 --state steiermark --private --sort price-desc + +# 1774 listings found (page 1 of 60): +# +# € 150 Nintendo Switch Konsole +# 123456789 · 8010 Graz · 10/25/2026 +# https://www.willhaben.at/iad/kaufen-und-verkaufen/d/nintendo-switch-konsole-123456789/ +``` + +## Filters + +`--facets` lists every filter the search offers for the current query, with hit counts and the parameter to use: + +```bash +willhaben search fahrrad --facets + +# Kategorie (category) +# Sport / Sportgeräte (77090) --filter ATTRIBUTE_TREE=4390 +# ... +# Zustand (Zustand) +# Neu (13144) --filter treeAttributes=22 +``` + +Pass them back with `--filter` (repeatable). Combine with `--facets` to drill down into subcategories: + +```bash +willhaben search fahrrad --category 4390 --facets +willhaben search fahrrad --filter ATTRIBUTE_TREE=4525 --filter treeAttributes=22 +``` + +::: tip +Search category ids are not the `categoryPath` codes used for [`publish`](/commands/publish). Use [`categories`](/commands/) to find those. +::: + +## JSON Output + +```bash +willhaben search fahrrad --rows 1 --json +``` + +```json +{ + "total": 93220, + "page": 1, + "rows": 1, + "ads": [ + { + "id": "123456789", + "title": "Kinderfahrrad 20 Zoll", + "price": 120, + "priceDisplay": "€ 120", + "location": "Jakomini", + "postCode": "8010", + "state": "Steiermark", + "isPrivate": true, + "paylivery": false, + "publishedAt": "2026-10-30T11:00:00Z", + "description": "Gut erhaltenes Kinderfahrrad ...", + "imageUrl": "https://cache.willhaben.at/mmo/...", + "url": "https://www.willhaben.at/iad/kaufen-und-verkaufen/d/..." + } + ] +} +``` + +With `--facets --json` the output also contains a `facets` array. diff --git a/docs/commands/whoami.md b/docs/commands/whoami.md index ac470ea..dfbb3b1 100644 --- a/docs/commands/whoami.md +++ b/docs/commands/whoami.md @@ -1,6 +1,8 @@ # whoami -Show current user information. +Show current user information and whether your session is still active. + +Checking the session refreshes it, which also extends it. If it has expired, the command says so and exits with code 1. Run `willhaben login` again in that case. ## Usage diff --git a/src/api/application-token.ts b/src/api/application-token.ts index ba5a220..d2c834e 100644 --- a/src/api/application-token.ts +++ b/src/api/application-token.ts @@ -1,27 +1,13 @@ import { createHmac, randomBytes } from "crypto"; import { loadConfig, saveConfig } from "../store/config.js"; +import { formatTimestamp, getClientHeaders, ORGANIZATION } from "./headers.js"; import type { ApplicationToken } from "../types/index.js"; -// Secret key from decompiled Android app +// Secret used to sign application token requests const HMAC_SECRET = "$2a$10$qTwigHZ2rRjCjRKwP.S6W."; -const ORGANIZATION = "api@tailored-apps.com"; +// Listed in https://app-aggregator.willhaben.at/service-registry.json const APPLICATION_DATA_URL = - "https://api.willhaben.at/restapi/v2/application-data"; - -// Generate timestamp in format: yyyy-MM-dd'T'HH:mm:ss+HHMM -function formatTimestamp(date: Date = new Date()): string { - const pad = (n: number) => n.toString().padStart(2, "0"); - const offset = -date.getTimezoneOffset(); - const sign = offset >= 0 ? "+" : "-"; - const offsetHrs = pad(Math.floor(Math.abs(offset) / 60)); - const offsetMins = pad(Math.abs(offset) % 60); - - return ( - `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}` + - `T${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}` + - `${sign}${offsetHrs}${offsetMins}` - ); -} + "https://app-aggregator.willhaben.at/api/v1/application-data"; // Generate HMAC-SHA1 signature function generateSignature(salt: string, timestamp: string): string { @@ -50,7 +36,7 @@ interface ApplicationDataResponse { // Fetch a new application token from the API async function fetchApplicationToken(): Promise { - const salt = randomBytes(12).toString("base64"); + const salt = randomBytes(12).toString("base64url"); const timestamp = formatTimestamp(); const signature = generateSignature(salt, timestamp); @@ -64,18 +50,14 @@ async function fetchApplicationToken(): Promise { }; const response = await fetch( - `${APPLICATION_DATA_URL}?config_item=search-config`, + // root-links is the smallest config item; the token is returned regardless + `${APPLICATION_DATA_URL}?config_item=root-links`, { method: "POST", headers: { + ...getClientHeaders(), "Content-Type": "application/json", - Accept: "application/json", - "User-Agent": "willhaben/6201787 CFNetwork/3860.400.51 Darwin/25.3.0", - "x-wh-client": - "api@tailored-apps.com;willhabenapp;ios;8.33.0;responsive_app", - "x-wh-date": timestamp, - "x-wh-security-version": "20130527022532", - "x-wh-visitor-id": crypto.randomUUID().toUpperCase(), + "X-WH-Date": timestamp, }, body: JSON.stringify(requestBody), } @@ -136,6 +118,3 @@ export async function clearApplicationToken(): Promise { delete config.applicationToken; await saveConfig(config); } - -// Export timestamp formatter for use in headers -export { formatTimestamp }; diff --git a/src/api/auth.ts b/src/api/auth.ts index ec32881..8a7fbbe 100644 --- a/src/api/auth.ts +++ b/src/api/auth.ts @@ -361,6 +361,10 @@ export async function login(): Promise> { accessToken: tokens.access_token, refreshToken: tokens.refresh_token, expiresAt: Date.now() + tokens.expires_in * 1000, + // 0 means the refresh token doesn't expire on its own + refreshExpiresAt: tokens.refresh_expires_in + ? Date.now() + tokens.refresh_expires_in * 1000 + : undefined, }); await setUserInfo(user); diff --git a/src/api/categories.ts b/src/api/categories.ts index 73b5c8f..fdc7ed3 100644 --- a/src/api/categories.ts +++ b/src/api/categories.ts @@ -63,8 +63,10 @@ export interface ValidationResult { export async function getCategoryTree( adTypeId: number = 67 ): Promise> { + // Public data, so it also works when logged out or the session expired return apiClient.get( - ENDPOINTS.categoryTreeWithAttributes(adTypeId) + ENDPOINTS.categoryTreeWithAttributes(adTypeId), + { authenticated: false } ); } diff --git a/src/api/client.ts b/src/api/client.ts index 9f68be2..dc6845d 100644 --- a/src/api/client.ts +++ b/src/api/client.ts @@ -1,23 +1,70 @@ import { getAuthTokens, setAuthTokens, isTokenExpired } from "../store/config.js"; -import { getApplicationToken, formatTimestamp } from "./application-token.js"; -import type { ApiResponse, RefreshTokenResponse } from "../types/index.js"; +import { getApplicationToken } from "./application-token.js"; +import { getClientHeaders } from "./headers.js"; +import type { ApiError, ApiResponse } from "../types/index.js"; -// Real API base URLs discovered via mitmproxy +// API base URLs const SSO_URL = "https://sso.willhaben.at"; const PUBLIC_API_URL = "https://publicapi.willhaben.at"; const REST_API_URL = "https://api.willhaben.at/restapi/v2"; +const SEARCH_API_URL = "https://ad-search.willhaben.at/restapi/v2"; + +const TOKEN_URL = `${SSO_URL}/auth/realms/willhaben/protocol/openid-connect/token`; + +export const SESSION_EXPIRED_ERROR: ApiError = { + code: "SESSION_EXPIRED", + message: "Your session has expired. Run `willhaben login` to log in again.", +}; + +/** + * Refresh the access token. Keycloak rotates refresh tokens, so the new + * refresh token must be stored too, otherwise the session dies once the + * original refresh token expires. + * Returns the new access token, or null if the session can't be refreshed. + */ +export async function refreshAccessToken(): Promise { + const tokens = await getAuthTokens(); + if (!tokens) return null; + + try { + const response = await fetch(TOKEN_URL, { + method: "POST", + headers: { "Content-Type": "application/x-www-form-urlencoded" }, + body: new URLSearchParams({ + client_id: "apps", + grant_type: "refresh_token", + refresh_token: tokens.refreshToken, + scope: "openid", + }), + }); + + if (!response.ok) return null; + + const data = await response.json(); + await setAuthTokens({ + accessToken: data.access_token, + refreshToken: data.refresh_token ?? tokens.refreshToken, + expiresAt: Date.now() + data.expires_in * 1000, + refreshExpiresAt: data.refresh_expires_in + ? Date.now() + data.refresh_expires_in * 1000 + : tokens.refreshExpiresAt, + }); + return data.access_token; + } catch { + return null; + } +} -// Common headers for mobile app API -const getDefaultHeaders = (): Record => ({ - "Content-Type": "application/json", - Accept: "application/json", - "User-Agent": "willhaben/6201787 CFNetwork/3860.400.51 Darwin/25.3.0", - "x-wh-client": "api@tailored-apps.com;willhabenapp;ios;8.33.0;responsive_app", - "x-wh-date": formatTimestamp(), - "x-wh-security-version": "20130527022532", - "x-wh-visitor-id": crypto.randomUUID().toUpperCase(), - applicationprovider: "api@tailored-apps.com", -}); +/** + * Get a valid access token, refreshing it if needed. + * Returns null if not logged in or the session has expired. + */ +export async function getValidAccessToken(): Promise { + const tokens = await getAuthTokens(); + if (!tokens) return null; + if (await isTokenExpired()) return refreshAccessToken(); + return tokens.accessToken; +} interface RequestOptions { method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE"; @@ -34,64 +81,6 @@ export class ApiClient { this.baseUrl = baseUrl; } - private async getAuthHeader(): Promise> { - const tokens = await getAuthTokens(); - if (!tokens) return {}; - - // Check if token needs refresh - if (await isTokenExpired()) { - const refreshed = await this.refreshToken(tokens.refreshToken); - if (refreshed) { - return { Authorization: `Bearer ${refreshed.accessToken}` }; - } - return {}; - } - - return { Authorization: `Bearer ${tokens.accessToken}` }; - } - - private async refreshToken( - refreshToken: string - ): Promise { - try { - const response = await fetch( - `${SSO_URL}/auth/realms/willhaben/protocol/openid-connect/token`, - { - method: "POST", - headers: { - "Content-Type": "application/x-www-form-urlencoded", - }, - body: new URLSearchParams({ - client_id: "apps", - grant_type: "refresh_token", - refresh_token: refreshToken, - }), - } - ); - - if (!response.ok) return null; - - const data = await response.json(); - - // Update stored tokens - const tokens = await getAuthTokens(); - if (tokens) { - await setAuthTokens({ - ...tokens, - accessToken: data.access_token, - expiresAt: Date.now() + data.expires_in * 1000, - }); - } - - return { - accessToken: data.access_token, - expiresIn: data.expires_in, - }; - } catch { - return null; - } - } - async request( endpoint: string, options: RequestOptions = {} @@ -108,12 +97,19 @@ export class ApiClient { // Get application token (required for all API requests) const applicationToken = await getApplicationToken(); - const authHeaders = authenticated ? await this.getAuthHeader() : {}; - const defaultHeaders = getDefaultHeaders(); - - if (contentType) { - defaultHeaders["Content-Type"] = contentType; + // Without a stored session the request goes out anonymously, as before + const authHeaders: Record = {}; + if (authenticated && (await getAuthTokens())) { + const accessToken = await getValidAccessToken(); + if (!accessToken) { + return { success: false, error: SESSION_EXPIRED_ERROR }; + } + authHeaders.Authorization = `Bearer ${accessToken}`; } + const defaultHeaders: Record = { + ...getClientHeaders(), + "Content-Type": contentType ?? "application/json", + }; const url = endpoint.startsWith("http") ? endpoint @@ -123,7 +119,7 @@ export class ApiClient { method, headers: { ...defaultHeaders, - "x-wh-application-token": applicationToken, + "X-WH-Application-Token": applicationToken, ...authHeaders, ...headers, }, @@ -207,4 +203,4 @@ export class ApiClient { } export const apiClient = new ApiClient(PUBLIC_API_URL); -export { SSO_URL, PUBLIC_API_URL, REST_API_URL }; +export { SSO_URL, PUBLIC_API_URL, REST_API_URL, SEARCH_API_URL }; diff --git a/src/api/headers.ts b/src/api/headers.ts new file mode 100644 index 0000000..f5a1d75 --- /dev/null +++ b/src/api/headers.ts @@ -0,0 +1,41 @@ +// Client identity sent with every request (willhaben Android app 8.67.0) +const APP_VERSION = "8.67.0"; +const APP_VERSION_CODE = "615389"; +const ORGANIZATION = "api@tailored-apps.com"; + +export const CLIENT_ID_HEADER = `${ORGANIZATION};willhabenapp;android;${APP_VERSION};responsive_app`; +export const USER_AGENT = `willhaben/${APP_VERSION_CODE} okhttp/5.5.0 Android/14`; +export const SECURITY_VERSION = "20130527022532"; + +// The app keeps one visitor id per install; we keep one per process +const VISITOR_ID = crypto.randomUUID(); + +// Generate timestamp in format: yyyy-MM-dd'T'HH:mm:ss+HHMM +export function formatTimestamp(date: Date = new Date()): string { + const pad = (n: number) => n.toString().padStart(2, "0"); + const offset = -date.getTimezoneOffset(); + const sign = offset >= 0 ? "+" : "-"; + const offsetHrs = pad(Math.floor(Math.abs(offset) / 60)); + const offsetMins = pad(Math.abs(offset) % 60); + + return ( + `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}` + + `T${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}` + + `${sign}${offsetHrs}${offsetMins}` + ); +} + +// Headers sent with every request (auth and application token are added by the caller) +export function getClientHeaders(): Record { + return { + Accept: "application/json", + "User-Agent": USER_AGENT, + "X-WH-Client": CLIENT_ID_HEADER, + "X-WH-Date": formatTimestamp(), + "X-WH-Security-Version": SECURITY_VERSION, + "X-WH-Visitor-Id": VISITOR_ID, + applicationprovider: ORGANIZATION, + }; +} + +export { ORGANIZATION }; diff --git a/src/api/listings.ts b/src/api/listings.ts index 4776cba..45744d6 100644 --- a/src/api/listings.ts +++ b/src/api/listings.ts @@ -1,4 +1,10 @@ -import { apiClient, REST_API_URL } from "./client.js"; +import { + apiClient, + getValidAccessToken, + REST_API_URL, + SESSION_EXPIRED_ERROR, +} from "./client.js"; +import { getClientHeaders } from "./headers.js"; import { updateCachedListings, updateCachedListing, @@ -17,7 +23,7 @@ import type { ApiResponse, } from "../types/index.js"; -// Real endpoints discovered via mitmproxy +// API endpoints const ENDPOINTS = { // Read endpoints (Public API) listMyAds: "/myatz/v1/atverz/showpagedadsfromuser", @@ -747,8 +753,8 @@ export async function uploadImage( ): Promise> { const { readFile } = await import("fs/promises"); const { basename } = await import("path"); - const { getApplicationToken, formatTimestamp } = await import("./application-token.js"); - const { getAuthTokens, isTokenExpired, setAuthTokens } = await import("../store/config.js"); + const { getApplicationToken } = await import("./application-token.js"); + const { getAuthTokens } = await import("../store/config.js"); try { const imageBuffer = await readFile(imagePath); @@ -770,50 +776,25 @@ export async function uploadImage( const blob = new Blob([imageBuffer], { type: contentType }); formData.append("file", blob, fileName); - // Get tokens and refresh if needed const applicationToken = await getApplicationToken(); - let tokens = await getAuthTokens(); - - if (!tokens) { + if (!(await getAuthTokens())) { return { success: false, error: { code: "AUTH_ERROR", message: "Not logged in" }, }; } - - // Refresh token if expired - if (await isTokenExpired()) { - const refreshResponse = await fetch( - "https://sso.willhaben.at/auth/realms/willhaben/protocol/openid-connect/token", - { - method: "POST", - headers: { "Content-Type": "application/x-www-form-urlencoded" }, - body: new URLSearchParams({ - client_id: "apps", - grant_type: "refresh_token", - refresh_token: tokens.refreshToken, - }), - } - ); - if (refreshResponse.ok) { - const refreshData = await refreshResponse.json(); - tokens = { - ...tokens, - accessToken: refreshData.access_token, - expiresAt: Date.now() + refreshData.expires_in * 1000, - }; - await setAuthTokens(tokens); - } + const accessToken = await getValidAccessToken(); + if (!accessToken) { + return { success: false, error: SESSION_EXPIRED_ERROR }; } + // Sent without apiClient so fetch can set the multipart Content-Type boundary const response = await fetch(ENDPOINTS.uploadImage(adId), { method: "POST", headers: { - "Authorization": `Bearer ${tokens.accessToken}`, - "x-wh-application-token": applicationToken, - "x-wh-client": "api@tailored-apps.com;willhabenapp;ios;8.33.0;responsive_app", - "x-wh-date": formatTimestamp(), - "Accept": "application/json", + ...getClientHeaders(), + Authorization: `Bearer ${accessToken}`, + "X-WH-Application-Token": applicationToken, }, body: formData, }); diff --git a/src/api/locations.ts b/src/api/locations.ts new file mode 100644 index 0000000..a64addd --- /dev/null +++ b/src/api/locations.ts @@ -0,0 +1,80 @@ +import { apiClient, REST_API_URL } from "./client.js"; +import type { ApiResponse } from "../types/index.js"; + +// Postcode to location lookup, as used when creating a listing +const ENDPOINTS = { + locationsForPostCode: (postCode: string) => + `${REST_API_URL}/locations/${encodeURIComponent(postCode)}`, +}; + +export interface Location { + id: number; + description: string; +} + +interface LocationsResponse { + locations?: Location[]; +} + +export async function getLocationsForPostCode( + postCode: string +): Promise> { + const response = await apiClient.get( + ENDPOINTS.locationsForPostCode(postCode), + { authenticated: false } + ); + + if (!response.success) { + return { success: false, error: response.error }; + } + + return { success: true, data: response.data?.locations ?? [] }; +} + +/** + * Resolve a location for a postcode, picking the one matching `id` or `name` + * (case-insensitive), or the only location for that postcode. + */ +export async function resolveLocation( + postCode: string, + name?: string, + id?: number +): Promise> { + const result = await getLocationsForPostCode(postCode); + if (!result.success || !result.data) { + return { success: false, error: result.error }; + } + + const locations = result.data; + if (locations.length === 0) { + return { + success: false, + error: { code: "LOCATION_NOT_FOUND", message: `No locations found for postcode ${postCode}` }, + }; + } + + const match = id !== undefined + ? locations.find((l) => l.id === id) + : name + ? locations.find((l) => l.description.toLowerCase() === name.toLowerCase()) + : locations.length === 1 + ? locations[0] + : undefined; + + if (!match) { + const options = locations.map((l) => `${l.description} (${l.id})`).join(", "); + return { + success: false, + error: { + code: "LOCATION_AMBIGUOUS", + message: id !== undefined + ? `Location id ${id} does not belong to postcode ${postCode}. Options: ${options}` + : name + ? `"${name}" is not a location for postcode ${postCode}. Options: ${options}` + : `Postcode ${postCode} has several locations, set "location" to one of: ${options}`, + }, + }; + } + + return { success: true, data: match }; +} diff --git a/src/api/search.ts b/src/api/search.ts new file mode 100644 index 0000000..8bae61b --- /dev/null +++ b/src/api/search.ts @@ -0,0 +1,200 @@ +import { apiClient, SEARCH_API_URL } from "./client.js"; +import type { ApiResponse } from "../types/index.js"; + +// Marketplace search across all categories +const MARKETPLACE_SEARCH_URL = `${SEARCH_API_URL}/search/atz/seo/kaufen-und-verkaufen/marktplatz`; +const WEB_AD_BASE_URL = "https://www.willhaben.at/iad/"; + +// areaId values from the search "Bundesland" navigator +export const STATES: Record = { + burgenland: 1, + kaernten: 2, + niederoesterreich: 3, + oberoesterreich: 4, + salzburg: 5, + steiermark: 6, + tirol: 7, + vorarlberg: 8, + wien: 900, +}; + +// sort ids from the search sortOrderList +export const SORT_ORDERS: Record = { + newest: 1, + nearest: 2, + "price-asc": 3, + "price-desc": 4, + relevance: 7, +}; + +export interface SearchOptions { + keyword?: string; + categoryId?: string; // ATTRIBUTE_TREE id, see the "category" facet + priceFrom?: number; + priceTo?: number; + state?: string; // key of STATES + seller?: "private" | "dealer"; + paylivery?: boolean; + periodDays?: number; + sort?: string; // key of SORT_ORDERS + page?: number; + rows?: number; + // Raw url parameters, e.g. ["treeAttributes", "22"] from a facet + params?: Array<[string, string]>; +} + +export interface SearchResultAd { + id: string; + title: string; + price: number | null; + priceDisplay: string | null; + location: string | null; + postCode: string | null; + state: string | null; + isPrivate: boolean; + paylivery: boolean; + publishedAt: string | null; + description: string | null; + imageUrl: string | null; + url: string | null; +} + +export interface SearchFacetValue { + label: string; + hits: number; + params: Array<[string, string]>; +} + +export interface SearchFacet { + id: string; + label: string; + values: SearchFacetValue[]; +} + +export interface SearchResult { + total: number; + page: number; + rows: number; + ads: SearchResultAd[]; + facets: SearchFacet[]; +} + +interface RawAttribute { + name: string; + values: string[]; +} + +interface RawAdvertSummary { + id: string; + description: string; + attributes: { attribute: RawAttribute[] }; + advertImageList?: { advertImage: Array<{ mainImageUrl: string }> }; +} + +interface RawUrlParam { + urlParameterName: string; + value: string; +} + +interface RawNavigator { + id: string; + label: string; + groupedPossibleValues?: Array<{ + possibleValues?: Array<{ + label: string; + hits: number; + urlParamRepresentationForValue?: RawUrlParam[]; + }>; + }>; +} + +interface RawSearchResponse { + rowsFound: number; + rowsRequested: number; + pageRequested: number; + advertSummaryList?: { advertSummary: RawAdvertSummary[] }; + navigatorGroups?: Array<{ navigatorList: RawNavigator[] }>; +} + +export function buildSearchUrl(options: SearchOptions): string { + const params = new URLSearchParams(); + if (options.keyword) params.set("keyword", options.keyword); + if (options.categoryId) params.set("ATTRIBUTE_TREE", options.categoryId); + if (options.priceFrom !== undefined) params.set("PRICE_FROM", String(options.priceFrom)); + if (options.priceTo !== undefined) params.set("PRICE_TO", String(options.priceTo)); + if (options.state) params.set("areaId", String(STATES[options.state])); + if (options.seller) params.set("ISPRIVATE", options.seller === "private" ? "1" : "0"); + if (options.paylivery) params.set("paylivery", "true"); + if (options.periodDays) params.set("periode", String(options.periodDays)); + if (options.sort) params.set("sort", String(SORT_ORDERS[options.sort])); + for (const [name, value] of options.params ?? []) params.append(name, value); + params.set("page", String(options.page ?? 1)); + params.set("rows", String(options.rows ?? 30)); + return `${MARKETPLACE_SEARCH_URL}?${params}`; +} + +function convertAd(ad: RawAdvertSummary): SearchResultAd { + const attr = (name: string) => + ad.attributes.attribute.find((a) => a.name === name)?.values[0] ?? null; + const price = attr("PRICE"); + const seoUrl = attr("SEO_URL"); + + return { + id: ad.id, + title: attr("HEADING") ?? ad.description, + price: price !== null ? parseFloat(price) : null, + priceDisplay: attr("PRICE_FOR_DISPLAY"), + location: attr("LOCATION"), + postCode: attr("POSTCODE"), + state: attr("STATE"), + isPrivate: attr("ISPRIVATE") === "1", + paylivery: attr("p2penabled") === "true", + publishedAt: attr("PUBLISHED_String"), + description: attr("BODY_DYN"), + imageUrl: ad.advertImageList?.advertImage[0]?.mainImageUrl ?? null, + url: seoUrl ? `${WEB_AD_BASE_URL}${seoUrl}` : null, + }; +} + +function convertFacets(response: RawSearchResponse): SearchFacet[] { + const navigators = (response.navigatorGroups ?? []).flatMap((g) => g.navigatorList); + return navigators + .map((nav) => ({ + id: nav.id, + label: nav.label, + values: (nav.groupedPossibleValues ?? []) + .flatMap((g) => g.possibleValues ?? []) + .map((v) => ({ + label: v.label, + hits: v.hits, + params: (v.urlParamRepresentationForValue ?? []).map( + (p) => [p.urlParameterName, p.value] as [string, string] + ), + })), + })) + .filter((facet) => facet.values.length > 0); +} + +export async function searchAds( + options: SearchOptions +): Promise> { + const response = await apiClient.get(buildSearchUrl(options), { + authenticated: false, + }); + + if (!response.success || !response.data) { + return { success: false, error: response.error }; + } + + const data = response.data; + return { + success: true, + data: { + total: data.rowsFound, + page: data.pageRequested, + rows: data.rowsRequested, + ads: (data.advertSummaryList?.advertSummary ?? []).map(convertAd), + facets: convertFacets(data), + }, + }; +} diff --git a/src/cli/commands/auth.ts b/src/cli/commands/auth.ts index fa1023c..a391df2 100644 --- a/src/cli/commands/auth.ts +++ b/src/cli/commands/auth.ts @@ -3,7 +3,8 @@ import chalk from "chalk"; import ora from "ora"; import prompts from "prompts"; import { login, logout, whoami } from "../../api/auth.js"; -import { isAuthenticated } from "../../store/config.js"; +import { refreshAccessToken } from "../../api/client.js"; +import { getAuthTokens, isAuthenticated } from "../../store/config.js"; export function registerAuthCommands(program: Command): void { program @@ -77,6 +78,22 @@ export function registerAuthCommands(program: Command): void { if (result.data.name) { console.log(` Name: ${result.data.name}`); } + + // A refresh is confirmed by the server and also extends the session + const sessionSpinner = ora("Checking session...").start(); + const accessToken = await refreshAccessToken(); + sessionSpinner.stop(); + if (accessToken) { + const tokens = await getAuthTokens(); + const until = tokens?.refreshExpiresAt + ? ` (renews automatically, idle timeout ${new Date(tokens.refreshExpiresAt).toLocaleString()})` + : ""; + console.log(` Session: ${chalk.green("active")}${chalk.dim(until)}`); + } else { + console.log(` Session: ${chalk.red("expired")}`); + console.log(chalk.dim("Run `willhaben login` to log in again.")); + process.exitCode = 1; + } } else { spinner.fail(chalk.red("Failed to fetch user info")); console.error( diff --git a/src/cli/commands/listings.ts b/src/cli/commands/listings.ts index ed8a75e..c3b58d1 100644 --- a/src/cli/commands/listings.ts +++ b/src/cli/commands/listings.ts @@ -22,6 +22,7 @@ import { type PublishListingOptions, } from "../../api/listings.js"; import { isAuthenticated, getConfigValue, getJwtUserInfo } from "../../store/config.js"; +import { resolveLocation } from "../../api/locations.js"; import { getCachedListing } from "../../store/listings.js"; import type { ListingTemplate, Listing } from "../../types/index.js"; @@ -124,12 +125,10 @@ export function registerListingCommands(program: Command): void { program .command("get ") - .description("Get details of a specific listing") + .description("Get details of a listing (yours or any public one)") .option("--json", "Output as JSON") .option("--cached", "Use cached data if available") .action(async (id: string, opts) => { - await requireAuth(); - // Try cache first if requested if (opts.cached) { const cached = await getCachedListing(id); @@ -192,7 +191,7 @@ export function registerListingCommands(program: Command): void { } // Validate required fields - const requiredFields = ["title", "description", "price", "categoryPath", "postCode", "locationId", "location"]; + const requiredFields = ["title", "description", "price", "categoryPath", "postCode"]; const missing = requiredFields.filter((f) => !(f in template) || template[f as keyof ListingTemplate] === undefined); if (missing.length > 0) { console.error(chalk.red(`Template missing required fields: ${missing.join(", ")}`)); @@ -202,8 +201,7 @@ export function registerListingCommands(program: Command): void { description: "Item description", price: 10, postCode: "8010", - locationId: 117458, - location: "Graz", + location: "Jakomini", categoryPath: ["BOOKSFILMANDMUSIC", "NON_FICTION_BOOKS"], condition: "gebraucht", delivery: ["PICKUP", "Versand"] @@ -213,13 +211,29 @@ export function registerListingCommands(program: Command): void { const spinner = ora("Publishing listing...").start(); + let locationId = template.locationId; + let location = template.location; + if (locationId === undefined || location === undefined) { + spinner.text = "Resolving location..."; + const resolved = await resolveLocation(template.postCode, template.location, template.locationId); + if (!resolved.success || !resolved.data) { + spinner.fail(chalk.red("Failed to resolve location")); + console.error(chalk.red(resolved.error?.message || "Unknown error occurred")); + console.error(chalk.dim(`Run \`willhaben locations ${template.postCode}\` to see the options.`)); + process.exit(1); + } + locationId ??= resolved.data.id; + location ??= resolved.data.description; + spinner.text = "Publishing listing..."; + } + const publishOptions: PublishListingOptions = { title: template.title, description: template.description, price: template.price, postCode: template.postCode, - locationId: template.locationId, - location: template.location, + locationId, + location, street: template.street, categoryPath: template.categoryPath, condition: template.condition, diff --git a/src/cli/commands/locations.ts b/src/cli/commands/locations.ts new file mode 100644 index 0000000..011cbf3 --- /dev/null +++ b/src/cli/commands/locations.ts @@ -0,0 +1,38 @@ +import { Command } from "commander"; +import chalk from "chalk"; +import ora from "ora"; +import { getLocationsForPostCode } from "../../api/locations.js"; + +export function registerLocationCommands(program: Command): void { + program + .command("locations ") + .description("Look up the location ids for a postcode (for listing templates)") + .option("--json", "Output as JSON") + .action(async (postCode: string, opts) => { + const spinner = ora("Looking up locations...").start(); + const result = await getLocationsForPostCode(postCode); + + if (!result.success || !result.data) { + spinner.fail(chalk.red("Failed to look up locations")); + console.error(chalk.red(result.error?.message || "Unknown error occurred")); + process.exit(1); + } + spinner.stop(); + + if (opts.json) { + console.log(JSON.stringify(result.data, null, 2)); + return; + } + + if (result.data.length === 0) { + console.log(chalk.yellow(`No locations found for postcode ${postCode}.`)); + return; + } + + console.log(chalk.bold(`Locations for postcode ${postCode}:\n`)); + for (const location of result.data) { + console.log(` ${chalk.cyan(String(location.id).padEnd(8))} ${location.description}`); + } + console.log(chalk.dim(`\nUse in a template: "postCode": "${postCode}", "location": ""`)); + }); +} diff --git a/src/cli/commands/search.ts b/src/cli/commands/search.ts new file mode 100644 index 0000000..b0f5f23 --- /dev/null +++ b/src/cli/commands/search.ts @@ -0,0 +1,138 @@ +import { Command, InvalidArgumentError } from "commander"; +import chalk from "chalk"; +import ora from "ora"; +import { + searchAds, + STATES, + SORT_ORDERS, + type SearchFacet, + type SearchOptions, + type SearchResultAd, +} from "../../api/search.js"; + +function parseNumber(value: string): number { + const n = Number(value); + if (Number.isNaN(n)) throw new InvalidArgumentError("Not a number."); + return n; +} + +function parseChoice(choices: Record) { + return (value: string): string => { + const key = value.toLowerCase(); + if (!(key in choices)) { + throw new InvalidArgumentError(`Allowed: ${Object.keys(choices).join(", ")}`); + } + return key; + }; +} + +function collectFilter(value: string, previous: Array<[string, string]>): Array<[string, string]> { + const index = value.indexOf("="); + if (index <= 0) throw new InvalidArgumentError("Use the form param=value, e.g. treeAttributes=22"); + return [...previous, [value.slice(0, index), value.slice(index + 1)]]; +} + +function formatAd(ad: SearchResultAd): void { + const price = ad.priceDisplay ?? (ad.price !== null ? `€ ${ad.price}` : "–"); + const badges = [ad.isPrivate ? null : chalk.yellow("dealer"), ad.paylivery ? chalk.cyan("paylivery") : null] + .filter(Boolean) + .join(" "); + console.log(`${chalk.green(price.padEnd(10))} ${chalk.bold(ad.title)} ${badges}`); + + const published = ad.publishedAt ? new Date(ad.publishedAt).toLocaleDateString() : null; + const meta = [ad.id, [ad.postCode, ad.location].filter(Boolean).join(" "), published] + .filter(Boolean) + .join(" · "); + console.log(chalk.dim(`${" ".repeat(11)}${meta}`)); + if (ad.url) console.log(chalk.dim(`${" ".repeat(11)}${ad.url}`)); +} + +function formatFacets(facets: SearchFacet[]): void { + for (const facet of facets) { + if (facet.id === "keyword") continue; + console.log(chalk.bold(`${facet.label} (${facet.id})`)); + for (const value of facet.values) { + const params = value.params.map(([k, v]) => `${k}=${v}`).join("&"); + console.log(` ${value.label} ${chalk.dim(`(${value.hits})`)} ${chalk.cyan(`--filter ${params}`)}`); + } + console.log(); + } +} + +export function registerSearchCommands(program: Command): void { + program + .command("search [keyword...]") + .description("Search marketplace listings (no login required)") + .option("-c, --category ", "Category id (see --facets)") + .option("--min ", "Minimum price", parseNumber) + .option("--max ", "Maximum price", parseNumber) + .option("--state ", `State: ${Object.keys(STATES).join(", ")}`, parseChoice(STATES)) + .option("--private", "Only private sellers") + .option("--dealer", "Only dealers") + .option("--paylivery", "Only listings with PayLivery (buyer protection and shipping)") + .option("--days ", "Only listings published in the last n days", parseNumber) + .option("--sort ", `Sort: ${Object.keys(SORT_ORDERS).join(", ")}`, parseChoice(SORT_ORDERS)) + .option("-p, --page ", "Page number", parseNumber, 1) + .option("-n, --rows ", "Results per page", parseNumber, 30) + .option("-f, --filter ", "Raw search filter, repeatable (see --facets)", collectFilter, []) + .option("--facets", "Show available filters with their hit counts") + .option("--json", "Output as JSON") + .action(async (keywordParts: string[], opts) => { + if (opts.private && opts.dealer) { + console.error(chalk.red("Use either --private or --dealer, not both.")); + process.exit(1); + } + + const options: SearchOptions = { + keyword: keywordParts.join(" ") || undefined, + categoryId: opts.category, + priceFrom: opts.min, + priceTo: opts.max, + state: opts.state, + seller: opts.private ? "private" : opts.dealer ? "dealer" : undefined, + paylivery: opts.paylivery, + periodDays: opts.days, + sort: opts.sort, + page: opts.page, + rows: opts.rows, + params: opts.filter, + }; + + const spinner = ora("Searching...").start(); + const result = await searchAds(options); + + if (!result.success || !result.data) { + spinner.fail(chalk.red("Search failed")); + console.error(chalk.red(result.error?.message || "Unknown error occurred")); + process.exit(1); + } + spinner.stop(); + + const { data } = result; + if (opts.json) { + const { facets, ...rest } = data; + console.log(JSON.stringify(opts.facets ? data : rest, null, 2)); + return; + } + + if (opts.facets) { + formatFacets(data.facets); + return; + } + + if (data.ads.length === 0) { + console.log(chalk.yellow("No listings found.")); + return; + } + + const pages = Math.ceil(data.total / data.rows); + console.log(chalk.bold(`${data.total} listings found (page ${data.page} of ${pages}):\n`)); + for (const ad of data.ads) { + formatAd(ad); + console.log(); + } + if (data.page < pages) { + console.log(chalk.dim(`Next page: add --page ${data.page + 1}`)); + } + }); +} diff --git a/src/cli/index.ts b/src/cli/index.ts index 6406d0f..b04302d 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -4,6 +4,8 @@ import { registerListingCommands } from "./commands/listings.js"; import { registerConfigCommands } from "./commands/config.js"; import { registerSetupCommands } from "./commands/setup.js"; import { registerCategoryCommands } from "./commands/categories.js"; +import { registerSearchCommands } from "./commands/search.js"; +import { registerLocationCommands } from "./commands/locations.js"; export function createCLI(): Command { const program = new Command(); @@ -17,6 +19,8 @@ export function createCLI(): Command { registerAuthCommands(program); registerListingCommands(program); registerCategoryCommands(program); + registerSearchCommands(program); + registerLocationCommands(program); registerConfigCommands(program); registerSetupCommands(program); diff --git a/src/types/index.ts b/src/types/index.ts index bbea73e..f13fd4a 100644 --- a/src/types/index.ts +++ b/src/types/index.ts @@ -3,6 +3,7 @@ export interface AuthTokens { accessToken: string; refreshToken: string; expiresAt: number; // Unix timestamp + refreshExpiresAt?: number; // Unix timestamp; absent for sessions from older versions } // Application token for API access (valid 30 days) @@ -73,8 +74,10 @@ export interface ListingTemplate { categoryPath: string[]; // Location settings postCode: string; - locationId: number; // District ID, e.g., 117458 for Jakomini/Graz - location: string; // District name, e.g., "Jakomini" + // District name, e.g., "Jakomini". Optional if the postcode has a single location. + location?: string; + // District ID, e.g., 117458 for Jakomini/Graz. Resolved from postCode + location if omitted. + locationId?: number; street?: string; // Street address (any text) // Optional attributes condition?: "neu" | "gebraucht" | "defekt"; From 7bb18c660fc22659c530c153d1d8d5785c984e6c Mon Sep 17 00:00:00 2001 From: Thomas Leiter Date: Fri, 30 Oct 2026 11:14:55 +0100 Subject: [PATCH 2/3] Fix listing status mapping in list and get Both endpoints return the same numeric ad status, but list and get mapped it differently and neither knew sold (120), so sold ads showed as active or inactive. Map the status id in one place and add draft, pending, rejected and sold. --- src/api/listings.ts | 31 +++++++++++++++---------------- src/cli/commands/listings.ts | 4 ++++ src/types/index.ts | 10 +++++++++- 3 files changed, 28 insertions(+), 17 deletions(-) diff --git a/src/api/listings.ts b/src/api/listings.ts index 45744d6..781d96b 100644 --- a/src/api/listings.ts +++ b/src/api/listings.ts @@ -144,18 +144,24 @@ interface WillhabenListingsResponse { totalNumberOfAdvertDetails: number; } +// Map the numeric ad status, which both /myatz/v1/ and /atdetail/v1/ return +function statusFromId(statusId: number): Listing["status"] { + if (statusId === 50 || statusId === 51) return "active"; + if (statusId === 120) return "sold"; + if (statusId >= 60 && statusId <= 63) return "expired"; + if ((statusId >= 80 && statusId <= 87) || (statusId >= 110 && statusId <= 117)) { + return "rejected"; + } + if (statusId === 30 || statusId === 31 || statusId === 90) return "pending"; + if (statusId === 10) return "draft"; + return "inactive"; +} + // Convert API response to our Listing type (for /myatz/v1/ endpoints) function convertToListing(ad: WillhabenAdvert, verticalName: string): Listing { const priceAttr = ad.attributes?.attribute.find((a) => a.name === "PRICE"); const price = priceAttr ? parseFloat(priceAttr.values[0]) : 0; - const statusMap: Record = { - active: "active", - passive: "expired", - sold: "inactive", - inactive: "inactive", - }; - return { id: ad.id, title: ad.description, @@ -164,7 +170,7 @@ function convertToListing(ad: WillhabenAdvert, verticalName: string): Listing { currency: "EUR", category: verticalName, categoryId: ad.adTypeId, - status: statusMap[ad.advertStatus.id] || "active", + status: statusFromId(ad.advertStatus.statusId), images: ad.advertImageList?.advertImage .filter((img) => img.mainImageUrl) @@ -219,13 +225,6 @@ function convertAdDetailToListing(detail: AdDetailResponse): Listing { values: [kv.value], })) || []; - // Map status - const statusMap: Record = { - 50: "active", - 60: "inactive", - 70: "expired", - }; - return { id: detail.adId, title: detail.description, @@ -234,7 +233,7 @@ function convertAdDetailToListing(detail: AdDetailResponse): Listing { currency: "EUR", category, categoryId: detail.adTypeId, - status: statusMap[detail.status.id] || "active", + status: statusFromId(detail.status.id), images, attributes, createdAt: new Date().toISOString(), diff --git a/src/cli/commands/listings.ts b/src/cli/commands/listings.ts index c3b58d1..3b28199 100644 --- a/src/cli/commands/listings.ts +++ b/src/cli/commands/listings.ts @@ -58,10 +58,14 @@ function formatStatus(status: Listing["status"]): string { switch (status) { case "active": return chalk.green(status); + case "draft": + case "pending": case "inactive": return chalk.yellow(status); case "expired": + case "rejected": return chalk.red(status); + case "sold": case "deleted": return chalk.dim(status); default: diff --git a/src/types/index.ts b/src/types/index.ts index f13fd4a..34a90fe 100644 --- a/src/types/index.ts +++ b/src/types/index.ts @@ -48,7 +48,15 @@ export interface Listing { currency: string; category: string; categoryId: number; - status: "active" | "inactive" | "expired" | "deleted"; + status: + | "draft" + | "pending" + | "active" + | "expired" + | "rejected" + | "sold" + | "inactive" + | "deleted"; images: ListingImage[]; attributes: ListingAttribute[]; location?: { From 7afe1a94f67ec28cf5d1333c5ada629d1a3bda5b Mon Sep 17 00:00:00 2001 From: Thomas Leiter Date: Fri, 30 Oct 2026 11:21:31 +0100 Subject: [PATCH 3/3] Upload template images on publish and make --draft work publish now saves the listing, uploads the template's images, and only then puts it live, so a listing never goes live without its photos. If an upload fails, the listing stays a draft. --draft was accepted but ignored; it now keeps the listing as a draft, and the new `activate` command puts it live. --- LLMS.md | 26 +++++++++++---- README.md | 11 +++++-- docs/commands/index.md | 1 + docs/commands/publish.md | 28 +++++++++++++--- src/api/listings.ts | 63 +++++++++++++++++++++++++++--------- src/cli/commands/listings.ts | 54 ++++++++++++++++++++++++++++--- src/types/index.ts | 2 +- 7 files changed, 151 insertions(+), 34 deletions(-) diff --git a/LLMS.md b/LLMS.md index c4e5306..7a7d823 100644 --- a/LLMS.md +++ b/LLMS.md @@ -96,6 +96,7 @@ Create a JSON file with the listing details: | `locationId` | number | Location id, looked up automatically from `postCode` + `location` | | `condition` | string | `"neu"`, `"gebraucht"`, or `"defekt"` | | `delivery` | string[] | `["PICKUP"]`, `["Versand"]`, or both | +| `images` | string[] | Image files (jpg, png, gif, webp), relative to the template file. First is the cover | | `street` | string | Street address | | `attributes` | object | Category-specific attributes | | `contactInfo.name` | string | Contact name override | @@ -112,15 +113,24 @@ willhaben locations 8010 --json ### Step 3: Publish the Listing +`publish` saves a draft, uploads the template's `images`, then puts the listing live. If an image upload fails, the listing stays a draft and the error contains its ID. + ```bash # Publish from template file willhaben publish listing.json +# Save as draft only, so the user can review it in the willhaben app first +willhaben publish listing.json --draft +# ...then put it live +willhaben activate + # Output as JSON (for programmatic use) willhaben publish listing.json --json ``` -### Step 4: Upload Images +Prefer `--draft` when the user hasn't explicitly asked to publish right away. + +### Step 4: Manage Images Later ```bash # Upload single image @@ -159,6 +169,9 @@ willhaben update --description "Updated description" willhaben delete willhaben delete --force # Skip confirmation +# Put a draft live +willhaben activate + # Deactivate (take offline temporarily) willhaben deactivate @@ -215,15 +228,16 @@ cat > listing.json << 'EOF' "postCode": "8010", "location": "Jakomini", "condition": "gebraucht", - "delivery": ["PICKUP", "Versand"] + "delivery": ["PICKUP", "Versand"], + "images": ["buch_cover.jpg", "buch_rueckseite.jpg"] } EOF -# 5. Publish -willhaben publish listing.json +# 5. Save as draft with images, let the user review it in the app +willhaben publish listing.json --draft -# 6. Upload images (use listing ID from publish output) -willhaben upload-image buch_cover.jpg buch_rueckseite.jpg +# 6. Put it live (use listing ID from publish output) +willhaben activate ``` ## JSON Output Mode diff --git a/README.md b/README.md index cad105c..e831729 100644 --- a/README.md +++ b/README.md @@ -142,7 +142,8 @@ Create a template file `my-item.json`: "postCode": "1010", "categoryPath": ["MOBILE_ELECTRONICS", "MOBILE_PHONES", "IPHONE"], "condition": "gebraucht", - "delivery": ["PICKUP", "Versand"] + "delivery": ["PICKUP", "Versand"], + "images": ["photo1.jpg", "photo2.jpg"] } ``` @@ -150,6 +151,10 @@ Then publish: ```bash willhaben publish my-item.json + +# Or save a draft first, check it in the app, then put it live +willhaben publish my-item.json --draft +willhaben activate ``` --- @@ -170,9 +175,10 @@ willhaben publish my-item.json |---------|-------------| | `willhaben list` | List all your listings | | `willhaben get ` | Get details of a listing (yours or any public one) | -| `willhaben publish ` | Create a new listing from JSON | +| `willhaben publish ` | Create a new listing from JSON, with images (`--draft` to review first) | | `willhaben update ` | Update listing properties | | `willhaben delete ` | Delete a listing | +| `willhaben activate ` | Put a draft live | | `willhaben republish ` | Republish an expired listing | | `willhaben deactivate ` | Take a listing offline | | `willhaben reserve ` | Mark as reserved | @@ -316,6 +322,7 @@ willhaben upload-image 123456789 photo1.jpg photo2.jpg photo3.jpg | `street` | string | Street address | | `condition` | string | `"neu"`, `"gebraucht"`, or `"defekt"` | | `delivery` | string[] | `["PICKUP"]`, `["Versand"]`, or both | +| `images` | string[] | Image files, relative to the template file. Uploaded before the listing goes live | | `attributes` | object | Category-specific attributes | | `contactInfo` | object | Contact information override | | `skipValidation` | boolean | Skip attribute validation | diff --git a/docs/commands/index.md b/docs/commands/index.md index ecdbc47..3a1abbb 100644 --- a/docs/commands/index.md +++ b/docs/commands/index.md @@ -31,6 +31,7 @@ Quick reference for all willhaben-cli commands. | Command | Description | |---------|-------------| +| `activate ` | Put a draft live | | `republish ` | Republish an expired listing | | `deactivate ` | Take a listing offline | | `reserve ` | Mark as reserved | diff --git a/docs/commands/publish.md b/docs/commands/publish.md index b599f03..5c9cd47 100644 --- a/docs/commands/publish.md +++ b/docs/commands/publish.md @@ -18,8 +18,17 @@ willhaben publish [options] | Option | Description | |--------|-------------| +| `--draft` | Save as a draft without putting it live. Publish it later with `willhaben activate ` | | `--json` | Output as JSON | +## How publishing works + +1. The listing is saved as a draft. +2. The images from `images` are uploaded. +3. The draft is put live, unless `--draft` is set. + +If an image upload fails, the listing stays a draft and never goes live without its photos. The error message contains the draft ID. + ## Template Format ### Required Fields @@ -40,6 +49,7 @@ willhaben publish [options] | `locationId` | number | Location id. Looked up from `postCode` and `location` if omitted | | `condition` | string | `"neu"`, `"gebraucht"`, or `"defekt"` | | `delivery` | string[] | `["PICKUP"]`, `["Versand"]`, or both | +| `images` | string[] | Image files (jpg, png, gif, webp), relative to the template file. The first one is the cover image | | `attributes` | object | Category-specific attributes | ## Example Template @@ -54,7 +64,8 @@ Create `my-item.json`: "postCode": "1010", "categoryPath": ["MOBILE_ELECTRONICS", "MOBILE_PHONES", "IPHONE"], "condition": "gebraucht", - "delivery": ["PICKUP", "Versand"] + "delivery": ["PICKUP", "Versand"], + "images": ["front.jpg", "back.jpg"] } ``` @@ -62,9 +73,18 @@ Then publish: ```bash willhaben publish my-item.json -# Listing created successfully! -# ID: 123456789 -# URL: https://willhaben.at/iad/object?adId=123456789 +# ✔ Listing published successfully! +# ID: 123456789 +# Title: iPhone 14 Pro - Excellent Condition +# Price: € 799 +# Images: 2 +``` + +Or save it as a draft first, check it in the willhaben app, and put it live afterwards: + +```bash +willhaben publish my-item.json --draft +willhaben activate 123456789 ``` ## Category Examples diff --git a/src/api/listings.ts b/src/api/listings.ts index 781d96b..e2bda06 100644 --- a/src/api/listings.ts +++ b/src/api/listings.ts @@ -399,6 +399,10 @@ export interface PublishListingOptions { attributes?: Record; // Skip attribute validation (not recommended) skipValidation?: boolean; + // Image file paths, uploaded before the listing goes live + images?: string[]; + // Keep the listing as a draft instead of putting it live + draft?: boolean; } // Cached category tree for validation @@ -577,34 +581,54 @@ export async function createListing( }; } - const adId = saveResponse.data.adId; + const adId = saveResponse.data.adId.toString(); - // Step 2: Activate/publish the draft (uses PUT) - const activateResponse = await apiClient.put( - ENDPOINTS.publish(adId.toString()) - ); + // Step 2: Upload images while it's still a draft, so it never goes live without them + let images: Listing["images"] = []; + if (options.images && options.images.length > 0) { + const uploadResponse = await uploadImages(adId, options.images); + if (!uploadResponse.success) { + return { + success: false, + error: { + code: "IMAGE_UPLOAD_FAILED", + message: `Draft saved (ID: ${adId}) but image upload failed: ${uploadResponse.error?.message ?? "unknown error"}`, + details: { adId }, + }, + }; + } + images = (uploadResponse.data?.advertImage ?? []).map((img) => ({ + url: img.mainImageUrl, + id: String(img.id), + })); + } - if (!activateResponse.success) { - return { - success: false, - error: activateResponse.error || { - code: "ACTIVATE_FAILED", - message: `Draft created (ID: ${adId}) but failed to publish`, - }, - }; + // Step 3: Activate/publish the draft (uses PUT) + if (!options.draft) { + const activateResponse = await activateListing(adId); + if (!activateResponse.success) { + return { + success: false, + error: { + code: "ACTIVATE_FAILED", + message: `Draft saved (ID: ${adId}) but failed to publish: ${activateResponse.error?.message ?? "unknown error"}`, + details: { adId }, + }, + }; + } } // Return the created listing const listing: Listing = { - id: adId.toString(), + id: adId, title: options.title, description: options.description, price: options.price, currency: "EUR", category: options.categoryPath[options.categoryPath.length - 1] || "Unknown", categoryId: 67, - status: "active", - images: [], + status: options.draft ? "draft" : "active", + images, attributes: [], createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(), @@ -614,6 +638,13 @@ export async function createListing( return { success: true, data: listing }; } +/** + * Put a saved draft live. + */ +export async function activateListing(id: string): Promise> { + return apiClient.put(ENDPOINTS.publish(id)); +} + // Response type from GET /bap/{id} for editing interface EditAdResponse { heading: string; diff --git a/src/cli/commands/listings.ts b/src/cli/commands/listings.ts index 3b28199..85ab470 100644 --- a/src/cli/commands/listings.ts +++ b/src/cli/commands/listings.ts @@ -2,6 +2,7 @@ import { Command } from "commander"; import chalk from "chalk"; import ora from "ora"; import { readFile } from "fs/promises"; +import { dirname, resolve } from "path"; import prompts from "prompts"; import { listMyListings, @@ -10,6 +11,7 @@ import { updateListing, deleteListing, republishListing, + activateListing, deactivateListing, markListingSold, markListingReserved, @@ -170,7 +172,7 @@ export function registerListingCommands(program: Command): void { .command("publish ") .description("Publish a new listing from a JSON template file") .option("--json", "Output as JSON") - .option("--draft", "Save as draft without publishing") + .option("--draft", "Save as draft without publishing (put it live later with `activate`)") .action(async (file: string, opts) => { await requireAuth(); @@ -213,7 +215,20 @@ export function registerListingCommands(program: Command): void { process.exit(1); } - const spinner = ora("Publishing listing...").start(); + // Image paths are relative to the template file; check them before creating anything + const imagePaths = (template.images ?? []).map((image) => resolve(dirname(file), image)); + for (const imagePath of imagePaths) { + if (!(await Bun.file(imagePath).exists())) { + console.error(chalk.red(`Image not found: ${imagePath}`)); + process.exit(1); + } + if (!/\.(jpe?g|png|gif|webp)$/i.test(imagePath)) { + console.error(chalk.red(`Unsupported image type: ${imagePath} (use jpg, png, gif or webp)`)); + process.exit(1); + } + } + + const spinner = ora(opts.draft ? "Saving draft..." : "Publishing listing...").start(); let locationId = template.locationId; let location = template.location; @@ -228,7 +243,7 @@ export function registerListingCommands(program: Command): void { } locationId ??= resolved.data.id; location ??= resolved.data.description; - spinner.text = "Publishing listing..."; + spinner.text = opts.draft ? "Saving draft..." : "Publishing listing..."; } const publishOptions: PublishListingOptions = { @@ -245,12 +260,16 @@ export function registerListingCommands(program: Command): void { firstName: template.contactInfo?.name, attributes: template.attributes, skipValidation: template.skipValidation, + images: imagePaths, + draft: opts.draft, }; const result = await createListing(publishOptions, userInfo); if (result.success && result.data) { - spinner.succeed(chalk.green("Listing published successfully!")); + spinner.succeed( + chalk.green(opts.draft ? "Draft saved, not published yet." : "Listing published successfully!") + ); if (opts.json) { console.log(JSON.stringify(result.data, null, 2)); @@ -258,9 +277,13 @@ export function registerListingCommands(program: Command): void { console.log(` ID: ${chalk.cyan(result.data.id)}`); console.log(` Title: ${result.data.title}`); console.log(` Price: ${chalk.green(`€ ${result.data.price}`)}`); + console.log(` Images: ${result.data.images.length}`); + if (opts.draft) { + console.log(chalk.dim(`\nCheck it in the willhaben app, then run \`willhaben activate ${result.data.id}\` to put it live.`)); + } } } else { - spinner.fail(chalk.red("Failed to publish listing")); + spinner.fail(chalk.red(opts.draft ? "Failed to save draft" : "Failed to publish listing")); console.error( chalk.red(result.error?.message || "Unknown error occurred") ); @@ -374,6 +397,27 @@ export function registerListingCommands(program: Command): void { } }); + program + .command("activate ") + .description("Put a draft live") + .action(async (id: string) => { + await requireAuth(); + + const spinner = ora("Publishing listing...").start(); + + const result = await activateListing(id); + + if (result.success) { + spinner.succeed(chalk.green("Listing published successfully!")); + } else { + spinner.fail(chalk.red("Failed to publish listing")); + console.error( + chalk.red(result.error?.message || "Unknown error occurred") + ); + process.exit(1); + } + }); + program .command("deactivate ") .description("Deactivate a listing (take offline)") diff --git a/src/types/index.ts b/src/types/index.ts index 34a90fe..951f961 100644 --- a/src/types/index.ts +++ b/src/types/index.ts @@ -90,9 +90,9 @@ export interface ListingTemplate { // Optional attributes condition?: "neu" | "gebraucht" | "defekt"; delivery?: ("PICKUP" | "Versand")[]; + images?: string[]; // Image file paths, relative to the template file // Legacy fields (kept for compatibility) categoryId?: number; - images?: string[]; // File paths or URLs attributes?: Record; contactInfo?: { name?: string;