Skip to content

Conversation

@apoorvajainrp21
Copy link

Description

Backend implementation for Mastodon auto-poster feature, providing API endpoints for posting, scheduling, and managing social media content.

Related PRS (if any):

To test this backend PR you need to checkout the #4558 frontend PR.

Features Implemented

  • ✅ RESTful API with 5 endpoints
  • ✅ Image upload to Mastodon with alt text support
  • ✅ Scheduled posts with MongoDB storage
  • ✅ Automated cron job (runs every minute)
  • ✅ Post history retrieval from Mastodon
  • ✅ Two-step image upload (upload + update alt text)
  • ✅ Comprehensive error handling

Main Changes

New Files:

  • src/controllers/mastodonPostController.js - Main API controller with image upload logic
  • src/cronjobs/mastodonScheduleJob.js - Cron job for processing scheduled posts
  • src/routes/mastodonRouter.js - RESTful API routes
  • src/models/mastodonSchedule.js - MongoDB schema for scheduled posts

Modified Files:

  • src/server.js - Added mastodon routes and cron job initialization
  • package.json - Added form-data dependency
  • package-lock.json - Updated lock file

API Endpoints

POST /api/mastodon/createPin

Post immediately to Mastodon

{
  title: string,
  description: string,
  imgType: 'FILE' | 'URL',
  mediaItems: string (base64),
  mediaAltText: string (optional),
  crossPostTo: string[] (optional)
}

POST /api/mastodon/schedule

Schedule a post for later

{
  title: string,
  description: string,
  imgType: 'FILE' | 'URL',
  mediaItems: string (base64),
  mediaAltText: string (optional),
  scheduledTime: string (ISO 8601),
  crossPostTo: string[] (optional)
}

GET /api/mastodon/schedule

Fetch all scheduled posts

DELETE /api/mastodon/schedule/:id

Delete a scheduled post by ID

GET /api/mastodon/history?limit=20

Fetch post history from Mastodon API

Technical Implementation

Image Upload Process (Two-Step)

  1. Convert base64 to Buffer
  2. Upload to Mastodon /api/v1/media → get media ID
  3. Update media with alt text via PUT /api/v1/media/:id
  4. Attach media ID to post

Why two steps? Mastodon API requires alt text to be set separately after upload.

Cron Job Flow

  1. Runs every minute (* * * * *)
  2. Queries MongoDB for posts where scheduledTime <= now
  3. Uploads images to Mastodon (with alt text)
  4. Posts to Mastodon API
  5. Deletes from MongoDB on success
  6. Logs errors without stopping other posts

Error Handling

  • Try-catch blocks around all API calls
  • Continue posting other scheduled items if one fails
  • Graceful degradation (post without image if upload fails)
  • Detailed logging for debugging

Environment Variables Required

Add to .env:

MASTODON_ENDPOINT=https://mastodon.social
MASTODON_ACCESS_TOKEN=your_mastodon_access_token_here

To get access token:

  1. Go to your Mastodon instance → Preferences → Development
  2. Create new application
  3. Set scopes: read write
  4. Copy access token

How to Test

Setup:

  1. Checkout this branch: apoorva-mastodon-autoposter
  2. Checkout frontend PR: apoorva-mastodon-autoposter
  3. Add environment variables to .env
  4. Run: npm install
  5. Run: npm run build
  6. Run: npm start
  7. ✅ Verify server starts without errors
  8. ✅ Verify cron job initializes: "✅ Mastodon schedule cron job started"

Test Endpoints:

1. POST Immediately (with image + alt text)

curl -X POST http://localhost:4500/api/mastodon/createPin \
  -H "Content-Type: application/json" \
  -d '{
    "title": "Test Post",
    "description": "Testing image with alt text",
    "imgType": "FILE",
    "mediaItems": "data:image/png;base64,iVBORw0KGgo...",
    "mediaAltText": "Description of image for screen readers"
  }'

✅ Verify post appears on Mastodon
✅ Verify image has alt text (inspect HTML)

2. Schedule Post

curl -X POST http://localhost:4500/api/mastodon/schedule \
  -H "Content-Type: application/json" \
  -d '{
    "title": "Scheduled Post",
    "description": "This will post in 2 minutes",
    "scheduledTime": "2025-12-14T10:30:00.000Z",
    "imgType": "FILE",
    "mediaItems": "data:image/png;base64,iVBORw0KGgo...",
    "mediaAltText": "Alt text here"
  }'

✅ Verify saves to MongoDB
✅ Wait 2 minutes
✅ Verify cron job posts it
✅ Verify removes from MongoDB

3. Fetch Scheduled Posts

curl http://localhost:4500/api/mastodon/schedule

✅ Verify returns array of scheduled posts

4. Delete Scheduled Post

curl -X DELETE http://localhost:4500/api/mastodon/schedule/[POST_ID]

✅ Verify removes from MongoDB

5. Fetch Post History

curl http://localhost:4500/api/mastodon/history?limit=20

✅ Verify returns last 20 posts from Mastodon
✅ Verify includes engagement metrics (likes, reblogs)

Integration Test with Frontend:

  1. Run both frontend and backend
  2. Test all features through UI
  3. Monitor backend logs for errors
  4. Check MongoDB for scheduled posts
  5. Verify cron job processes posts on time

Code Quality

  • ✅ ESLint compliant
  • ✅ Async/await instead of callbacks
  • ✅ Promise.all for parallel processing
  • ✅ No for-of loops (uses map + Promise.all)
  • ✅ Proper error logging
  • ✅ CamelCase with eslint-disable for Mastodon API fields

Dependencies Added

  • form-data@^4.0.0 - For multipart/form-data image uploads to Mastodon API

Database Schema

mastodonschedules collection:

{
  _id: ObjectId,
  postData: String (JSON stringified),
  scheduledTime: Date,
  createdAt: Date,
  updatedAt: Date
}

Security Considerations

  • Access token stored in environment variables (not committed)
  • Base64 images stored temporarily in MongoDB
  • No sensitive data logged
  • Proper CORS headers maintained

Performance

  • Cron job uses Promise.all for parallel processing
  • Images uploaded only when posting (not stored long-term)
  • MongoDB queries optimized with indexes
  • Graceful error handling prevents cascade failures

Known Issues

None at this time

Future Enhancements

  • Support multiple images (up to 4)
  • Implement actual cross-posting to other platforms
  • Add retry logic for failed posts
  • Add post analytics tracking
  • Support for video uploads

tanmay-ar0ra and others added 2 commits October 29, 2025 17:12
- Implement mastodonPostController with image upload and alt text
- Add cron job for scheduled post processing
- Create mastodonRouter with RESTful endpoints
- Add form-data dependency for media uploads
- Integrate with Mastodon API v1
@one-community one-community added the High Priority - Please Review First This is an important PR we'd like to get merged as soon as possible label Jan 2, 2026
@one-community one-community changed the title feat: Add Mastodon API integration backend Apoorva - feat: Add Mastodon API integration backend Jan 2, 2026
Copy link

@Anusha-Gali Anusha-Gali left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi Apoorva,

I have reviewed your PR locally and the backend does work as per requirement.
Screenshot 2026-01-07 at 4 39 23 PM
Screenshot 2026-01-07 at 4 39 30 PM
Screenshot 2026-01-07 at 4 45 54 PM
Screenshot 2026-01-07 at 4 46 17 PM
Screenshot 2026-01-07 at 4 46 33 PM

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

High Priority - Please Review First This is an important PR we'd like to get merged as soon as possible

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants