heard
HEARD · DOCUMENTATION

Complete WSL installation and deployment

This project deploys the entire mobile application to newdateline.com. It does not require a separate microphone app.

Architecture

iPhone Safari on newdateline.com
  → microphone + optional location permission
  → configurable recording/gain/silence gate
  → API Gateway
  → Python Lambda + ShazamIO
  → DynamoDB history + S3 artwork cache
  → S3 geographic-cell place index + on-demand lookup Lambda
  → same website adds the match to the top of history and highlights it

Uploaded WAV audio is processed in Lambda memory and is not stored. Successful song metadata and location are stored.

What AWS creates

The NewDatelineMusicStack CloudFormation stack creates:

The data table and S3 buckets use RETAIN so a stack removal cannot silently erase stored history or artwork.

1. Requirements

You need:

Docker is not required. The included WSL build script downloads Linux x86-64 Python wheels directly and creates the Lambda asset before CDK runs.

2. Install or verify WSL2

Open PowerShell as Administrator:

wsl --install -d Ubuntu
wsl --list --verbose

Ubuntu must show version 2. If it shows version 1:

wsl --set-version Ubuntu 2

Restart Windows if requested, then open Ubuntu.

3. Install Ubuntu prerequisites

In the Ubuntu terminal:

sudo apt update
sudo apt install -y curl unzip zip jq python3 python3-pip python3-venv

Install Node.js 22 with nvm:

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.3/install.sh | bash
source ~/.bashrc
nvm install 22
nvm use 22
node --version
npm --version

4. Install AWS CLI v2

For a normal Intel/AMD Windows computer:

cd /tmp
curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o awscliv2.zip
unzip -q -o awscliv2.zip
sudo ./aws/install --update
aws --version

Configure credentials:

aws configure
aws sts get-caller-identity

Do not continue until get-caller-identity returns the intended AWS account.

5. Verify newdateline.com DNS

aws route53 list-hosted-zones-by-name --dns-name newdateline.com

The response must include a public hosted zone named newdateline.com. in the same account.

If the domain was registered outside Route 53, configure the registrar to use the four name servers shown in Route 53 for this hosted zone.

6. Extract and move the project into WSL

If the ZIP is in C:\Users\johnp\Downloads:

cd ~
unzip /mnt/c/Users/johnp/Downloads/heard-windows-11-tray-v7103.zip
cd ~/heard-windows-11-tray-v7103/web-aws-source

Running npm and pip from ~/heard-windows-11-tray-v7103/web-aws-source is faster and more reliable than deploying directly under /mnt/c/....

7. Select an AWS region

For an update, reuse the region and account of your existing NewDatelineMusicStack. Do not create a parallel stack in another region. The commands below describe the source default; adjust them to the existing deployment.

This example uses us-west-2 for Lambda, DynamoDB, API Gateway, and S3. CloudFront's certificate is created automatically in us-east-1, as AWS requires.

export AWS_REGION=us-west-2
export AWS_DEFAULT_REGION=us-west-2
aws configure set region us-west-2

8. Deploy

cd ~/heard-windows-11-tray-v7103/web-aws-source
chmod +x deploy.sh build-lambda.sh takeover-domain.sh
./deploy.sh

The script performs these operations:

  1. creates the private S3 geographic-cell index bucket and on-demand lookup Lambda;
  2. installs CDK/TypeScript dependencies;
  3. checks whether this stack already owns a CloudFront distribution;
  4. removes newdateline.com and www.newdateline.com from unrelated CloudFront distributions and waits for those updates;
  5. on the first deployment, deletes conflicting apex/www A, AAAA, or CNAME records from the public Route 53 zone;
  6. creates .lambda-build/identify using Lambda-compatible Linux Python wheels;
  7. compiles TypeScript;
  8. bootstraps CDK for the current account and region;
  9. deploys NewDatelineMusicStack and associates both hostnames with this project.

The domain takeover is automatic and intentionally destructive to the previous hostname routing. It does not delete the old CloudFront distribution or its origin; it only removes these two alternate domain names and their conflicting DNS records.

The first deployment can take several minutes because CloudFront, ACM, and Cognito must be created. Successful output includes SiteUrl, IdentifyApiUrl, HistoryApiUrl, HistoryTableName, PlaceIndexBucketName, PlaceLookupFunctionArn, PlaceIndexFunctionArn, UserPoolId, and UserPoolClientId.

This release resolves the exact LookupFunctionArn output from NewDatelinePlaceLookupStack. Its configured same-account fallback is:

arn:aws:lambda:us-east-1:977083116081:function:NewDatelinePlaceLookupStack-LookupFunctionC8CB8341-IAvrH7WmWgf7

The corresponding Cognito-protected endpoint is https://va9hgx3p3i.execute-api.us-east-1.amazonaws.com/v1/places/nearby. Heard invokes the Lambda through IAM from its backend rather than sending browser or Windows requests directly to that protected endpoint.

Then open:

https://newdateline.com

DNS and CloudFront can take a few additional minutes to become reachable.

9. Build and upload the low-cost place index

After deployment, convert your prepared Overture GeoJSON/GeoJSONL chunks and upload them. The importer uses a temporary SQLite database, so it does not keep a nationwide dataset in memory:

cd ~/heard-windows-11-tray-v7103/web-aws-source
python3 tools/build-place-index.py data/prepared/*.geojsonl \
  --output-dir data/place-index/v1
tools/upload-place-index.sh data/place-index/v1

Gzip-compressed .geojsonl.gz, .ndjson.gz, and normal GeoJSON FeatureCollections are also accepted. The generated objects contain only compact named-place records. A lookup reads the small set of cells intersecting the configured radius, calculates exact Haversine distances in Lambda, deduplicates names, and returns the same bestMatch/matches/alternatives contract used by the web and Windows apps.

Deployment automatically discovers the lookup Lambda in NewDatelinePlaceLookupStack and merges its Nearby Places API results with the S3 index and OpenStreetMap results. You can still explicitly set PLACE_LOOKUP_FUNCTION_ARN when the Lambda lives in a differently named stack. Set DISABLE_NEARBY_PLACES_API=1 only when you intentionally want to bypass the external service. Until an index is uploaded, OpenStreetMap remains available as a best-effort fallback.

The importer includes named places, address-only features, and unnamed residential buildings. If an index was generated with Heard 7.48, rebuild it using --replace-output and upload it again. The manual correction dialog also queries current OpenStreetMap data and always permits a typed place name, so a user is not limited to what exists in the imported snapshot.

See COST-REDUCTION.md for verification and safe retirement of the old RDS stack.

10. Idempotent redeployment

To publish later changes:

cd ~/heard-windows-11-tray-v7103/web-aws-source
./deploy.sh

The stack name and resource IDs remain stable, so CloudFormation updates the same project. In particular, retain NewDatelineMusicStack, the UserPool construct ID, and the WebClient child ID: repeat deployments then preserve the existing Cognito user pool, users, and browser client. Do not rename NewDatelineMusicStack unless you intentionally want a separate deployment.

On repeat deployments, takeover-domain.sh discovers this stack's existing CloudFront physical resource ID and preserves its aliases and Route 53 records. This prevents the preflight from disconnecting its own site.

The site application shell deliberately uses no-store/no-cache and a disabled CloudFront cache policy. This ensures phone browsers receive the current controller after each deployment instead of retaining an older or blank application shell.

Preview infrastructure changes before deployment:

cd ~/heard-windows-11-tray-v7103/web-aws-source
./build-lambda.sh
cd infra
npm install
npm run build
npx cdk diff

11. Use the website on iPhone

  1. Open Safari on the iPhone.
  2. Visit https://newdateline.com.
  3. Tap the gear icon.
  4. Review the sample interval, sample length, gain, minimum RMS, and location setting.
  5. Tap Save configuration.
  6. Tap Start.
  7. Allow microphone access.
  8. Allow location access if you want locations saved.
  9. Keep the browser visible and the screen awake; the device may suspend background recording.
  10. Tap Stop when finished.

The site attempts another sample according to the saved interval. Settings are stored in Safari local storage on that phone. Stop and restart listening after changing them.

Device authorization is automatic and there is no password panel. The product eyebrow is removed from the mobile header, Start and Stop are condensed to 38 pixels and remain side by side, and listener status plus instructions share one visually separated line.

The page heading is heard, displayed in a large bold fixed-width console font. The map, its view controls, and the separate just-identified result panel have been removed; identified-song history is the single results view. A newly identified song is inserted at the top and remains strongly highlighted until another song is identified or a different song row is selected. The configuration dialog uses two compact panes on wider screens and automatically changes to a tight single-column layout on phones or short displays.

Tap any identified-song row to open its music-services dialog. Spotify uses the matched URL when ShazamIO provides one and otherwise uses search. Apple Music, Amazon Music, and YouTube open searches for the identified artist and title.

The compact share dialog automatically creates a private snapshot link containing today's identified songs, the latest three displayed song groups, or all identified songs. Changing the radio selection immediately replaces the displayed URL. Its option text wraps beside small radio controls without horizontal scrolling, the small link text has a dedicated copy icon, and its actions stack on narrow phones. Multiple generated links remain valid independently.

Shared-history metadata uses DynamoDB expression aliases for every projected field, including scope, so copied links do not fail on reserved expression words. Links created by v46 remain compatible after deploying this fix.

History is sorted into newest-first date sections; the current day's date heading is omitted. Consecutive detections are combined when the normalized artist and title match, each adjacent detection is within 10 minutes, and the coordinates are within 500 feet (152.4 meters). If records do not contain coordinates, an exact normalized business/address match is used; consecutive matching records that both have no location are also combined. A combined row displays its first-to-last time range and remains clickable for music-service links. The same rules are applied in shared history. The history Lambda walks DynamoDB pages and returns up to the latest 2,000 identifications.

Swipe a song row left on iPhone to reveal Delete. Deleting a combined row removes every underlying identification represented by that row. This is permanent DynamoDB deletion and is available only in the authenticated owner view.

Optional cross-device account

Tap the person icon to sign in or create an account. Both flows ask for email first and password second. Passwords require at least eight characters but do not require uppercase, lowercase, digits, symbols, or any particular character type. If Create account finds an existing confirmed email, it starts password recovery; if the registration is unconfirmed, it sends a fresh verification code before password recovery.

The user pool uses Cognito-managed verification email, not SES sandbox delivery, so any valid registration email can receive its own confirmation code subject to Cognito quotas and normal spam filtering. To resend confirmation mail to every currently unconfirmed profile after deployment, run ./resend-unconfirmed-verifications.sh from WSL.

Anonymous history remains tied to the authorized device. On sign-in, that device history is copied idempotently to the Cognito account; subsequent identifications use the account partition. Signing into the same account on another authorized phone or computer shows the same history and imports that device's existing anonymous rows.

Use the share arrow to create an unguessable, read-only history URL for the current device or signed-in account. Choose Today, Latest three, or All songs, and use the compact, checked-by-default options to include or exclude location and time. The link updates automatically whenever any option changes. The dialog offers a copy icon, Text link (opening Messages/contact selection on a phone), and the native iPhone share sheet. Previously generated links remain valid with their own saved settings; older links default to showing both location and time. A shared page does not expose listening, account, settings, sharing, deletion controls, or a link back to the owner's playlist. Anyone holding a URL can read only that link's selected snapshot.

Test alternate visual styles

Open https://newdateline.com/?test=1 to display the Test style dropdown in the upper-right area. It includes the original appearance and 20 alternate treatments covering color, typography, padding, density, corners, and shadows. The last test selection is remembered in that browser, but it is applied only while the exact test=1 query parameter is present. Normal URLs retain the production appearance and do not show the selector.

Nearby photo thumbnails

Nearby-photo lookup is disabled by default. Turn on Enable nearby photos in the Nearby photos configuration pane to show photo controls and permit photo-lookup requests. Turning it off removes those controls and prevents the browser from requesting nearby photos. Saving the setting refreshes history immediately.

The deployed browser configuration uses the supplied live New Dateline endpoints:

Auth:     https://v3ta3c6zxh.execute-api.us-east-1.amazonaws.com/auth
History:  https://v3ta3c6zxh.execute-api.us-east-1.amazonaws.com/history
Identify: https://v3ta3c6zxh.execute-api.us-east-1.amazonaws.com/identify
Photos:   https://v3ta3c6zxh.execute-api.us-east-1.amazonaws.com/photos
Photo lookup: https://v3ta3c6zxh.execute-api.us-east-1.amazonaws.com/photo-lookup
Site:     https://newdateline.com

The stack-managed history table remains NewDatelineMusicStack-Identifications2FF1D72A-R34RP4R9Z695. It provides the device/share authorization records checked by /photos; the browser never accesses DynamoDB directly. To recover after intentionally recreating the API, set NEW_DATELINE_API_BASE before deployment. Normal repeat deployments use the supplied base automatically.

When nearby photos are enabled, the browser lazily requests photos for a song with stored coordinates as its row approaches the screen. The server queries PhotoLookupServiceStack for images taken within the configured number of hours before or after the song and within the configured distance (200 feet by default). Matches appear behind a Photos (N) disclosure that is collapsed by default. Expand it to see up to three random thumbnails and, when more exist, the all-photo gallery button. Tap a thumbnail to open the full image. If no photos match—or the photo service is temporarily unavailable—the row remains unchanged and no photo message or empty placeholder is shown.

After expanding Photos (N), up to three randomly selected matches appear beneath the song. If the lookup returned more than three, an … button appears after them. Tap it to open a responsive gallery containing thumbnails for every returned result; tap any gallery thumbnail to open the full picture. With three or fewer matches, every result appears in the expanded panel and the … button is omitted.

The configuration dialog includes Photo matching distance, configurable from 25 to 5,000 feet and defaulting to 200 feet, plus Photo time window, configurable from 0.08 to 720 hours and defaulting to 0.33 hours (approximately 20 minutes before and after the song). It also includes Ignore photo date/time, which is off by default. When enabled, the time-window control is disabled, the request omits the date range, and matching uses only the song's coordinates and configured distance. These preferences are saved on the individual phone and photo rows refresh immediately after saving; microphone-related settings still apply after Save timing for the next sample; restart for other recording settings.

This deployment reads the PhotoLookupFunctionArn output from PhotoLookupServiceStack. The expected value in this AWS account is:

arn:aws:lambda:us-east-1:977083116081:function:icloud-photo-lookup-query

That ARN is also included as the fallback if CloudFormation output discovery is unavailable. To point at a different compatible function:

export PHOTO_LOOKUP_FUNCTION_ARN='arn:aws:lambda:us-east-1:123456789012:function:photo-lookup'
./deploy.sh
unset PHOTO_LOOKUP_FUNCTION_ARN

The phone calls the New Dateline /photo-lookup route. /photos remains a backward-compatible alias. Its Lambda invokes icloud-photo-lookup-query through the service's same-account direct invocation contract using start, end, lat, lon, and radius_feet. The underlying service is not called directly by Safari. For normal matching, the query window is exactly 20 minutes before through 20 minutes after the song and the default radius is 200 feet.

When Ignore photo date/time is enabled, New Dateline scans icloud-photo-metadata-977083116081-us-east-1, filters by Haversine distance only, and creates 15-minute signed URLs for objects in icloud-photos-ndaccgog. The table path also serves as a fallback if the shared lookup function fails. The Lambda walks every table page internally in bounded 250-record reads, then returns one complete, deduplicated result to the browser. Every unique photo within the configured radius is retained regardless of its time or date; there is no 24-photo collection cap in this mode.

If no matches exist or either lookup path is unavailable, the song row shows no photo text, error, or placeholder. Safe progress and error details are written to Safari's browser console, and backend failures are written to the PhotosFn CloudWatch log group. The route accepts either the owner's authorized-device token or a currently valid shared-history token, so thumbnails also load for recipients of a shared playlist. Songs without stored coordinates are intentionally skipped because a 200-foot location comparison is impossible. This project stores no duplicate images.

An empty response from the shared PhotoLookup Lambda is now verified against the metadata table rather than accepted immediately. If a generated JPEG preview cannot load, the browser retries that thumbnail with the signed original object and removes the photo silently only if both fail.

Every ./deploy.sh run finishes with ./test-photo-lookup.sh. The test selects a real GPS-indexed metadata record, invokes icloud-photo-lookup-query with that record's own ±20-minute/200-foot window, and confirms that both preview and original URLs are returned. It reports counts only and does not download or display the private image. If the table has no GPS metadata, the lookup returns no match, or URLs are missing, deployment exits with a specific repair message. You can rerun the test independently at any time:

./test-photo-lookup.sh

The Chrome console message A listener indicated an asynchronous response ... message channel closed originates from a browser-extension message listener; this project does not register Chrome runtime message listeners. Version 17 prevents that exact rejected promise from interrupting page logic when the browser exposes it to the page. If Chrome still prints it with extensions enabled, reproduce in Incognito with extensions disabled to identify the extension; it is independent of the photo API.

Permanent device authorization

The browser sends the entered password only to the /auth Lambda over HTTPS. The Lambda retrieves the authoritative value from AWS Secrets Manager. The password is not present in index.html, app.js, config.js, or local storage.

On first use, AWS automatically issues a random 256-bit device token. Safari stores that token locally and sends it with history and recognition requests. DynamoDB stores only the token's SHA-256 hash. The authorization record has no expiration.

The device remains unlocked until one of these occurs:

Changing the password in Secrets Manager does not revoke previously authorized device tokens.

Change the AWS password later

For a one-time deployment with another password:

export NEW_DATELINE_PASSWORD='your-new-password'
./deploy.sh
unset NEW_DATELINE_PASSWORD

With no environment override, deployment stores listenup as requested. Never place the password in the website files.

Setting Starting value Purpose
Sample interval 120 seconds Starts one attempt every two minutes
Sample length 10 seconds Provides ShazamIO a useful clip
Microphone gain 2× Raises quieter background music
Minimum audio RMS 0.00010 Skips extremely quiet samples
Save location On Stores business/address/coordinates

If background music is being skipped, lower Minimum Audio RMS to 0.00005 or increase gain to 3. Very high gain can distort the sample and reduce recognition quality.

12. Restore iPhone permissions

If microphone access was denied:

  1. Open iPhone Settings.
  2. Open Apps → Safari → Microphone.
  3. Allow access.
  4. Reload newdateline.com.

For location:

  1. Open Settings → Privacy & Security → Location Services.
  2. Select Safari Websites.
  3. Choose While Using the App.
  4. Enable Precise Location.

13. iPhone background limitation

The listener runs only while Safari keeps the page active. iOS may pause JavaScript and microphone input when:

The site requests a screen wake lock when the browser supports it, but the mobile operating system remains in control. For reliable mobile listening, keep the browser visible and connect the phone to power for long sessions. Desktop recording and history updates continue while the webpage remains open in a window or tab.

14. Location behavior

Location resolution follows this order:

  1. closest named OpenStreetMap business or building within 200 feet;
  2. street address;
  3. latitude and longitude;
  4. Location unavailable if permission was denied or location failed.

Business/building identification first reverse-geocodes the phone coordinate, then searches named OpenStreetMap businesses and buildings within 200 feet (60.96 meters) and selects the closest mapped candidate by calculated distance. If the nearby lookup is unavailable or has no candidate, the reverse-geocoded feature remains the fallback. In a mall, office building, dense block, or multi-tenant property, the closest mapped place may still differ from the exact room or business.

The history interface displays one compact place line for each song: the highlighted business/building name first, followed by a • separator and the resolved location. The literal “Building/business” label is omitted. Older records remain compatible; when no business is stored, the location appears by itself.

15. Troubleshooting

spawnSync docker ENOENT

This project does not use Docker. Confirm you are deploying newdateline-mobile-music-complete, not the earlier AggCog/AppCog package. The stack in the error must be NewDatelineMusicStack, not AggCogMusicStack.

pip says no matching distribution

First update pip:

python3 -m pip install --user --upgrade pip

Then rerun:

./build-lambda.sh

The script intentionally requires compatible Linux x86-64 manylinux wheels for the Python 3.12 Lambda runtime, so compiled Windows files cannot accidentally enter the package.

CDK cannot find the hosted zone

Confirm credentials and zone ownership:

aws sts get-caller-identity
aws route53 list-hosted-zones-by-name --dns-name newdateline.com

CloudFront says the CNAME is already associated

The automatic takeover normally removes this conflict. Confirm jq is installed and review the takeover-domain.sh output. You can rerun the preflight safely:

cd ~/heard-windows-11-tray-v7103/web-aws-source
./takeover-domain.sh

Then run ./deploy.sh again. The preflight preserves the current NewDatelineMusicStack distribution but detaches the hostnames from any other distribution.

Site loads but history/identification fails

Open AWS Console → CloudWatch → Log groups and inspect the log groups containing IdentifyFn and HistoryFn. Also confirm the generated config.js was deployed and the API URL is reachable.

Automatic device authorization fails

Confirm the generated config.js points to the deployed /auth endpoint, then inspect the CloudWatch log group containing AuthFn. Redeploy with ./deploy.sh after correcting any API or Lambda error.

The site is blank after an update

Deploy this corrected version with ./deploy.sh, wait for CloudFormation to finish, then close the Safari tab and reopen https://newdateline.com. The deployment invalidates /*, disables CloudFront caching for the application shell, and gives browser assets a versioned URL. If Safari still displays an older page, use iPhone Settings → Apps → Safari → Advanced → Website Data, remove data for newdateline.com, and reopen the site.

Microphone permission never appears

Microphone access requires HTTPS and a direct user action. Open the production HTTPS URL in Safari and tap Start. It will not work from a local file or plain HTTP URL.

Samples are always skipped

Open Settings, reduce Minimum Audio RMS, increase microphone gain, save, stop, and restart. Confirm iPhone microphone openings are not blocked by a case or clothing.

Shazam returns no match

Try a louder or clearer musical section. Speech, crowd noise, live versions, remixes, instrumental intros, and distant music may not match.

16. Cost and security notes

The API is public so a phone can use it without signing in. The Lambda has reserved concurrency to limit simultaneous recognition work, but a publicly shared URL can still incur AWS charges. Configure an AWS Budget alert before wide distribution.

The reverse-geocoder is a best-effort public OpenStreetMap Nominatim request. For high traffic, replace it with a contracted geocoding provider and follow that provider's usage terms.

17. Stack outputs and removal

View outputs:

aws cloudformation describe-stacks \
  --stack-name NewDatelineMusicStack \
  --query 'Stacks[0].Outputs' \
  --output table

Destroy active resources only when you intend to remove the site:

cd ~/heard-windows-11-tray-v7103/web-aws-source/infra
npx cdk destroy

This is destructive. Retained DynamoDB and S3 resources remain after stack deletion and may continue to incur storage charges.