[nextjs]SNS Server-13(myapp23)

👉🏻좋아요와 좋아요 취소기능을 구현합니다.
Implement the “like” and “unlike” functions.

📁 전체 프로젝트 구조 / Overall Project Structure

myapp23/  
├── app/  (Next.js App Router)
│   ├── .well-known/webfinger/route.ts  -> webfinger
│   ├── api/posts/route.ts     -> Writing API
│   ├── api/follow/route.ts    -> Follow API(temporary)
│   ├── api/timeline/route.ts  -> Timeline API
│   ├── api/like/route.ts.     -> Like 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

📁 프로젝트 시작(myapp23)
Project Start (myapp23)

npx create-next-app@latest

📁 SQLite설치 / Installing SQLite

cd ~/myapp23
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;

📁 테이블 추가 / Add table

✔️ 테이블 및 인덱스 생성(sqlite)
Create Table and Index (sqlite)

CREATE TABLE IF NOT EXISTS likes (
  id TEXT PRIMARY KEY,          
  actor TEXT NOT NULL,           
  object TEXT NOT NULL,          
  username TEXT NOT NULL,       
  created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);

CREATE INDEX IF NOT EXISTS idx_likes_object ON likes(object);
CREATE INDEX IF NOT EXISTS idx_likes_actor ON likes(actor);

1)id TEXT PRIMARY KEY,
— Like Activity ID: https://aloy-horizon.duckdns.org/users/user1/likes/1234

2)actor TEXT NOT NULL,
— 좋아요 누른사람 / People who liked this

— https://freelifemakers.com/users/user1

3)object TEXT NOT NULL,
— 좋아요 누른 글 / Posts I’ve liked

— https://aloy-horizon.duckdns.org/users/user1/statuses/abc

4) username TEXT NOT NULL,
— 내 로컬 유저/My local user:: user1

✔️ myapp23/lib/db.ts 코드 수정

import Database from 'better-sqlite3';
import path from 'path';

const dbPath = path.join(process.cwd(), 'data.sqlite');
const db = new Database(dbPath);
db.pragma('journal_mode = WAL');

db.exec(`

... ...

  -- myapp23 ✅ likes/Undo likes
  CREATE TABLE IF NOT EXISTS likes (
    id TEXT PRIMARY KEY,           
    actor TEXT NOT NULL,    
    object TEXT NOT NULL,      
    username TEXT NOT NULL,       
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
  );
`);

db.exec(`
  CREATE INDEX IF NOT EXISTS idx_followers_username ON followers(username);
  CREATE INDEX IF NOT EXISTS idx_followers_actor ON followers(actor);
  CREATE INDEX IF NOT EXISTS idx_following_username ON following(username);
  CREATE INDEX IF NOT EXISTS idx_following_actor ON following(actor);
  CREATE INDEX IF NOT EXISTS idx_posts_username_created ON posts(username, created_at DESC);
  CREATE INDEX IF NOT EXISTS idx_inbox_username_created ON inbox_posts(username, created_at DESC);
  CREATE INDEX IF NOT EXISTS idx_inbox_actor ON inbox_posts(actor);
  CREATE UNIQUE INDEX IF NOT EXISTS idx_following_actor_username ON following(actor, username);
  CREATE UNIQUE INDEX IF NOT EXISTS idx_followers_actor_username ON followers(actor, username);
  -- myapp23 ✅
  CREATE INDEX IF NOT EXISTS idx_likes_object ON likes(object);
  CREATE INDEX IF NOT EXISTS idx_likes_actor ON likes(actor);
`);

export default db;

📁 코드 수정 및 라우트 추가
Code modifications and route additions

✔️ 라우트 추가 / Add Route

app/api/like/route.ts 

// app/api/like/route.ts
// myapp23 ✅ - Like / Undo Like

import { NextRequest, NextResponse } from 'next/server';
import db from '@/lib/db';
import { getActorData, sendLike, sendUndoLike, signedFetch } from '@/lib/ap';

export async function POST(req: NextRequest) {
  try {
    const { username, target } = await req.json();
    if (!username || !target) {
      return NextResponse.json({ ok: false, error: 'username and target required' }, { status: 400 });
    }

    let inbox: string;
    let apObjectId: string = target;

    try {
      const postRes = await signedFetch(target, username);
      if (postRes.ok) {
        const postData = await postRes.json();
        apObjectId = postData.id || target;
        const attributedTo = postData.attributedTo || postData.actor;
        const actorUrl = typeof attributedTo === 'string' ? attributedTo : attributedTo?.id;
        if (!actorUrl) throw new Error('no actor in post');
        const actorInfo = await getActorData(actorUrl, username);
        inbox = actorInfo.inbox;
      } else {
        const url = new URL(target);
        const parts = url.pathname.split('/');
        const usersIdx = parts.indexOf('users');
        if (usersIdx === -1) throw new Error('invalid target');
        const actorUrl = `${url.origin}${parts.slice(0, usersIdx + 2).join('/')}`;
        const actorInfo = await getActorData(actorUrl, username);
        inbox = actorInfo.inbox;
      }
    } catch (e) {
      console.error(e);
      return NextResponse.json({ ok: false, error: 'invalid target post id' }, { status: 400 });
    }

    // 중복 체크는 apObjectId로 해야 함 (Mastodon 대응)
    const existing = db.prepare('SELECT id FROM likes WHERE object = ? AND username = ?').get(apObjectId, username) as any;
    if (existing) {
      return NextResponse.json({ ok: true, alreadyLiked: true, id: existing.id });
    }

    const result = await sendLike(inbox, apObjectId, username);

    db.prepare('INSERT OR IGNORE INTO likes (id, actor, object, username) VALUES (?,?,?,?)')
      .run(result.likeDoc.id, result.likeDoc.actor, result.likeDoc.object, username);

    return NextResponse.json({ ok: true, result });

  } catch (e: any) {
    console.error('[Like POST]', e);
    return NextResponse.json({ ok: false, error: e.message }, { status: 500 });
  }
}

export async function DELETE(req: NextRequest) {
  try {
    const { username, target } = await req.json();
    if (!username || !target) {
      return NextResponse.json({ ok: false, error: 'username and target required' }, { status: 400 });
    }

    let apObjectId: string = target;
    let inbox: string;

    try {
      const postRes = await signedFetch(target, username);
      if (postRes.ok) {
        const postData = await postRes.json();
        apObjectId = postData.id || target;
        const attributedTo = postData.attributedTo || postData.actor;
        const actorUrl = typeof attributedTo === 'string' ? attributedTo : attributedTo?.id;
        if (!actorUrl) throw new Error('no actor');
        const actorInfo = await getActorData(actorUrl, username);
        inbox = actorInfo.inbox;
      } else {
        const url = new URL(target);
        const parts = url.pathname.split('/');
        const usersIdx = parts.indexOf('users');
        if (usersIdx === -1) throw new Error('invalid target');
        const actorUrl = `${url.origin}${parts.slice(0, usersIdx + 2).join('/')}`;
        const actorInfo = await getActorData(actorUrl, username);
        inbox = actorInfo.inbox;
      }
    } catch (e) {
      return NextResponse.json({ ok: false, error: 'invalid target post id' }, { status: 400 });
    }

    const likeRow = db.prepare('SELECT id FROM likes WHERE object = ? AND username = ?').get(apObjectId, username) as any;
    if (!likeRow) {
      return NextResponse.json({ ok: true, alreadyUnliked: true });
    }

    const result = await sendUndoLike(inbox, likeRow.id, apObjectId, username);

    db.prepare('DELETE FROM likes WHERE id = ?').run(likeRow.id);

    return NextResponse.json({ ok: true, result });

  } catch (e: any) {
    console.error('[Like DELETE]', e);
    return NextResponse.json({ ok: false, error: e.message }, { status: 500 });
  }
}

✔️ 코드수정 / Code modification

— lib/ap.ts에 sendLike, sendUndoLike 추가


... ...

// ✅ myapp23 - Like 보내기 / Send Like
export async function sendLike(toInbox: string, targetPostId: string, username: string) {
  const actorId = `https://${DOMAIN}/users/${username}`;
  const likeId = `${actorId}/likes/${Date.now()}`;

  const likeDoc = {
    '@context': 'https://www.w3.org/ns/activitystreams',
    id: likeId,
    type: 'Like',
    actor: actorId,
    object: targetPostId
  };

  const body = JSON.stringify(likeDoc);
  const url = new URL(toInbox);
  const digest = `SHA-256=${crypto.createHash('sha256').update(body).digest('base64')}`;
  const date = new Date().toUTCString();
  const signingString = `(request-target): post ${url.pathname}\nhost: ${url.host}\ndate: ${date}\ndigest: ${digest}`;
  const signer = crypto.createSign('sha256');
  signer.update(signingString);
  const signature = signer.sign(PRIVATE_KEY, 'base64');
  const keyId = `${actorId}#main-key`;
  const sigHeader = `keyId="${keyId}",headers="(request-target) host date digest",signature="${signature}"`;

  console.log(`❤️ [${username}] Like 전송 -> ${toInbox} (${targetPostId})`);

  const res = await fetch(toInbox, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/activity+json',
      'Date': date,
      'Digest': digest,
      'Signature': sigHeader,
      'Host': url.host
    },
    body
  });

  const text = await res.text();
  console.log(`📬 Like 결과: ${res.status}`, text);
  return { ok: res.ok, status: res.status, text, likeDoc };
}

// ✅ myapp23 - Undo Like 보내기 / Send Undo Like
export async function sendUndoLike(toInbox: string, likeId: string, targetPostId: string, username: string) {
  const actorId = `https://${DOMAIN}/users/${username}`;
  const undoId = `${actorId}#undo/${Date.now()}`;

  const undoDoc = {
    '@context': 'https://www.w3.org/ns/activitystreams',
    id: undoId,
    type: 'Undo',
    actor: actorId,
    object: {
      id: likeId,
      type: 'Like',
      actor: actorId,
      object: targetPostId
    }
  };

  const body = JSON.stringify(undoDoc);
  const url = new URL(toInbox);
  const digest = `SHA-256=${crypto.createHash('sha256').update(body).digest('base64')}`;
  const date = new Date().toUTCString();
  const signingString = `(request-target): post ${url.pathname}\nhost: ${url.host}\ndate: ${date}\ndigest: ${digest}`;
  const signer = crypto.createSign('sha256');
  signer.update(signingString);
  const signature = signer.sign(PRIVATE_KEY, 'base64');
  const keyId = `${actorId}#main-key`;
  const sigHeader = `keyId="${keyId}",headers="(request-target) host date digest",signature="${signature}"`;

  console.log(`💔 [${username}] Undo Like 전송 -> ${toInbox}`);

  const res = await fetch(toInbox, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/activity+json',
      'Date': date,
      'Digest': digest,
      'Signature': sigHeader,
      'Host': url.host
    },
    body
  });

  const text = await res.text();
  console.log(`📬 Undo Like 결과: ${res.status}`, text);
  return { ok: res.ok, status: res.status, text, undoDoc };
}

// ✅ myapp23 - Actor 데이터 가져오기 (inbox/route, like/route 공용)
export async function getActorData(actorUrl: string, username: string) {
  const res = await signedFetch(actorUrl, username);
  if (!res.ok) throw new Error(`getActorData failed: ${res.status} ${await res.text()}`);
  const data = await res.json();
  return {
    id: data.id,
    inbox: data.inbox
  };
}

— myapp23/app/users/[username]/inbox/route.ts에 Like 처리 추가

export async function POST(req: Request, { params }: { params: Promise<{ username: string }> }) {
... ...
  if (body.type === 'Undo') {
       // Follow Undo인 경우 / If it's a Follow Undo
      if (body.object?.type === 'Follow' || typeof body.object === 'string' || body.object?.id?.includes('#follow')) {
         const unfollowActorId = body.actor; // 누가 언팔했는지 / who unfollowed
         //db.prepare('DELETE FROM followers WHERE actor = ?').run(unfollowActorId);

      // ✅ myapp15 - 언팔로우 시 username도 조건에 추가 / Add username condition when unfollowing
         db.prepare('DELETE FROM followers WHERE actor = ? AND username = ?').run(unfollowActorId, username);
         console.log(`🗑️ [${username}] 언팔로우 / unfollow : ${unfollowActorId}`);
      }
      // ✅ myapp23 - Like Undo
      else if (objType === 'Like' || obj?.id?.includes('/likes/')) {
        const likeId = typeof obj === 'string'? obj : obj.id;
        db.prepare('DELETE FROM likes WHERE id =?').run(likeId);
        console.log(`💔 [${username}] Unlike 저장 / unlike : ${likeId} by ${actorId}`);
      }

  }
}

... ...

    // ✅ myapp23 - 좋아요 받기 / Get Likes !
    if (body.type === 'Like') {
      try {
        const likeId = body.id;
        const objectId = typeof body.object === 'string'? body.object : body.object?.id;
        console.log(`❤️ [${username}] Like 도착: ${actorId} -> ${objectId}`);

        db.prepare('INSERT OR IGNORE INTO likes (id, actor, object, username) VALUES (?,?,?,?)')
         .run(likeId, actorId, objectId, username);

        console.log(`✅ [${username}] likes 저장 완료: ${likeId}`);
      } catch (e) {
        console.error(`❌ Like 저장 실패/
Failed to save 'Like'`, e);
      }
      return new Response('', { status: 202 });
    }

📁 테스트 / Test

✔️ pinafore에서 좋아요 누르기 / Like on Pinafore

pinafore

— 내 서버 로그 / My server log

 GET /users/user1/posts/c0ee1d4b-b09a-4062-b0e9-9b3b40f50bb3 404 in 328ms (next.js: 266ms, application-code: 62ms)
📩 [user1] INBOX: Like https://freelifemakers.com/users/user1
⚠️ [user1] publicKey 없음, 검증 스킵 / no publicKey, skip verify
❤️ [user1] Like 도착: https://freelifemakers.com/users/user1 -> https://aloy-horizon.duckdns.org/users/user1/posts/c0ee1d4b-b09a-4062-b0e9-9b3b40f50bb3
✅ [user1] likes 저장 완료: https://freelifemakers.com/users/user1/liked/01M0XS4TFGAA6G2YPYE72P0YRA
 POST /users/user1/inbox 202 in 668ms (next.js: 547ms, application-code: 121ms)

— 데이터베이스 / Database(SQLITE)

1)likes테이블 / likes table

myapp23 % sqlite3 data.sqlite
SQLite version 3.51.0 2025-06-12 13:14:41
Enter ".help" for usage hints.
sqlite> select * from likes;
https://freelifemakers.com/users/user1/liked/01M0XS4TFGAA6G2YPYE72P0YRA|https://freelifemakers.com/users/user1|https://aloy-horizon.duckdns.org/users/user1/posts/c0ee1d4b-b09a-4062-b0e9-9b3b40f50bb3|user1|2026-04-10 00:10:26
sqlite> 

✔️ freelifemakers.com의 글에 좋아요 누르기 / Like posts on freelifemakers.com

— POST 메소드로 특정 포스트에 좋아요 누르기
Like a specific post using the POST method.

curl -X POST https://aloy-horizon.duckdns.org/api/like \
 -H "Content-Type: application/json" \
 -d '{"username":"user1","target":"https://freelifemakers.com/users/user1/statuses/[POST_ID]"}'
myapp23 % curl -X POST https://aloy-horizon.duckdns.org/api/like \
 -H "Content-Type: application/json" \
 -d '{"username":"user1","target":"https://freelifemakers.com/users/user1/statuses/01M0XT1VBF23F8Y5EXAPK1VY56"}'
{"ok":true,"result":{"ok":true,"status":202,"text":"{\"status\":\"Accepted\"}","likeDoc":{"@context":"https://www.w3.org/ns/activitystreams","id":"https://aloy-horizon.duckdns.org/users/user1/likes/1787708354555","type":"Like","actor":"https://aloy-horizon.duckdns.org/users/user1","object":"https://freelifemakers.com/users/user1/statuses/01M0XT1VBF23F8Y5EXAPK1VY56"}}}%                                                                                                                                     
gimdaegyeong@gimdaegyeong-ui-MacBookAir myapp23 % 

1) 기존 글 검색 / Search existing posts

myapp23 % sqlite3 data.sqlite
SQLite version 3.51.0 2025-06-12 13:14:41
Enter ".help" for usage hints.
sqlite> select * from inbox_posts;
https://freelifemakers.com/users/user1/statuses/01M0EJPP57WC47FAK0N395S7MB|https://freelifemakers.com/users/user1|<p>inbox_posts table test</p>|user1|2026-08-20 03:16:15|
https://freelifemakers.com/users/user1/statuses/01M0KMS8K1XRFW703S32MX6V25|https://freelifemakers.com/users/user1|<p>actor test</p>|user1|2026-08-22T11:28:48+09:00|https://freelifemakers.com/users/user1/statuses/01M0KMS8K1XRFW703S32MX6V25
01M0XT1VBF23F8Y5EXAPK1VY56|https://freelifemakers.com/users/user1|<p>likes test</p>|user1|2026-08-26T10:13:17+09:00|https://freelifemakers.com/users/user1/statuses/01M0XT1VBF23F8Y5EXAPK1VY56
sqlite> 

2) 좋아요 실행하기 / like posts on

A. 터미널에서 실행하기 / Running in the terminal

curl -X POST https://aloy-horizon.duckdns.org/api/like \
 -H "Content-Type: application/json" \
 -d '{"username":"user1","target":"https://freelifemakers.com/users/user1/statuses/01M0XT1VBF23F8Y5EXAPK1VY56"}'

B. 응답메세지(성공인경우) / Response message (in case of success)

{"ok":true,"result":{"ok":true,"status":202,"text":"{\"status\":\"Accepted\"}","likeDoc":{"@context":"https://www.w3.org/ns/activitystreams","id":"https://aloy-horizon.duckdns.org/users/user1/likes/1787708354555","type":"Like","actor":"https://aloy-horizon.duckdns.org/users/user1","object":"https://freelifemakers.com/users/user1/statuses/01M0XT1VBF23F8Y5EXAPK1VY56"}}}% 
Screenshot

C.다른 마스토돈(https://mastodon.social/users/Gargron/statuses/114559081070832514)의 게시물에 좋아요 누르기(성공)
Liking a post from another Mastodon instance
(https://mastodon.social/users/Gargron/statuses/114559081070832514) (Success)

– 다른 마스토돈 게시물에 좋아요 실행하기 / Like other Mastodon posts

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

– 응답성공 / Response successful

{"ok":true,"result":{"ok":true,"status":202,"text":"","likeDoc":{"@context":"https://www.w3.org/ns/activitystreams","id":"https://aloy-horizon.duckdns.org/users/user1/likes/af39dead-cb1a-45ba-bf9d-f3074921c2a0","type":"Like","actor":"https://aloy-horizon.duckdns.org/users/user1","object":"https://mastodon.social/users/Gargron/statuses/114559081070832514"}}}%

3) 좋아요 취소 실행 / Perform Undo

A.gotosocial – freelifemakers.com

– 좋아요 취소 전송 / Undo Send

curl -X DELETE https://aloy-horizon.duckdns.org/api/like \
 -H "Content-Type: application/json" \
 -d '{"username":"user1","target":"https://freelifemakers.com/users/user1/statuses/01M0XT1VBF23F8Y5EXAPK1VY56"}'

– 응답성공 / Response successful

  {"ok":true,"result":{"ok":true,"status":202,"text":"{\"status\":\"Accepted\"}","undoDoc":{"@context":"https://www.w3.org/ns/activitystreams","id":"https://aloy-horizon.duckdns.org/users/user1#undo/75038dda-f43b-4167-b49a-376ce2a0a29f","type":"Undo","actor":"https://aloy-horizon.duckdns.org/users/user1","object":{"id":"https://aloy-horizon.duckdns.org/users/user1/likes/09d8e157-6f0e-4320-af76-2bf337faf2f6","type":"Like","actor":"https://aloy-horizon.duckdns.org/users/user1","object":"https://freelifemakers.com/users/user1/statuses/01M0XT1VBF23F8Y5EXAPK1VY56"}}}}

B.mastodon – https://mastodon.social/users/Gargron/statuses/114559081070832514

– 좋아요 취소 전송 / Undo Send

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

– 응답성공 / Response successful

 {"ok":true,"result":{"ok":true,"status":202,"text":"","undoDoc":{"@context":"https://www.w3.org/ns/activitystreams","id":"https://aloy-horizon.duckdns.org/users/user1#undo/9aabf284-68a7-42a2-9761-1b7ee0b7bcb2","type":"Undo","actor":"https://aloy-horizon.duckdns.org/users/user1","object":{"id":"https://aloy-horizon.duckdns.org/users/user1/likes/af39dead-cb1a-45ba-bf9d-f3074921c2a0","type":"Like","actor":"https://aloy-horizon.duckdns.org/users/user1","object":"https://mastodon.social/users/Gargron/statuses/114559081070832514"}}}}%

요한복음 8장 32절 / John 8:32

“그리고 너희는 진리를 알게 될 것이며, 진리가 너희를 자유롭게 할 것이다.”

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

Leave a Reply