[nextjs]SNS Server-15(myapp25)

πŸ‘‰πŸ» myapp25μ—μ„œλŠ” λΆ€μŠ€νŠΈν•˜λŠ” 경우 λ‚΄ νŒ”λ‘œμ›Œμ—κ²Œ 글을 μ „λ‹¬ν•˜λŠ” κΈ°λŠ₯을 κ΅¬ν˜„ν•©λ‹ˆλ‹€.
In myapp25, we are implementing a feature that delivers posts to your followers when you “boost” them.

πŸ“ 전체 ν”„λ‘œμ νŠΈ ꡬ쑰 / Overall Project Structure

myapp24/  
β”œβ”€β”€ app/  (Next.js App Router)
β”‚   β”œβ”€β”€ .well-known/webfinger/route.ts  -> webfinger
β”‚   β”œβ”€β”€ api/follow/route.ts    -> Follow API(temporary)
β”‚   β”œβ”€β”€ api/announce/route.ts  -> Boost(Announcement)
β”‚   β”œβ”€β”€ api/like/route.ts.     -> Like API
β”‚   β”œβ”€β”€ api/posts/route.ts     -> Writing API
β”‚   β”œβ”€β”€ api/timeline/route.ts  -> Timeline API
β”‚   β”œβ”€β”€ users/[username]/
β”‚   β”‚   β”œβ”€β”€ statuses/[id]/route.ts -> Indivisual Post
β”‚   β”‚   β”œβ”€β”€ route.ts               -> Acotr Information
β”‚   β”‚   β”œβ”€β”€ followers/route.ts     -> Followers List
β”‚   β”‚   β”œβ”€β”€ following/route.ts     -> Following List
β”‚   β”‚   β”œβ”€β”€ inbox/route.ts         -> Inbox
β”‚   β”‚   └── outbox/route.ts        -> outbox
β”‚   β”œβ”€β”€ usersui/[username]/page.tsx  -> Timeline UI
β”‚   β”œβ”€β”€ layout.tsx, page.tsx, globals.css
β”‚   └── favicon.ico
β”œβ”€β”€ lib/
β”‚   β”œβ”€β”€ ap.ts                  -> Follow Accept
β”‚   └── db.ts                  -> DB connection
β”œβ”€β”€ data/
β”‚   └── keys/                  -> private.pem, public.pem
β”œβ”€β”€ data.sqlite                -> Database
β”œβ”€β”€ Caddyfile                  -> https 
└── package.json

πŸ“ ν”„λ‘œμ νŠΈ μ‹œμž‘(myapp25)
Project Start (myapp25)

npx create-next-app@latest

πŸ“ SQLiteμ„€μΉ˜ / Installing SQLite

cd ~/myapp25
npm install better-sqlite3
npm install -D @types/better-sqlite3

πŸ“ DDNS,httpsμ„€μ • / DDNS,https settings

πŸ“ λ„λ©”μΈν—ˆμš©, @userid μ‚¬μš©ν•˜κΈ°
Allowing domains, using @userid

— next.config.ts

import type { NextConfig } from "next";

const nextConfig: NextConfig = {
  /* allow domain*/
  allowedDevOrigins: ['aloy-horizon.duckdns.org', '*.duckdns.org'],

  /* host.domain.org/@userid */
  async rewrites() {
    return [
      {
        source: '/@:username',
        destination: '/usersui/:username',
      },
    ]
  }
};


export default nextConfig;

πŸ“ λΆ€μŠ€νŠΈ 보낼 λ•Œ / When sending a boost

βœ”οΈ myapp25/app/api/announce/route.ts

    if (result.ok) {
      db.prepare('INSERT INTO announces (id, username, object) VALUES (?, ?, ?)').run(result.announceDoc.id, username, apObjectId);
    
      // βœ… myapp25 - νŒ”λ‘œμ›Œμ—κ²Œ λΆ€μŠ€νŠΈ 배달 / Deliver Boosts to followers
      const followers = db.prepare('SELECT inbox, actor FROM followers WHERE username = ?').all(username) as any[];
      console.log(`πŸ“’ λΆ€μŠ€νŠΈ 배달 μ‹œμž‘: ${followers.length}λͺ…μ—κ²Œ`);

      for (const f of followers) {
        try {
          // νŒ”λ‘œμ›Œ inbox에 Announce κ·ΈλŒ€λ‘œ 전달
          // ap.ts에 sendAnnounce μž¬μ‚¬μš©
          await sendAnnounce(f.inbox, apObjectId, username);
        } catch (e) {
          console.error(`배달 μ‹€νŒ¨ -> ${f.actor}`, e);
        }
      }
      
    }

πŸ“ λΆ€μŠ€νŠΈ 받을 λ•Œ / When receiving a boost

βœ”οΈ myapp25/app/users/[username]/inbox/route.ts

— λΆ€μŠ€νŠΈ λ°›κΈ° / Receive boost

 // βœ… myapp25 - λΆ€μŠ€νŠΈ λ°›κΈ° / Receive Boost !
    if (body.type === 'Announce') {
      try {
        const announceId = body.id;
        const objectId = typeof body.object === 'string' ? body.object : body.object?.id;
        console.log(`πŸ” [${username}] Announce 도착: ${actorId} -> ${objectId}`);

        // 1. announces ν…Œμ΄λΈ”μ— 기둝
        // Record in announces table
        db.prepare('INSERT OR IGNORE INTO announces (id, username, object) VALUES (?,?,?)')
          .run(announceId, username, objectId);

        // 2. 원글 λ‚΄μš© κ°€μ Έμ™€μ„œ inbox_posts에 μ €μž₯ (νƒ€μž„λΌμΈμ— 뜨게)
        // Retrieve the original post content and save it to inbox_posts (so it appears on the timeline)
        try {
          const noteRes = await fetch(objectId, {
            headers: { Accept: 'application/activity+json' }
          });
          if (noteRes.ok) {
            const note = await noteRes.json();
            const longId = note.id || objectId;
            const shortId = `${longId.split('/').pop()}_boost_${Date.now()}`; // λΆ€μŠ€νŠΈλŠ” 별도 id
            const content = note.content || note.summary || '';

            db.prepare(`
              INSERT OR IGNORE INTO inbox_posts (id, actor, content, username, original_id, created_at) 
              VALUES (?, ?, ?, ?, ?, ?)
            `).run(shortId, actorId, content, username, longId, body.published || new Date().toISOString());
            console.log(`βœ… [${username}] λΆ€μŠ€νŠΈ inbox_posts μ €μž₯ / Boost inbox_posts save: ${shortId}`);
          }
        } catch (fetchErr) {
          console.log(`⚠ 원글 fetch μ‹€νŒ¨, content 없이 μ €μž₯`, fetchErr);
          // fetch μ‹€νŒ¨ν•΄λ„ λΆ€μŠ€νŠΈ 기둝은 남김 / Boost records are saved even if fetch fails.
          db.prepare(`
            INSERT OR IGNORE INTO inbox_posts (id, actor, content, username, original_id, created_at) 
            VALUES (?, ?, ?, ?, ?, ?)
          `).run(`boost_${Date.now()}`, actorId, `[Boost] ${objectId}`, username, objectId, new Date().toISOString());
        }

        console.log(`βœ… [${username}] announces μ €μž₯ μ™„λ£Œ / Announcements saved.: ${announceId}`);
      } catch (e) {
        console.error(`❌ Announce μ €μž₯ μ‹€νŒ¨ / Failed to save Announce.`, e);
      }
      return new Response('', { status: 202 });
    }

— λΆ€μŠ€νŠΈ μ·¨μ†Œλ°›κΈ° / Cancel Boost(Undo Announce)

    // βœ… myapp25 - Undo Announce (λΆ€μŠ€νŠΈ μ·¨μ†Œ λ°›κΈ°)
    if (body.type === 'Undo') {
      // μœ„μ—μ„œ 이미 Follow, Like Undo μ²˜λ¦¬ν–ˆμœΌλ‹ˆκΉŒ μ—¬κΈ°μ„œλŠ” Announce Undo만
      const obj = body.object;
      if (typeof obj === 'object' && obj.type === 'Announce') {
        const announceId = obj.id;
        const objectId = typeof obj.object === 'string' ? obj.object : obj.object?.id;
        console.log(`↩ [${username}] Undo Announce: ${actorId} -> ${objectId}`);
        
        db.prepare('DELETE FROM announces WHERE id = ?').run(announceId);
        // inbox_postsμ—μ„œ λΆ€μŠ€νŠΈ 글도 μ‚­μ œ (선택)
        db.prepare('DELETE FROM inbox_posts WHERE original_id = ? AND actor = ?').run(objectId, actorId);
        console.log(`πŸ—‘ [${username}] λΆ€μŠ€νŠΈ μ·¨μ†Œ 처리 μ™„λ£Œ / Boost processing cancellation complete.`);
        return new Response('', { status: 202 });
      }
    }

πŸ“ ν…ŒμŠ€νŠΈ / Test

# νŒ”λ‘œμš° (following 1둜 증가)
# Follow (following increased to 1)

curl -X POST https://aloy-horizon.duckdns.org/api/follow \
  -H "Content-Type: application/json" \
  -d '{"username":"user1","target":"https://mastodon.social/users/mcnees"}'

# μ–ΈνŒ”λ‘œμš° (following 0으둜 κ°μ†Œ)
# Unfollow (following count reduced to 0)

curl -X DELETE https://aloy-horizon.duckdns.org/api/follow \
  -H "Content-Type: application/json" \
  -d '{"username":"user1","target":"https://mastodon.social/users/mcnees"}'

# λΆ€μŠ€νŠΈ μ‹€ν–‰ / Boost
curl -X POST https://aloy-horizon.duckdns.org/api/announce \
 -H "Content-Type: application/json" \
 -d '{"username":"user1","target":"https://mastodon.social/@mcnees/117089019419350090"}'

# λΆ€μŠ€νŠΈ μ·¨μ†Œ / Cancle Boost
curl -X DELETE https://aloy-horizon.duckdns.org/api/announce \
 -H "Content-Type: application/json" \
 -d '{"username":"user1","target":"https://mastodon.social/@mcnees/117089019419350090"}'

βœ”οΈ λ§ˆμŠ€ν† λˆ μ„œλ²„μ˜ κΈ€ λΆ€μŠ€νŠΈν•˜κΈ° / Boost a post on a Mastodon server

https://mastodon.social/@mcnees/117089019419350090

— νŒ”λ‘œμš°,λΆ€μŠ€νŠΈμ‹€ν–‰ / Execute Follow and Boost

# λ§ˆμŠ€ν† λˆ μ„œλ²„μ— νŒ”λ‘œμš° μš”μ²­ / Follow request to a Mastodon server

myapp25 % curl -X POST https://aloy-horizon.duckdns.org/api/follow \
  -H "Content-Type: application/json" \
  -d '{"username":"user1","target":"https://mastodon.social/users/mcnees"}'

{"ok":true,"inbox":"https://mastodon.social/users/mcnees/inbox","target":"https://mastodon.social/users/mcnees","username":"user1","result":"","follow":{"@context":"https://www.w3.org/ns/activitystreams","id":"https://aloy-horizon.duckdns.org/users/user1/follows/1787878537250","type":"Follow","actor":"https://aloy-horizon.duckdns.org/users/user1","object":"https://mastodon.social/users/mcnees"}}%                                                               

# λΆ€μŠ€νŠΈ μ‹€ν–‰ / Run Boost

 myapp25 % curl -X POST https://aloy-horizon.duckdns.org/api/announce \
 -H "Content-Type: application/json" \
 -d '{"username":"user1","target":"https://mastodon.social/@mcnees/117089019419350090"}'

{"ok":true,"result":{"ok":true,"status":202,"text":"","announceDoc":{"@context":"https://www.w3.org/ns/activitystreams","id":"https://aloy-horizon.duckdns.org/users/user1/announces/15aad35a-32de-4de0-b832-9134498b94d5","type":"Announce","actor":"https://aloy-horizon.duckdns.org/users/user1","object":"https://mastodon.social/users/mcnees/statuses/117089019419350090","published":"2026-08-28T00:56:17.391Z","to":["https://www.w3.org/ns/activitystreams#Public"],"cc":["https://aloy-horizon.duckdns.org/users/user1/followers","https://aloy-horizon.duckdns.org/users/user1"]}}}%                                         
gimdaegyeong@gimdaegyeong-ui-MacBookAir myapp25 % 
Mastodon Boost

— λ‚΄ DB에 λΆ€μŠ€νŠΈ 전달확인 / Check Boost delivery status in my DB

sqlite> select * from announces;
https://freelifemakers.com/users/user1/statuses/01M12WRSDN77HCBMPES6NH8A4Z|user1|https://freelifemakers.com/users/user1/statuses/01M10AHFHCKGF9BY5G4H50VSHG|2026-08-28 00:36:59
https://aloy-horizon.duckdns.org/users/user1/announces/9d4b9bc4-fa12-4073-b034-794c0dde40f8|user1|https://freelifemakers.com/users/user1/statuses/01M12X859S7WNSJJD42NWZS8T7|2026-08-28 00:46:46
https://aloy-horizon.duckdns.org/users/user1/announces/15aad35a-32de-4de0-b832-9134498b94d5|user1|https://mastodon.social/users/mcnees/statuses/117089019419350090|2026-08-28 00:56:17
sqlite> 

βœ”οΈ freelifemakers.comμ—μ„œ λΆ€μŠ€νŠΈ ν•œ 경우
If you boosted via freelifemakers.com

Screenshot
sqlite> select * from announces;
https://freelifemakers.com/users/user1/statuses/01M12WRSDN77HCBMPES6NH8A4Z|user1|https://freelifemakers.com/users/user1/statuses/01M10AHFHCKGF9BY5G4H50VSHG|2026-08-28 00:36:59

βœ”οΈ aloy-horizon.duckdns.orgκ°€ freelifemakers.com을 λΆ€μŠ€νŠΈν•œ 경우
If aloy-horizon.duckdns.org has boosted freelifemakers.com

# λΆ€μŠ€νŠΈ μ‹€ν–‰ / Boost
curl -X POST https://aloy-horizon.duckdns.org/api/announce \
 -H "Content-Type: application/json" \
 -d 
'{"username":"user1","target":"https://freelifemakers.com/users/user1/statuses/01M12X859S7WNSJJD42NWZS8T7"}'

# λΆ€μŠ€νŠΈ μ·¨μ†Œ / Cancle Boost
curl -X DELETE https://aloy-horizon.duckdns.org/api/announce \
 -H "Content-Type: application/json" \
 -d 
'{"username":"user1","target":"https://freelifemakers.com/users/user1/statuses/01M12X859S7WNSJJD42NWZS8T7"}'
myapp25 % curl -X POST https://aloy-horizon.duckdns.org/api/announce \
 -H "Content-Type: application/json" \
 -d '{"username":"user1","target":"https://freelifemakers.com/users/user1/statuses/01M12X859S7WNSJJD42NWZS8T7"}'

{"ok":true,"result":{"ok":true,"status":202,"text":"{\"status\":\"Accepted\"}","announceDoc":{"@context":"https://www.w3.org/ns/activitystreams","id":"https://aloy-horizon.duckdns.org/users/user1/announces/9d4b9bc4-fa12-4073-b034-794c0dde40f8","type":"Announce","actor":"https://aloy-horizon.duckdns.org/users/user1","object":"https://freelifemakers.com/users/user1/statuses/01M12X859S7WNSJJD42NWZS8T7","published":"2026-08-28T00:46:46.182Z","to":["https://www.w3.org/ns/activitystreams#Public"],"cc":["https://aloy-horizon.duckdns.org/users/user1/followers","https://aloy-horizon.duckdns.org/users/user1"]}}}%      
sqlite> select * from announces;
https://freelifemakers.com/users/user1/statuses/01M12WRSDN77HCBMPES6NH8A4Z|user1|https://freelifemakers.com/users/user1/statuses/01M10AHFHCKGF9BY5G4H50VSHG|2026-08-28 00:36:59
https://aloy-horizon.duckdns.org/users/user1/announces/9d4b9bc4-fa12-4073-b034-794c0dde40f8|user1|https://freelifemakers.com/users/user1/statuses/01M12X859S7WNSJJD42NWZS8T7|2026-08-28 00:46:46
sqlite> 

μš”ν•œλ³΅μŒ 8μž₯ 32절 / John 8:32

“그리고 λ„ˆν¬λŠ” 진리λ₯Ό μ•Œκ²Œ 될 것이며, 진리가 λ„ˆν¬λ₯Ό 자유둭게 ν•  것이닀.”

“Then you will know the truth ,and the truth will set you free”

Leave a Reply