From f199ce865a522a3af9557c79b48db05bb4ff6cc1 Mon Sep 17 00:00:00 2001 From: anujs3 Date: Mon, 16 Nov 2026 15:42:19 +0000 Subject: [PATCH] Add Location Search and Tagging Find a location by name, then use it in a post. --- README.md | 1 + public/scripts/publish.js | 38 +-- public/scripts/upload.js | 5 + src/index.js | 356 +++++++++++++++++------ test/app-scoped-user-id.test.js | 2 +- test/attachment-controls.test.js | 8 + test/attachment-validation.test.js | 231 ++++++++++++++- test/location-details.test.js | 428 ++++++++++++++++++++++++++++ test/publishing-form-errors.test.js | 88 +++++- views/account.pug | 1 + views/location_details.pug | 50 ++++ views/upload.pug | 5 + 12 files changed, 1108 insertions(+), 105 deletions(-) create mode 100644 test/location-details.test.js create mode 100644 views/location_details.pug diff --git a/README.md b/README.md index 01c7094..4626139 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,7 @@ Use this sample app to try the [Threads API](https://developers.facebook.com/doc - **Reply Management:** Hide or unhide replies in the direct-replies view. - **Search:** Search by keyword or topic tag. Choose Top or Recent results. Filter by date, media type, and author. See the [Search Guide](https://developers.facebook.com/documentation/threads/keyword-search) for parameters and limits. - **Public Profiles:** Look up a public profile. Browse its posts. +- **Public Location Search:** Find a location to add to your post. View its details. - **Post Insights:** View post metrics. Filter by date. - **User Insights:** View account metrics. Filter by date. - **Quotas:** View API usage. Refresh the reported counts. diff --git a/public/scripts/publish.js b/public/scripts/publish.js index 830bf95..259dc5e 100644 --- a/public/scripts/publish.js +++ b/public/scripts/publish.js @@ -24,41 +24,47 @@ async function queryContainerStatus() { onAsyncRequestStarting(); - let jsonResponse; + let status; try { - let response = await fetch(`/container/status/${containerId}`); - - if (response?.ok) { - jsonResponse = await response.json(); - } else { - console.error(response); - } - } catch (e) { - console.error(e); + const response = await fetch( + `/container/status/${encodeURIComponent(containerId)}` + ); + if (response.ok) ({ status } = await response.json()); + } catch { + // Show the fixed status message below. } finally { onAsyncRequestEnded(); } - switch (jsonResponse?.status) { + const errorMessage = document.getElementById('error-message'); + errorMessage.textContent = ''; + switch (status) { case 'FINISHED': - // Enable publishing document.getElementById('submit').removeAttribute('disabled'); break; case 'IN_PROGRESS': - // Retry setTimeout( queryContainerStatus, QUERY_CONTAINER_STATUS_TIMEOUT_IN_SECONDS * 1000 ); break; case 'ERROR': + errorMessage.textContent = 'The post could not be processed.'; + break; + case 'EXPIRED': + errorMessage.textContent = 'The publishing container has expired.'; + break; + case 'PUBLISHED': + errorMessage.textContent = 'This post has already been published.'; + break; default: - document.getElementById('error-message').textContent = - jsonResponse?.error_message ?? 'Unknown error'; + status = 'Unknown'; + errorMessage.textContent = + 'Unable to check the post status. Refresh this page to try again.'; break; } - updateView(statusDOMElement, jsonResponse?.status); + updateView(statusDOMElement, status); } function updateView(statusDOMElement, status) { diff --git a/public/scripts/upload.js b/public/scripts/upload.js index f4ec0cb..d08751f 100644 --- a/public/scripts/upload.js +++ b/public/scripts/upload.js @@ -165,6 +165,7 @@ document.addEventListener('DOMContentLoaded', async () => { const topicTagInput = document.getElementById('topic-tag'); const linkAttachmentInput = document.getElementById('link-attachment'); + const locationInput = document.getElementById('location-id'); const replyControlSelect = document.getElementById('reply-control'); const attachmentsList = document.getElementById('attachments-list'); const pollAttachmentOptions = document.getElementById( @@ -173,6 +174,10 @@ document.addEventListener('DOMContentLoaded', async () => { if (ghostPostCheckbox) { ghostPostCheckbox.addEventListener('change', async () => { + if (locationInput) { + locationInput.disabled = ghostPostCheckbox.checked; + if (ghostPostCheckbox.checked) locationInput.value = ''; + } // When ghost post is checked, disable fields that are not relevant to ghost posts if (ghostPostCheckbox.checked) { topicTagMediaControl.style.display = 'none'; diff --git a/src/index.js b/src/index.js index c8d53b7..6702b56 100644 --- a/src/index.js +++ b/src/index.js @@ -28,11 +28,13 @@ const upload = multer(); const DEFAULT_THREADS_QUERY_LIMIT = 10; const MAX_MEDIA_ATTACHMENTS = 20; +const FIELD__ADDRESS = 'address'; const FIELD__ALT_TEXT = 'alt_text'; const FIELD__APPLICATION = 'application'; const FIELD__APP_SCOPED_USER_ID = 'user_id'; +const FIELD__CITY = 'city'; const FIELD__CLICKS = 'clicks'; -const FIELD__ERROR_MESSAGE = 'error_message'; +const FIELD__COUNTRY = 'country'; const FIELD__EXPIRES_AT = 'expires_at'; const FIELD__FOLLOWERS_COUNT = 'followers_count'; const FIELD__HIDE_STATUS = 'hide_status'; @@ -41,7 +43,9 @@ const FIELD__ISSUED_AT = 'issued_at'; const FIELD__IS_REPLY = 'is_reply'; const FIELD__IS_VERIFIED = 'is_verified'; const FIELD__IS_QUOTE_POST = 'is_quote_post'; +const FIELD__LATITUDE = 'latitude'; const FIELD__LIKES = 'likes'; +const FIELD__LONGITUDE = 'longitude'; const FIELD__LINK_ATTACHMENT_URL = 'link_attachment_url'; const FIELD__TOPIC_TAG = 'topic_tag'; const FIELD__MEDIA_TYPE = 'media_type'; @@ -51,6 +55,7 @@ const FIELD__OWNER = 'owner'; const FIELD__GIF_URL = 'gif_url'; const FIELD__PERMALINK = 'permalink'; const FIELD__POLL_ATTACHMENT = 'poll_attachment'; +const FIELD__POSTAL_CODE = 'postal_code'; const FIELD__REPLIES = 'replies'; const FIELD__REPOSTS = 'reposts'; const FIELD__QUOTED_POST = 'quoted_post'; @@ -101,6 +106,7 @@ const PARAMS__HIDE = 'hide'; const PARAMS__INPUT_TOKEN = 'input_token'; const PARAMS__LIMIT = 'limit'; const PARAMS__LINK_ATTACHMENT = 'link_attachment'; +const PARAMS__LOCATION_ID = 'location_id'; const PARAMS__LOCATION_SEARCH_CONFIG = 'location_search_config'; const PARAMS__LOCATION_SEARCH_QUOTA_USAGE = 'location_search_quota_usage'; const PARAMS__MEDIA_TYPE = 'media_type'; @@ -744,15 +750,32 @@ app.get('/publishingLimit', loggedInUserChecker, async (req, res) => { }); app.get('/upload', loggedInUserChecker, (req, res) => { - const { replyToId: replyToID, quotePostId: quotePostID } = req.query; + const { + replyToId: replyToID, + quotePostId: quotePostID, + locationId: rawLocationID = '', + } = req.query; + const locationID = + typeof rawLocationID === 'string' ? rawLocationID.trim() : ''; let title = 'Upload'; if (replyToID !== undefined) title = 'Upload (Reply)'; else if (quotePostID) title = 'Upload (Quote)'; - res.render('upload', { + const values = { title, replyToId: replyToID, quotePostId: quotePostID, - }); + locationId: locationID, + }; + if ( + typeof rawLocationID !== 'string' || + (locationID && !isLocationID(locationID)) + ) { + return res.status(400).render('upload', { + ...values, + error: 'Enter a numeric location ID.', + }); + } + res.render('upload', values); }); app.post('/repost', upload.array(), async (req, res) => { @@ -776,6 +799,28 @@ app.post('/repost', upload.array(), async (req, res) => { } }); +const PUBLISHING_STATUSES = new Set([ + 'ERROR', + 'EXPIRED', + 'FINISHED', + 'IN_PROGRESS', + 'PUBLISHED', +]); +const UNCONFIRMED_PUBLISHING_MESSAGE = + 'Publishing was not confirmed. Check Threads before trying again.'; + +function isPublishingID(id) { + return typeof id === 'string' && /^[1-9]\d*$/.test(id); +} + +function readPublishingID(response) { + const data = response?.data; + if (data?.error || !isPublishingID(data?.id)) { + throw new Error('Invalid publishing response.'); + } + return data.id; +} + const publishingRateLimit = rateLimit({ windowMs: 60 * 1000, limit: 20, @@ -805,6 +850,7 @@ app.post( replyToId, topicTag = '', linkAttachment, + locationId: rawLocationID = '', autoPublishText, pollOptionA, pollOptionB, @@ -900,10 +946,29 @@ app.post( }); } + const locationID = + typeof rawLocationID === 'string' ? rawLocationID.trim() : ''; + if ( + typeof rawLocationID !== 'string' || + (locationID && !isLocationID(locationID)) + ) { + return res.status(400).json({ + error: true, + message: 'Enter a numeric location ID.', + }); + } + if (locationID && ghostPostMedia) { + return res.status(400).json({ + error: true, + message: 'Ghost posts cannot include a location.', + }); + } + const params = { [PARAMS__REPLY_CONTROL]: replyControl, [PARAMS__REPLY_TO_ID]: replyToId, }; + if (locationID) params[PARAMS__LOCATION_ID] = locationID; if (linkAttachment) { params[PARAMS__LINK_ATTACHMENT] = linkAttachment; } @@ -987,66 +1052,57 @@ app.post( } if (params.media_type === MEDIA_TYPE__CAROUSEL) { - const createChildPromises = params.children.map((child) => - axios.post( - buildGraphAPIURL( - `${req.session.user_id}/threads`, - child, - req.session.access_token - ), - {} - ) - ); try { - const createCarouselItemResponse = await Promise.all( - createChildPromises + const responses = await Promise.all( + params.children.map(async (child) => + axios.post( + buildGraphAPIURL( + `${req.session.user_id}/threads`, + child, + req.session.access_token + ), + {} + ) + ) ); - // Replace children with the IDs - params.children = createCarouselItemResponse - .filter((response) => response.status === 200) - .map((response) => response.data.id) + params.children = responses + .map((response) => { + if (response?.status !== 200) + throw new Error('Invalid carousel item response.'); + return readPublishingID(response); + }) .join(','); - } catch (e) { - console.error(e.message); - res.json({ + } catch { + return res.status(502).json({ error: true, - message: `Error creating child elements: ${e}`, + message: 'Unable to create the carousel. Try again.', }); - return; } } - const postThreadsUrl = buildGraphAPIURL( - `${req.session.user_id}/threads`, - params, - req.session.access_token - ); try { + const postThreadsUrl = buildGraphAPIURL( + `${req.session.user_id}/threads`, + params, + req.session.access_token + ); const postResponse = await axios.post( postThreadsUrl, {}, { httpsAgent: agent } ); - const id = postResponse.data.id; - if ( - autoPublishText === 'on' && - params.media_type === MEDIA_TYPE__TEXT - ) { + const id = readPublishingID(postResponse); + if (params[PARAMS__AUTO_PUBLISH_TEXT]) { // If auto_publish_text is on, the returned ID is the published Threads ID. - return res.json({ - redirectUrl: `/threads/${id}`, - }); - } else { - // Otherwise, the returned ID is the container ID. - return res.json({ - id: id, - }); + return res.json({ redirectUrl: `/threads/${id}` }); } - } catch (e) { - console.error(e.message); - res.json({ + return res.json({ id }); + } catch { + return res.status(502).json({ error: true, - message: `Error during upload: ${e}`, + message: params[PARAMS__AUTO_PUBLISH_TEXT] + ? UNCONFIRMED_PUBLISHING_MESSAGE + : 'Unable to create the post. Try again.', }); } } @@ -1065,26 +1121,30 @@ app.get( loggedInUserChecker, async (req, res) => { const { containerId } = req.params; - const getContainerStatusUrl = buildGraphAPIURL( - containerId, - { - [PARAMS__FIELDS]: [FIELD__STATUS, FIELD__ERROR_MESSAGE].join( - ',' - ), - }, - req.session.access_token - ); - + if (!isPublishingID(containerId)) { + return res.status(400).json({ + error: true, + message: 'Enter a numeric container ID.', + }); + } try { - const queryResponse = await axios.get(getContainerStatusUrl, { + const getContainerStatusUrl = buildGraphAPIURL( + encodeURIComponent(containerId), + { [PARAMS__FIELDS]: FIELD__STATUS }, + req.session.access_token + ); + const { data } = await axios.get(getContainerStatusUrl, { httpsAgent: agent, }); - res.json(queryResponse.data); - } catch (e) { - console.error(e.message); - res.json({ + if (data?.error || !PUBLISHING_STATUSES.has(data?.status)) { + throw new Error('Invalid container status response.'); + } + return res.json({ status: data.status }); + } catch { + return res.status(502).json({ error: true, - message: `Error querying container status: ${e}`, + message: + 'Unable to check the post status. Refresh this page to try again.', }); } } @@ -1097,27 +1157,22 @@ app.post( upload.array(), async (req, res) => { const { containerId } = req.body; - const publishThreadsUrl = buildGraphAPIURL( - `${req.session.user_id}/threads_publish`, - { - creation_id: containerId, - }, - req.session.access_token - ); - try { - const postResponse = await axios.post(publishThreadsUrl, { - httpsAgent: agent, - }); - const threadId = postResponse.data.id; - res.json({ - id: threadId, - }); - } catch (e) { - console.error(e.message); - res.json({ + const publishThreadsUrl = buildGraphAPIURL( + `${req.session.user_id}/threads_publish`, + { creation_id: containerId }, + req.session.access_token + ); + const postResponse = await axios.post( + publishThreadsUrl, + {}, + { httpsAgent: agent } + ); + return res.json({ id: readPublishingID(postResponse) }); + } catch { + return res.status(502).json({ error: true, - message: `Error during publishing: ${e}`, + message: UNCONFIRMED_PUBLISHING_MESSAGE, }); } } @@ -1823,6 +1878,143 @@ app.get('/debug', loggedInUserChecker, async (req, res) => { } }); +function isLocationID(locationID) { + return typeof locationID === 'string' && /^[1-9]\d*$/.test(locationID); +} + +const locationSearchRateLimit = rateLimit({ + windowMs: 60 * 1000, + limit: 60, + standardHeaders: 'draft-8', + legacyHeaders: false, + handler: (req, res, _next, options) => { + res.status(options.statusCode).render('location_details', { + title: 'Public Location Search', + q: typeof req.query.q === 'string' ? req.query.q.trim() : '', + locationId: + typeof req.query.locationId === 'string' + ? req.query.locationId.trim() + : '', + error: 'Too many location requests. Wait a minute and try again.', + }); + }, +}); + +app.get('/locationDetails', (req, res) => { + const queryStart = req.originalUrl.indexOf('?'); + const query = queryStart < 0 ? '' : req.originalUrl.slice(queryStart); + return res.redirect(`/locationSearch${query}`); +}); + +app.get( + '/locationSearch', + locationSearchRateLimit, + loggedInUserChecker, + async (req, res) => { + const { locationId = '', q = '' } = req.query; + const values = { + title: 'Public Location Search', + locationId: typeof locationId === 'string' ? locationId.trim() : '', + q: typeof q === 'string' ? q.trim() : '', + }; + const locationID = values.locationId; + if ( + typeof locationId !== 'string' || + (locationID && !isLocationID(locationID)) + ) { + return res.status(400).render('location_details', { + ...values, + error: 'Enter a numeric location ID.', + }); + } + if (typeof q !== 'string') { + return res.status(400).render('location_details', { + ...values, + error: 'Enter a location name.', + }); + } + if (!values.locationId && !values.q) + return res.render('location_details', values); + const params = { + [PARAMS__FIELDS]: [ + FIELD__ID, + FIELD__NAME, + FIELD__ADDRESS, + FIELD__CITY, + FIELD__COUNTRY, + FIELD__LATITUDE, + FIELD__LONGITUDE, + FIELD__POSTAL_CODE, + ].join(','), + }; + if (!values.locationId) params[PARAMS__Q] = values.q; + try { + const url = new URL( + buildGraphAPIURL( + locationID + ? encodeURIComponent(locationID) + : 'location_search', + params, + null + ) + ); + if ( + url.origin !== 'https://graph.threads.com' || + url.username || + url.password || + url.hash + ) { + return res.status(502).render('location_details', { + ...values, + error: 'Unable to load locations. Try again.', + }); + } + if (req.session.access_token) { + url.searchParams.append( + PARAMS__ACCESS_TOKEN, + req.session.access_token + ); + } + const response = await axios.get(url.toString(), { + httpsAgent: agent, + maxRedirects: 0, + }); + if (values.locationId) { + if ( + response.data?.id !== values.locationId || + response.data.error + ) + throw new Error('The API returned an unexpected location.'); + return res.render('location_details', { + ...values, + location: response.data, + }); + } + if (response.data?.error || !Array.isArray(response.data?.data)) { + throw new Error( + 'The API returned an invalid location search response.' + ); + } + const locations = []; + for (const location of response.data.data) { + const rawID = location?.id; + const id = Number.isSafeInteger(rawID) ? String(rawID) : rawID; + if (!isLocationID(id) || id.trim() !== id) continue; + locations.push({ ...location, id }); + } + if (response.data.data.length && !locations.length) { + throw new Error('The API returned no usable locations.'); + } + return res.render('location_details', { ...values, locations }); + } catch { + return res.status(502).render('location_details', { + ...values, + error: 'Unable to load locations. Try again.', + }); + } + } +); + app.get('/keywordSearch', loggedInUserChecker, async (req, res) => { const { keyword, searchType = 'TOP', before, after, limit } = req.query; const { searchMode = 'KEYWORD', since, until } = req.query; diff --git a/test/app-scoped-user-id.test.js b/test/app-scoped-user-id.test.js index c3890c3..7f3f946 100644 --- a/test/app-scoped-user-id.test.js +++ b/test/app-scoped-user-id.test.js @@ -264,7 +264,7 @@ test('reads, paging, carousel creation, and publishing use only the session ID', `/${userId}/threads_publish`, ].includes(u.pathname) ); - return { data: { id: '123' } }; + return { status: 200, data: { id: '123' } }; }, }, userId diff --git a/test/attachment-controls.test.js b/test/attachment-controls.test.js index f1d1f01..35a2042 100644 --- a/test/attachment-controls.test.js +++ b/test/attachment-controls.test.js @@ -55,6 +55,7 @@ test('media hides and disables text attachments, restores drafts, and preserves const fields = { 'media-type': mediaType, 'link-attachment': link, + 'location-id': element('123'), 'poll-attachment-button': pollButton, 'poll-attachment-options': pollOptions, 'attachments-list': attachments, @@ -128,8 +129,13 @@ test('media hides and disables text attachments, restores drafts, and preserves assertTextAttachments(true); assert.equal(pollOptions.style.display, 'block'); assert.equal(controls['.ghost-post-media-control'].style.display, 'none'); + const location = fields['location-id']; + assert.equal(location.value, '123'); + assert.equal(location.disabled, false); ghost.checked = true; await ghost.events.change(); + assert.equal(location.value, ''); + assert.equal(location.disabled, true); assertTextAttachments(false); assert.equal(link.value, ''); assert.deepEqual( @@ -140,6 +146,8 @@ test('media hides and disables text attachments, restores drafts, and preserves assert.equal(pollButton.textContent, 'Attach Poll 🗳️'); ghost.checked = false; await ghost.events.change(); + assert.equal(location.value, ''); + assert.equal(location.disabled, false); assertTextAttachments(true); const html = pug.renderFile(path.join(__dirname, '../views/upload.pug'), { diff --git a/test/attachment-validation.test.js b/test/attachment-validation.test.js index adb0237..6d5feb5 100644 --- a/test/attachment-validation.test.js +++ b/test/attachment-validation.test.js @@ -98,8 +98,9 @@ async function checkError(response, status, message) { assert.deepEqual(await response.json(), { error: true, message }); } -test('upload rejects incompatible attachments before creating any containers', async (t) => { +test('upload validates attachments and applies location tags only to parent containers', async (t) => { const calls = []; + const locationID = '9007199254740993123'; const { request } = await startApp(t, { post: async (url) => { calls.push(new URL(url)); @@ -114,7 +115,7 @@ test('upload rejects incompatible attachments before creating any containers', a const link = { linkAttachment: 'https://example.invalid/' }; for (const [values, message] of [ [ - { ...media, ...link }, + { ...media, ...link, locationId: '0' }, 'Check the post options and attachments, then try again.', ], [ @@ -163,6 +164,7 @@ test('upload rejects incompatible attachments before creating any containers', a ); } assert.equal(calls.length, 5); + assert.equal(calls[0].searchParams.has('location_id'), false); for (const index of [0, 1, 3, 4]) { assert.equal(calls[index].searchParams.has('link_attachment'), false); } @@ -202,7 +204,10 @@ test('upload rejects incompatible attachments before creating any containers', a const start = calls.length; const response = await request( '/upload', - uploadForm(mediaSet(count, mode)) + uploadForm({ + ...mediaSet(count, mode), + ...(mode === 'mixed' && { locationId: locationID }), + }) ); assert.equal(response.status, 200); await response.json(); @@ -211,6 +216,7 @@ test('upload rejects incompatible attachments before creating any containers', a const fields = mediaSet(count, mode); for (const [index, child] of batch.slice(0, -1).entries()) { assert.equal(child.searchParams.get('is_carousel_item'), 'true'); + assert.equal(child.searchParams.has('location_id'), false); assert.equal( child.searchParams.get('media_type'), fields.attachmentType[index].toUpperCase() @@ -221,6 +227,10 @@ test('upload rejects incompatible attachments before creating any containers', a ); } assert.equal(batch.at(-1).searchParams.get('media_type'), 'CAROUSEL'); + assert.equal( + batch.at(-1).searchParams.get('location_id'), + mode === 'mixed' ? locationID : null + ); assert.equal( batch.at(-1).searchParams.get('children').split(',').length, count @@ -239,6 +249,221 @@ test('upload rejects incompatible attachments before creating any containers', a 'No child or parent container request is made.' ); } + const taggedCalls = []; + const statusReads = []; + let failure; + let statusReply; + const { logs, request: taggedRequest } = await startApp(t, { + get: async (url) => { + statusReads.push(new URL(url)); + if (statusReply) return { data: statusReply }; + throw new Error('synthetic-status-marker'); + }, + post: async (url, body, config) => { + const target = new URL(url); + taggedCalls.push({ target, body, config }); + const videoChild = + target.searchParams.has('is_carousel_item') && + target.searchParams.get('media_type') === 'VIDEO'; + if ( + failure === 'reject' || + (failure === 'child-reject' && videoChild) + ) + throw new Error('synthetic-publishing-marker'); + if (failure === 'missing-id') return { status: 200, data: {} }; + if (failure === 'error-ack') { + return { + status: 200, + data: { + id: '999', + error: { message: 'synthetic-publishing-marker' }, + }, + }; + } + const id = failure === 'child-bad-id' && videoChild ? '0' : '999'; + return { status: 200, data: { id } }; + }, + }); + const beforeGhost = [statusReads.length, taggedCalls.length]; + await checkError( + await taggedRequest( + '/upload', + uploadForm({ locationId: locationID, ghostPostMedia: 'true' }) + ), + 400, + 'Ghost posts cannot include a location.' + ); + assert.deepEqual([statusReads.length, taggedCalls.length], beforeGhost); + for (const [values, mediaType] of [ + [{}, 'TEXT'], + [media, 'IMAGE'], + [ + { + attachmentType: ['Video'], + attachmentUrl: ['https://example.invalid/video.mp4'], + }, + 'VIDEO', + ], + [{ autoPublishText: 'on' }, 'TEXT'], + ]) { + const before = taggedCalls.length; + const response = await taggedRequest( + '/upload', + uploadForm({ ...values, locationId: ` ${locationID} ` }) + ); + assert.equal(response.status, 200); + const autoPublish = values.autoPublishText === 'on'; + assert.deepEqual( + await response.json(), + autoPublish ? { redirectUrl: '/threads/999' } : { id: '999' } + ); + assert.equal(taggedCalls.length, before + 1); + const { target } = taggedCalls.at(-1); + assert.equal(target.origin, 'https://graph.threads.com'); + assert.equal(target.pathname, '/456/threads'); + assert.equal(target.searchParams.get('location_id'), locationID); + assert.equal(target.searchParams.get('media_type'), mediaType); + assert.equal( + target.searchParams.get('auto_publish_text'), + autoPublish ? 'true' : null + ); + if (mediaType !== 'TEXT') { + assert.equal( + target.searchParams.get( + mediaType === 'IMAGE' ? 'image_url' : 'video_url' + ), + values.attachmentUrl[0] + ); + } + } + assert.equal( + (await taggedRequest('/upload', uploadForm({ locationId: ' ' }))) + .status, + 200 + ); + assert.equal( + taggedCalls.at(-1).target.searchParams.has('location_id'), + false + ); + const before = taggedCalls.length; + for (const value of ['0', '../me', ['123', '456']]) { + await checkError( + await taggedRequest('/upload', uploadForm({ locationId: value })), + 400, + 'Enter a numeric location ID.' + ); + assert.equal(taggedCalls.length, before); + } + + const published = await taggedRequest( + '/publish', + uploadForm({ containerId: '999' }) + ); + assert.equal(published.status, 200); + assert.deepEqual(await published.json(), { id: '999' }); + assert.equal(taggedCalls.length, before + 1); + const { target: publishTarget, body, config } = taggedCalls.at(-1); + assert.equal(Object.prototype.toString.call(body), '[object Object]'); + assert.deepEqual(Object.keys(body), []); + assert.ok(config?.httpsAgent instanceof https.Agent); + assert.equal(config.httpsAgent, taggedCalls[0].config.httpsAgent); + assert.equal(publishTarget.pathname, '/456/threads_publish'); + assert.equal(publishTarget.searchParams.get('creation_id'), '999'); + assert.equal(publishTarget.searchParams.has('location_id'), false); + + const unconfirmed = + 'Publishing was not confirmed. Check Threads before trying again.'; + for (const mode of ['child-reject', 'child-bad-id']) { + failure = mode; + const before = taggedCalls.length; + await checkError( + await taggedRequest( + '/upload', + uploadForm({ ...mediaSet(2, 'mixed'), locationId: locationID }) + ), + 502, + 'Unable to create the carousel. Try again.' + ); + const children = taggedCalls.slice(before); + assert.equal(children.length, 2); + for (const { target } of children) { + assert.equal(target.pathname, '/456/threads'); + assert.equal(target.searchParams.get('is_carousel_item'), 'true'); + } + assert.equal(statusReads.length, 0); + } + for (const mode of ['reject', 'missing-id']) { + failure = mode; + const before = taggedCalls.length; + await checkError( + await taggedRequest( + '/upload', + uploadForm({ locationId: locationID, autoPublishText: 'on' }) + ), + 502, + unconfirmed + ); + assert.equal(taggedCalls.length, before + 1); + const { target } = taggedCalls.at(-1); + assert.equal(target.pathname, '/456/threads'); + assert.equal(target.searchParams.get('location_id'), locationID); + assert.equal(target.searchParams.get('auto_publish_text'), 'true'); + assert.equal(statusReads.length, 0); + } + for (const mode of ['reject', 'missing-id', 'error-ack']) { + failure = mode; + const before = taggedCalls.length; + await checkError( + await taggedRequest('/publish', uploadForm({ containerId: '999' })), + 502, + unconfirmed + ); + assert.equal(taggedCalls.length, before + 1); + const last = taggedCalls.at(-1); + assert.equal(last.target.pathname, '/456/threads_publish'); + assert.equal(last.target.searchParams.get('creation_id'), '999'); + assert.deepEqual(Object.keys(last.body), []); + assert.equal(last.config.httpsAgent, taggedCalls[0].config.httpsAgent); + assert.equal(statusReads.length, 0); + } + + const beforeStatus = taggedCalls.length; + const statusFailure = + 'Unable to check the post status. Refresh this page to try again.'; + await checkError( + await taggedRequest('/container/status/999'), + 502, + statusFailure + ); + for (const status of ['FINISHED', 'ERROR']) { + statusReply = { + status, + error_message: 'synthetic-status-marker', + id: '999', + }; + const response = await taggedRequest('/container/status/999'); + assert.equal(response.status, 200); + assert.deepEqual(await response.json(), { status }); + } + statusReply = { status: 'synthetic-status-marker' }; + await checkError( + await taggedRequest('/container/status/999'), + 502, + statusFailure + ); + assert.equal(statusReads.length, 4); + await checkError( + await taggedRequest('/container/status/not-an-id'), + 400, + 'Enter a numeric container ID.' + ); + assert.equal(taggedCalls.length, beforeStatus); + assert.equal(statusReads.length, 4); + for (const target of statusReads) { + assert.equal(target.pathname, '/999'); + assert.equal(target.searchParams.get('fields'), 'status'); + } + assert.deepEqual(logs, []); }); test('browser rejects incompatible media attachments before submitting', () => { diff --git a/test/location-details.test.js b/test/location-details.test.js new file mode 100644 index 0000000..5f71337 --- /dev/null +++ b/test/location-details.test.js @@ -0,0 +1,428 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * This source code is licensed under the license found in the + * LICENSE file in the root directory of this source tree. + */ + +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const http = require('node:http'); +const https = require('node:https'); +const path = require('node:path'); +const vm = require('node:vm'); +const { createRequire } = require('node:module'); +const { once } = require('node:events'); +const { test } = require('node:test'); + +const entry = path.join(__dirname, '../src/index.js'); +const appRequire = createRequire(entry); +const exampleLocation = { + id: '123', + name: 'Example Location', + address: 'Example Address', + city: 'Example City', + country: 'Example Country', + latitude: 0, + longitude: 0, + postal_code: 'EXAMPLE', +}; + +async function startApp(t, get, signedIn = true, graphBase) { + let source = fs.readFileSync(entry, 'utf8'); + if (graphBase) { + const declaration = /const GRAPH_API_BASE_URL =[\s\S]*?;/g; + assert.equal(Array.from(source.matchAll(declaration)).length, 1); + source = source.replace( + declaration, + `const GRAPH_API_BASE_URL = ${JSON.stringify(graphBase)};` + ); + } + const app = vm.runInNewContext( + source + '\napp;', + { + __dirname: path.dirname(entry), + process: { + env: { + SESSION_SECRET: 'test-secret', + ...(signedIn && { + INITIAL_ACCESS_TOKEN: 'test-token', + INITIAL_USER_ID: '456', + }), + }, + }, + console: { log() {}, error() {} }, + require(name) { + if (name === 'axios') return { get }; + if (name === 'dotenv') return { config() {} }; + if (name === 'fs') return { readFileSync: () => '' }; + if (name === 'https') + return { ...https, createServer: () => ({ listen() {} }) }; + return appRequire(name); + }, + }, + { filename: entry } + ); + const server = http.createServer(app); + server.listen(0, '127.0.0.1'); + await once(server, 'listening'); + t.after(() => new Promise((resolve) => server.close(resolve))); + const base = `http://127.0.0.1:${server.address().port}`; + let cookie; + return async (route) => { + const response = await fetch(new URL(route, base), { + redirect: 'manual', + signal: AbortSignal.timeout(10000), + headers: { ...(cookie && { cookie }) }, + }); + cookie = response.headers.get('set-cookie')?.split(';')[0] ?? cookie; + return response; + }; +} + +test('location search opens selected details and the prefilled publishing form', async (t) => { + const calls = []; + const longID = '9007199254740993123'; + const query = 'Café & /Menlo Park'; + let results = [ + { + ...exampleLocation, + id: longID, + name: '', + }, + { ...exampleLocation, id: 456 }, + { ...exampleLocation, id: Number.MAX_SAFE_INTEGER + 1 }, + { ...exampleLocation, id: '../me' }, + ]; + const request = await startApp(t, async (url, options) => { + const target = new URL(url); + calls.push(target); + assert.ok(options.httpsAgent); + assert.equal(options.maxRedirects, 0); + assert.equal(target.origin, 'https://graph.threads.com'); + assert.equal(target.searchParams.get('access_token'), 'test-token'); + assert.equal( + target.searchParams.get('fields'), + 'id,name,address,city,country,latitude,longitude,postal_code' + ); + if (target.pathname === '/location_search') { + assert.equal(target.searchParams.get('q'), query); + return { data: { data: results } }; + } + return { + data: { + ...exampleLocation, + id: target.pathname.slice(1), + name: '', + postal_code: undefined, + access_token: 'synthetic-response-token', + }, + }; + }); + const response = await request('/locationSearch?locationId=%20%20123%20'); + assert.equal(response.status, 200); + assert.equal(calls.length, 1); + assert.equal(calls[0].pathname, '/123'); + const html = await response.text(); + assert.match(html, /name="locationId" value="123"/); + assert.match(html, /<script>Example Location<\/script>/); + assert.doesNotMatch(html, /' }, + }, + }, + }, + { + response: { + data: { + error: { + message: + 'provider-secret https://example.invalid/provider', + }, + }, + }, + }, + new Error('client-secret https://example.invalid/client'), + null, // Mismatched ID. + ]) { + lookupFailure = failure; + const response = await request( + '/locationSearch?locationId=123&q=Menlo%20Park' + ); + assert.equal(response.status, 502); + const body = await response.text(); + assert.match(body, /Unable to load locations\. Try again\./); + assert.match(body, /name="locationId" value="123"/); + assert.match(body, /name="q" value="Menlo Park"/); + assert.doesNotMatch( + body, + /Permission denied|provider-secret|client-secret|test-token|example\.invalid|Use In Post|\/upload\?locationId=|Example Address/ + ); + } + for (const failure of [ + searchResult, + { error: { message: 'synthetic-secret' }, data: [] }, + { data: {} }, + { data: [{ id: '../me' }] }, + ]) { + searchResult = failure; + const response = await request('/locationSearch?q=Menlo%20Park'); + assert.equal(response.status, 502); + const body = await response.text(); + assert.match(body, /Unable to load locations\. Try again\./); + assert.match(body, /name="q" value="Menlo Park"/); + assert.doesNotMatch( + body, + /synthetic-secret|test-token|example\.invalid\/private|No locations found|Use In Post|Example Address/ + ); + } +}); + +test('location lookup rate limit stops API work and also bounds signed-out requests', async (t) => { + let calls = 0; + const request = await startApp(t, async (url) => { + calls++; + return { + data: + new URL(url).pathname === '/location_search' + ? { data: [exampleLocation] } + : exampleLocation, + }; + }); + for (let i = 0; i < 60; i++) { + const response = await request( + i === 0 + ? '/locationSearch?q=Menlo%20Park' + : '/locationSearch?locationId=123' + ); + assert.equal(response.status, 200); + await response.text(); + } + const blocked = await request('/locationSearch?q=Menlo%20Park'); + assert.equal(blocked.status, 429); + assert.ok(Number(blocked.headers.get('retry-after')) > 0); + const blockedHTML = await blocked.text(); + assert.match(blockedHTML, /Too many location requests/); + assert.match(blockedHTML, /name="q" value="Menlo Park"/); + assert.equal(calls, 60); + let signedOutCalls = 0; + const signedOut = await startApp( + t, + () => { + signedOutCalls++; + throw new Error('Unexpected API call'); + }, + false + ); + for (let i = 0; i < 60; i++) { + const response = await signedOut('/locationSearch'); + assert.equal(response.status, 302); + await response.text(); + } + assert.equal((await signedOut('/locationSearch')).status, 429); + assert.equal(signedOutCalls, 0); +}); diff --git a/test/publishing-form-errors.test.js b/test/publishing-form-errors.test.js index 3ff2118..da9ea73 100644 --- a/test/publishing-form-errors.test.js +++ b/test/publishing-form-errors.test.js @@ -35,6 +35,17 @@ test('publishing forms display server error messages, safely fall back, and keep { payload: { message: { text: 'Not a string.' } }, expected: fallback }, { payload: null, expected: fallback }, { invalidJson: true, expected: fallback }, + ...['/upload', '/publish'].map((action) => ({ + action, + status: 502, + payload: { + error: true, + message: + 'Publishing was not confirmed. Check Threads before trying again.', + }, + expected: + 'Publishing was not confirmed. Check Threads before trying again.', + })), { ok: true, payload: { id: '123' }, destination: '/threads/123' }, { ok: true, @@ -42,6 +53,7 @@ test('publishing forms display server error messages, safely fall back, and keep destination: '/threads/456', }, ]) { + const action = scenario.action ?? '/publish'; let submit; let calls = 0; const alerts = []; @@ -53,7 +65,7 @@ test('publishing forms display server error messages, safely fall back, and keep }, getAttribute(name) { assert.equal(name, 'action'); - return '/publish'; + return action; }, }; const window = { location: { href: '' } }; @@ -88,7 +100,7 @@ test('publishing forms display server error messages, safely fall back, and keep console: { error() {} }, async fetch(url, options) { calls++; - assert.equal(url, '/publish'); + assert.equal(url, action); assert.equal(options.method, 'POST'); assert.equal(options.mode, 'same-origin'); assert.equal( @@ -96,8 +108,10 @@ test('publishing forms display server error messages, safely fall back, and keep 'synthetic-csrf-token' ); assert.ok(options.body instanceof Form); + const status = scenario.status ?? (scenario.ok ? 200 : 400); return { - ok: scenario.ok === true, + status, + ok: status >= 200 && status < 300, async json() { if (scenario.invalidJson) throw new SyntaxError( @@ -132,3 +146,71 @@ test('publishing forms display server error messages, safely fall back, and keep } } }); + +test('container status only polls while processing and enables publishing when finished', async () => { + const source = fs.readFileSync( + path.join(__dirname, '../public/scripts/publish.js'), + 'utf8' + ); + for (const state of ['Unknown', 'IN_PROGRESS', 'FINISHED']) { + const failed = state === 'Unknown'; + const timers = []; + const logs = []; + let loading = false; + let disabled = true; + let requests = 0; + const fields = { + 'container-id': { getAttribute: () => '999' }, + 'container-status': {}, + 'error-message': {}, + submit: { + removeAttribute(name) { + assert.equal(name, 'disabled'); + disabled = false; + }, + }, + }; + await vm.runInNewContext(source + '\nqueryContainerStatus();', { + document: { + addEventListener() {}, + getElementById: (id) => fields[id], + }, + async fetch(url) { + requests++; + assert.equal(url, '/container/status/999'); + assert.equal(loading, true); + return new Response( + JSON.stringify( + failed + ? { message: 'synthetic-status-marker' } + : { status: state } + ), + { status: failed ? 502 : 200 } + ); + }, + onAsyncRequestStarting() { + loading = true; + }, + onAsyncRequestEnded() { + loading = false; + }, + setTimeout(callback, delay) { + assert.equal(callback.name, 'queryContainerStatus'); + timers.push(delay); + }, + console: { error: (...args) => logs.push(args) }, + }); + assert.equal(requests, 1); + assert.equal(loading, false); + assert.equal(fields['container-status'].innerText, state); + assert.equal( + fields['error-message'].textContent, + failed + ? 'Unable to check the post status. Refresh this page to try again.' + : '' + ); + assert.equal(disabled, state !== 'FINISHED'); + assert.deepEqual(timers, state === 'IN_PROGRESS' ? [5000] : []); + assert.deepEqual(logs, []); + } +}); diff --git a/views/account.pug b/views/account.pug index 9f43712..47fabcf 100644 --- a/views/account.pug +++ b/views/account.pug @@ -23,6 +23,7 @@ block content button(onclick="location.href='/mentions'") My Mentions button(onclick="location.href='/keywordSearch'") Search for Threads button(onclick="location.href='/profileLookup'") Profile Lookup + button(onclick="location.href='/locationSearch'") Public Location Search button(onclick="location.href='/userInsights'") My Insights button(onclick="location.href='/publishingLimit'") Publishing Limit button(onclick="location.href='/debug'") Debug Access Token diff --git a/views/location_details.pug b/views/location_details.pug new file mode 100644 index 0000000..07adbcb --- /dev/null +++ b/views/location_details.pug @@ -0,0 +1,50 @@ +extends layout_with_account + +block content + form(action='/locationSearch' method='GET') + label(for='location-query') Location Name + input#location-query(type='text' name='q' value=q placeholder='Menlo Park' required) + input(type='submit' value='Search Locations') + p Apps without approved location access can search only for Menlo Park. + + if locations + if locations.length + table + thead + tr + th Location ID + th Name + th Address + th City + th Action + tbody + each result in locations + tr + td=result.id + td + a(href=`/locationSearch?locationId=${encodeURIComponent(result.id)}&q=${encodeURIComponent(q)}`)=result.name || result.id + td=result.address + td=result.city + td + a(href=`/upload?locationId=${encodeURIComponent(result.id)}`) Use In Post + else + p No locations found. + + h3 Load a Location ID + form(action='/locationSearch' method='GET') + label(for='location-id') Location ID + input#location-id(type='text' name='locationId' value=locationId inputmode='numeric' placeholder='Enter a location ID…') + input(type='submit' value='Load Location') + + if location + table + thead + tr + th Field + th Value + tbody + each field in [['ID', 'id'], ['Name', 'name'], ['Address', 'address'], ['City', 'city'], ['Country', 'country'], ['Latitude', 'latitude'], ['Longitude', 'longitude'], ['Postal Code', 'postal_code']] + tr + td=field[0] + td=location[field[1]] + a(href=`/upload?locationId=${encodeURIComponent(locationId)}`) Use In Post diff --git a/views/upload.pug b/views/upload.pug index ef9de78..d7ffa6d 100644 --- a/views/upload.pug +++ b/views/upload.pug @@ -50,6 +50,11 @@ block content label(for='topic-tag') Topic Tag input#topic-tag(type='text' name='topicTag' value='' maxlength='50') + div.location-media-control.upload-field + label(for='location-id') Location ID + input#location-id(type='text' name='locationId' value=locationId inputmode='numeric' pattern='[1-9][0-9]*') + a(href='/locationSearch' target='_blank' rel='noopener') Search Locations + div.link-attachment-media-control.upload-field label(for='link-attachment') Link Attachment input#link-attachment(type='text' name='linkAttachment' value='')