[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 % 

— 내 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

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