diff --git a/src/index.js b/src/index.js index 6702b56..b0afdcd 100644 --- a/src/index.js +++ b/src/index.js @@ -47,6 +47,7 @@ const FIELD__LATITUDE = 'latitude'; const FIELD__LIKES = 'likes'; const FIELD__LONGITUDE = 'longitude'; const FIELD__LINK_ATTACHMENT_URL = 'link_attachment_url'; +const FIELD__LOCATION_ID = 'location_id'; const FIELD__TOPIC_TAG = 'topic_tag'; const FIELD__MEDIA_TYPE = 'media_type'; const FIELD__MEDIA_URL = 'media_url'; @@ -1301,6 +1302,21 @@ app.get( is_ghost_post, }; postLoaded = true; + if (/^\d+$/.test(threadId)) { + try { + const locationUrl = buildGraphAPIURL( + threadId, + { [PARAMS__FIELDS]: FIELD__LOCATION_ID }, + req.session.access_token + ); + const locationResponse = await axios.get(locationUrl, { + httpsAgent: agent, + }); + data.location_id = locationResponse.data?.location_id; + } catch { + data.location_id = undefined; + } + } } catch (e) { error = e?.response?.data?.error?.message ?? e.message; console.error(error); @@ -1733,7 +1749,7 @@ app.get( } res.render('thread_insights', { - title: 'Thread Insights', + title: 'Media Insights', threadId, metrics, since, diff --git a/test/own-post-deletion.test.js b/test/own-post-deletion.test.js index 2a44093..9813ec3 100644 --- a/test/own-post-deletion.test.js +++ b/test/own-post-deletion.test.js @@ -276,8 +276,12 @@ test('owned detail shows Delete after Quote and Repost and reuses the existing g const reads = []; const readConfigs = []; api.get = async (url, config) => { - reads.push(new URL(url)); + const read = new URL(url); + reads.push(read); readConfigs.push(config); + if (read.searchParams.get('fields') === 'location_id') { + return { data: {} }; + } return get(url, config); }; const remove = api.delete; @@ -288,9 +292,10 @@ test('owned detail shows Delete after Quote and Repost and reuses the existing g }; const request = await startApp(t, api); const html = await (await request('/threads/123')).text(); + assert.equal(reads[1].searchParams.get('fields'), 'location_id'); assert.deepEqual( readConfigs.map((config) => config.maxRedirects), - [undefined, 0, 0, 0] + [undefined, undefined, 0, 0, 0] ); const quotePosition = html.indexOf('Quote'); const repostPosition = html.indexOf('Repost'); diff --git a/test/post-details-rate-limit.test.js b/test/post-details-rate-limit.test.js index 82dfb6a..573ba37 100644 --- a/test/post-details-rate-limit.test.js +++ b/test/post-details-rate-limit.test.js @@ -127,9 +127,15 @@ test('Post Details rejects excess requests before authentication and API work', /Too many post detail requests\. Wait a minute and try again\./ ); assert.ok(Number(blocked.headers.get('retry-after')) > 0); + assert.doesNotMatch( + blocked.text, + /action="\/repost"|quotePostId=|\/undefined/ + ); assert.deepEqual({ reads, authChecks }, before); assert.equal(authChecks, 60); - assert.equal(reads, signedIn ? 181 : 0); + // Each signed-in request loads the post, location, and two ownership records. + // The session's token binding is verified once. + assert.equal(reads, signedIn ? 241 : 0); assert.equal( (await request('/upload')).status, signedIn ? 200 : 302, diff --git a/test/post-details-ui.test.js b/test/post-details-ui.test.js index bed733b..87a2029 100644 --- a/test/post-details-ui.test.js +++ b/test/post-details-ui.test.js @@ -93,6 +93,14 @@ async function startApp(t, post, owner = '456', probe = {}) { return { get: async (url, config) => { const parsed = new URL(url); + if ( + parsed.searchParams.get('fields') === + 'location_id' + ) { + reads.push(parsed); + assert.ok(config.httpsAgent); + return { data: {} }; + } const stage = parsed.pathname === '/debug_token' ? 'token' @@ -514,12 +522,13 @@ test('Insights visibility requires verified ownership independently of deletion ); assert.equal( reads.length, - scenario.expectedReads ?? - (scenario.probe?.failToken || - scenario.probe?.tokenUserID || - scenario.probe?.tokenValid === false - ? 2 - : 4) + 1 + + (scenario.expectedReads ?? + (scenario.probe?.failToken || + scenario.probe?.tokenUserID || + scenario.probe?.tokenValid === false + ? 2 + : 4)) ); const probeFailed = scenario.probe?.failOwner || diff --git a/test/post-location.test.js b/test/post-location.test.js new file mode 100644 index 0000000..c6b2ea1 --- /dev/null +++ b/test/post-location.test.js @@ -0,0 +1,169 @@ +/** + * 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); + +async function startApp(t, get, signedIn = true) { + const app = vm.runInNewContext( + fs.readFileSync(entry, 'utf8') + '\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('post location IDs link to location details while poll and ghost fields keep working', async (t) => { + const calls = []; + let locationId = '345'; + let locationUnavailable = false; + const request = await startApp(t, async (url, options) => { + const apiUrl = new URL(url); + calls.push(apiUrl); + if (apiUrl.pathname === '/123/insights') return { data: { data: [] } }; + if (apiUrl.pathname === '/debug_token') { + assert.equal(options.maxRedirects, 0); + return { data: { data: { is_valid: true, user_id: '456' } } }; + } + if (apiUrl.pathname === '/456') { + assert.equal(options.maxRedirects, 0); + return { data: { id: '456' } }; + } + if (apiUrl.searchParams.get('fields') === 'id,media_type,owner') { + assert.equal(options.maxRedirects, 0); + return { data: { id: '123', owner: { id: '456' } } }; + } + if (apiUrl.pathname === '/345') + return { data: { id: '345', name: 'Example Location' } }; + if (apiUrl.searchParams.get('fields') === 'location_id') { + if (locationUnavailable) + throw new Error('Optional location field unavailable.'); + return { data: { location_id: locationId } }; + } + return { + data: { + text: 'Example post', + poll_attachment: { option_a: 'Option A', option_b: 'Option B' }, + ghost_post_status: 'ACTIVE', + access_token: 'synthetic-response-token', + }, + }; + }); + const html = await (await request('/threads/123')).text(); + assert.equal(calls[0].pathname, '/123'); + assert.ok( + !calls[0].searchParams.get('fields').split(',').includes('location_id') + ); + assert.equal(calls[1].pathname, '/123'); + assert.equal(calls[1].searchParams.get('fields'), 'location_id'); + assert.match( + html, + /Location ID<\/td>345<\/a>/ + ); + assert.match(html, /Option A/); + assert.match(html, /Is Ghost Post<\/td>true<\/td>/); + assert.doesNotMatch( + html, + /test-token|synthetic-response-token|access_token/ + ); + const linked = await ( + await request('/locationSearch?locationId=345') + ).text(); + assert.match(linked, /Example Location/); + assert.match( + await (await request('/threads/123/insights')).text(), + /

Media Insights<\/h1>/ + ); + for (const value of [ + undefined, + '', + '0', + '0123', + '', + { id: '345' }, + ]) { + locationId = value; + const untagged = await (await request('/threads/123')).text(); + assert.match(untagged, /Example post/); + assert.doesNotMatch( + untagged, + /Location ID<|locationId=|