[nextjs]SNS Server-47(myapp57) 

👉🏻 myapp57 은 기존 sns포스트에 댓글 기능을 추가합니다.
myapp57 adds a commenting feature to existing social media posts.

👉🏻 트리 형태로 글 하단에 묶이는 구조가 아니라 새글 처럼 뜨고 원본글에 추가되는 글을 표시하기 위해서 @userid post형식을 표시되는 기능입니다.
Instead of being grouped in a tree structure at the bottom of the post, this feature displays the content in the @userid post format, making it appear like a new post while indicating that it is an addition to the original post.

👉🏻 전체 코드는 깃허브에서 확인 할 수 있습니다.
You can find the full code on GitHub.

https://github.com/gideonslife01/flm-nextjs

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

myapp project/  
├── 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(deprecated)
│   ├── api/timeline/route.ts  -> Timeline API
│   ├── api/followinglist/route.ts  -> followinglist API
│   ├── api/followerslist/route.ts  -> followerslist API
│   ├── api/v1/instance/route.ts -> auth
│   ├── api/v1/apps/route.ts.    -> auth
│   ├── api/v1/accounts/verify_credentials/route.ts -> auth
│   ├── api/v1/statuses/route.ts -> Write Post
│   ├── api/v1/timelines/home/route.ts -> timeline
│   ├── api/v1/media/route.ts -> Image upload
│   ├── api/v1/media/[id]/route.ts  -> Image Delete 
│   ├── api/v1/instance/rules/route.ts -> Feature not implemented.
│   ├── api/v1/instance/domain_blocks/route.ts -> Feature not implemented.
│   ├── api/v1/filters/route.ts -> Feature not implemented.
│   ├── api/v1/lists/route.ts -> Feature not implemented.
│   ├── api/v1/announcements/route.ts -> Feature not implemented.
│   ├── api/v1/timelines/public/route.ts -> Feature not implemented.
│   ├── api/v1/statuses/[id]/context/route.ts -> Post Check,Delete
│   ├── oauth/authorize/route.ts -> auth
│   ├── oauth/token/route.ts -> auth
│   ├── oauth/login-and-authorize/route.ts -> Tursky,Pinafore login processing
│   ├── oauth/revoke/route.ts -> Feature not implemented.
│   ├── api/v1/search/home/route.ts -> search
│   ├── api/v2/search/home/route.ts -> search
│   ├── api/v2/notifications/policy/route.ts-> Feature not implemented.
│   ├── api/v1/accounts/[id]/followers/route.ts -> followers
│   ├── api/v1/accounts/[id]/following/route.ts -> following
│   ├── api/v1/statuses/[id]/route.ts -> -> Post delete(pinafore)
│   ├── api/auth/signup/route.ts        -> Website Signup
│   ├── api/auth/login/route.ts         -> Website Login
│   ├── api/auth/logout/route.ts        -> Website Logout
│   ├── api/auth/refresh/route.ts       -> Refresh Token
│   ├── api/cleanup-orphan/route.ts     -> post,outbox clean up
│   ├── api/auth/me/route.tsx           -> Login Check
│   ├── auth/signup/page.tsx            -> Signup UI
│   ├── auth/signup/page.tsx            -> Login UI        
│   ├── 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(Server, 404)
│   │   ├── ClientPage.tsx.        -> Timeline UI(Client,Call Active Themes)
│   │   └── _components/themes/
│   │       ├── themeex/ThemeexTheme.tsx   -> Example Theme
│   │       ├── pinafore/PinaforeTheme.tsx -> Theme 1
│   │       ├── pinafore/FollowersList.tsx -> Theme 1, FollowersList
│   │       ├── pinafore/FollowingList.tsx -> Theme 1, FollowingList
│   │       ├── pinafore/NotificationsList.tsx -> Theme 1, NotificationsList
│   │       ├── pinafore/TimelineList.tsx  -> Theme 1, TimelineList
│   │       ├── mastodon/MastodonTheme.tsx -> Theme 2
│   │       └── minimal/MinimaltTheme.tsx  -> Theme 3
│   ├── layout.tsx, page.tsx, globals.css
│   └── favicon.ico
├── lib/
│   ├── theme.tsx              -> Theme Provider
│   ├── watchThemes.ts         -> Check real-time theme changes
│   ├── auth.ts                -> Authentication, User Management
│   ├── ap.ts                  -> Follow,Undo,Create,Likes,Announce
│   ├── visibility.ts          -> Visibility(Public,Unlisted,Private,Direct)
│   └── db.ts                  -> DB connection
├── data/
│   ├── keys/userIDs/          -> private.pem, public.pem(New)
│   └── keys/                  -> private.pem, public.pem(legacy)
├── data.sqlite                -> Database(1/3)
├── data.sqlite-wal            -> Database(2/3)
├── data.sqlite-shm            -> Database(3/3)
├── Caddyfile                  -> https 
├── instrumentation.ts         -> Background Server
└── package.json

📁 프로젝트 시작 / Project Start


📁 테이블 수정 / Modify Table

✔️ user 테이블 – 버그수정용
user table – for bug fixes

# 컬럼추가
ALTER TABLE users ADD COLUMN mastodon_id TEXT;
UPDATE users SET mastodon_id = lower(hex(randomblob(4))) WHERE mastodon_id IS NULL;

# 스키마
sqlite> .schema users
CREATE TABLE users (
  username TEXT PRIMARY KEY,
  display_name TEXT DEFAULT '',
  summary TEXT DEFAULT '',
  private_key TEXT,
  public_key TEXT,
  email TEXT UNIQUE,
  password_hash TEXT,
  email_verified INTEGER DEFAULT 0,
  verification_token TEXT,
  created_at DATETIME DEFAULT CURRENT_TIMESTAMP
, mastodon_id TEXT);
sqlite> 

✔️ posts, inbox_posts 테이블에 reply 기능 추가 / Added reply functionality to the posts and inbox_posts tables.

— in_reply_to_id , in_reply_to_username

# 테이블 수정 - 터미널에서 실행 / Modify table – Run in the terminal

ALTER TABLE posts ADD COLUMN in_reply_to_id TEXT;
ALTER TABLE posts ADD COLUMN in_reply_to_username TEXT;

ALTER TABLE inbox_posts ADD COLUMN in_reply_to_id TEXT;
ALTER TABLE inbox_posts ADD COLUMN in_reply_to_username TEXT;

ALTER TABLE posts ADD COLUMN in_reply_to_account_id TEXT;
ALTER TABLE inbox_posts ADD COLUMN in_reply_to_account_id TEXT;

CREATE INDEX idx_posts_reply ON posts(in_reply_to_id);
CREATE INDEX idx_inbox_reply ON inbox_posts(in_reply_to_id);

CREATE INDEX idx_posts_reply_account ON posts(in_reply_to_account_id);
CREATE INDEX idx_inbox_reply_account ON inbox_posts(in_reply_to_account_id);

.schema posts

#----------------

# 실행결과 / Execution Result

sqlite> .schema posts
CREATE TABLE posts (
    id TEXT PRIMARY KEY,
    content TEXT NOT NULL,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
  , username TEXT DEFAULT 'user1', visibility TEXT DEFAULT 'public' CHECK(visibility IN ('public','unlisted','private','direct')), original_id TEXT, sensitive INTEGER DEFAULT 0, in_reply_to_id TEXT, in_reply_to_username TEXT);
CREATE INDEX idx_posts_username_created ON posts(username, created_at DESC);
CREATE INDEX idx_posts_visibility ON posts(visibility);
CREATE INDEX idx_posts_reply ON posts(in_reply_to_id);

sqlite> .schema inbox_posts
CREATE TABLE inbox_posts (
  id TEXT PRIMARY KEY,
  actor TEXT,
  content TEXT,
  username TEXT,
  created_at DATETIME DEFAULT CURRENT_TIMESTAMP
, original_id TEXT, visibility TEXT DEFAULT 'public' CHECK(visibility IN ('public','unlisted','private','direct')), type TEXT DEFAULT 'Note', sensitive INTEGER DEFAULT 0, in_reply_to_id TEXT, in_reply_to_username TEXT);
CREATE INDEX idx_inbox_username_created ON inbox_posts(username, created_at DESC);
CREATE INDEX idx_inbox_actor ON inbox_posts(actor);
CREATE INDEX idx_inbox_visibility ON inbox_posts(visibility);
CREATE INDEX idx_inbox_reply ON inbox_posts(in_reply_to_id);

📁 버그수정 / Bug fix

✔️ api/v1/statuses/route.ts

— API에서 account : { id: '1' ? '2' … } 하드코딩 부분 제거 -> mastodon_id로 수정
Removed the hardcoded account: { id: '1' ? '2' ... } section in the API and updated it to use mastodon_id.

— 모든 글의 id가 1번과 2번 밖에 없는 문제 발생
An issue arose where the IDs for all posts were limited to 1 and 2.

      account: {
        //id: username === 'user1' ? '1' : '2',
        id: mastodonId, // ✅ myapp57
        username: username,
        acct: `${username}@${DOMAIN}`,
        display_name: username,
        avatar: `https://${DOMAIN}/icon.png`
      },

✔️ lib/auth.ts

— mastodon_id 컬럼 추가 / Add the mastodon_id column.

— randomUUID().slice(0,8) 로 고유 id 생성
Generate a unique ID using randomUUID().slice(0,8)

export function createUser(username: string, email: string, passwordHash: string, displayName: string = '') {
  const { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', {
    modulusLength: 2048,
    publicKeyEncoding: { type: 'spki', format: 'pem' },
    privateKeyEncoding: { type: 'pkcs8', format: 'pem' }
  });

  const userKeyDir = path.join(process.cwd(), `data/keys/${username}`);
  if (!fs.existsSync(userKeyDir)) fs.mkdirSync(userKeyDir, { recursive: true });

  fs.writeFileSync(path.join(userKeyDir, 'private.pem'), privateKey);
  fs.writeFileSync(path.join(userKeyDir, 'public.pem'), publicKey);
  console.log(`✅ 키 파일 저장/save key file: data/keys/${username}/`);

  // return db.prepare(`
  //   INSERT INTO users (username, display_name, summary, private_key, public_key, email, password_hash, email_verified, created_at)
  //   VALUES (?,?, '',?,?,?,?, 1, CURRENT_TIMESTAMP)
  // `).run(username, displayName || username, privateKey, publicKey, email, passwordHash);

  // ✅ myapp58 - mastodon_id 생성 / create mastodon_id
  const mastodonId = crypto.randomUUID().slice(0, 8); 

  return db.prepare(`
    INSERT INTO users (username, display_name, summary, private_key, public_key, email, password_hash, email_verified, mastodon_id, created_at)
    VALUES (?,?, '',?,?,?,?, 1, ?, CURRENT_TIMESTAMP)
  `).run(username, displayName || username, privateKey, publicKey, email, passwordHash, mastodonId);

}

✔️ app/api/v1/timelines/home/route.ts

export function createUser(username: string, email: string, passwordHash: string, displayName: string = '') {
  const { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', {
    modulusLength: 2048,
    publicKeyEncoding: { type: 'spki', format: 'pem' },
    privateKeyEncoding: { type: 'pkcs8', format: 'pem' }
  });

  const userKeyDir = path.join(process.cwd(), `data/keys/${username}`);
  if (!fs.existsSync(userKeyDir)) fs.mkdirSync(userKeyDir, { recursive: true });

  fs.writeFileSync(path.join(userKeyDir, 'private.pem'), privateKey);
  fs.writeFileSync(path.join(userKeyDir, 'public.pem'), publicKey);
  console.log(`✅ 키 파일 저장/save key file: data/keys/${username}/`);

  // return db.prepare(`
  //   INSERT INTO users (username, display_name, summary, private_key, public_key, email, password_hash, email_verified, created_at)
  //   VALUES (?,?, '',?,?,?,?, 1, CURRENT_TIMESTAMP)
  // `).run(username, displayName || username, privateKey, publicKey, email, passwordHash);

  // ✅ myapp58 - mastodon_id 생성 / create mastodon_id
  const mastodonId = crypto.randomUUID().slice(0, 8); 

  return db.prepare(`
    INSERT INTO users (username, display_name, summary, private_key, public_key, email, password_hash, email_verified, mastodon_id, created_at)
    VALUES (?,?, '',?,?,?,?, 1, ?, CURRENT_TIMESTAMP)
  `).run(username, displayName || username, privateKey, publicKey, email, passwordHash, mastodonId);

}

✔️ app/api/v1/accounts/verify_credentials/route.ts

💡 verify_credentials/route.ts 라우트와 v1/statuses/[id]/route.ts의 id가 같아야 pinafore에서 delete 메뉴를 볼 수 있음.
The id in verify_credentials/route.ts and v1/statuses/[id]/route.ts must match for the delete menu to appear in Pinafore.

... ... 
// ✅ myapp57 - getUser함수로 계정 확인 / Verify the account using the `getUser` function.
function getUser(req: Request) {
  const auth = req.headers.get('Authorization')?.replace('Bearer ','').trim();
  if (auth) {
    // 1. oauth_tokens에서 access_token 검색
    // Retrieve access_token from oauth_tokens
    const o = db.prepare('SELECT username FROM oauth_tokens WHERE access_token=?').get(auth) as any;
    if (o?.username) return o.username;
    // 2. sessions에서 refresh_token도 검색
    // Also search for refresh_token in sessions
    const s = db.prepare('SELECT username FROM sessions WHERE refresh_token=?').get(auth) as any;
    if (s?.username) return s.username;
  }
  const cookie = req.headers.get('cookie') || '';
  const m = cookie.match(/refresh_token=([^;]+)/);
  if (m) {
    const s = db.prepare('SELECT username FROM sessions WHERE refresh_token=?').get(m[1]) as any;
    if (s?.username) return s.username;
  }
  return null;
}

export async function GET(req: Request) {
  // ✅ Mastodon 형식으로 리턴 / Return in Mastodon format
  return NextResponse.json({
    id:  mastodonId, // ✅ myapp57
    username: username,
    acct: `${username}@${DOMAIN}`,
    display_name: username,
    locked: false,
    bot: false,
    created_at: new Date().toISOString(),
    note: 'My ActivityPub server!',
    url: `https://${DOMAIN}/users/${username}`,
    avatar: `https://${DOMAIN}/icon.png`,
    avatar_static: `https://${DOMAIN}/icon.png`,
    header: `https://${DOMAIN}/icon.png`,
    header_static: `https://${DOMAIN}/icon.png`,
    followers_count: 1,
    following_count: 1,
    statuses_count: 100,
    source: {
      privacy: 'public',
      sensitive: false,
      language: 'en',
      note: '',
      fields: []
    }
  });
}

✔️ users테이블의 mastodon_id인 부분의 데이터 업데이트 실행
Execute a data update for the mastodon_id field in the users table.

sqlite3 data.sqlite "UPDATE users SET mastodon_id = lower(hex(randomblob(4))) WHERE mastodon_id IS NULL;"

✔️ app/api/v1/timelines/home/route.ts

// ✅ myapp48 - visibility 공통 헬퍼 import 추가 / Added import for common visibility helper
import { getViewerFromRequest, canSee } from '@/lib/visibility';
... ...
export async function GET(req: Request) {
... ...

  // ✅ myapp57 - 내 mastodon_id 조회 / select my mastodoin_id
  const me = db.prepare('SELECT mastodon_id FROM users WHERE username=?').get(viewer) as any;
  const myMastodonId = me?.mastodon_id || viewer;
... ...
  // ✅ myapp55 + myapp57
  if (filteredRows.length === 0) {
    // const fallback = db.prepare(`SELECT * FROM posts ORDER BY created_at DESC LIMIT 20`).all() as any[];
    // console.log(`HOME fallback=${fallback.length}`);

    const fallback = db.prepare(`
      SELECT * FROM posts 
      WHERE visibility IN ('public','unlisted')
      ORDER BY created_at DESC LIMIT 20
    `).all() as any[];
    filteredRows = fallback;
  }
... ...
    // ✅ myapp57 - 계정 정보 mastodon_id로 설정 / Set account information to mastodon_id
    const isMy = myPosts.some(p => p.id === row.id);
    let accountId = myMastodonId; 
    let accountUsername = viewer; 
... ...
    const baseAccount = isMy
    ? { 
        id: accountId, //✅ myapp57
        username, acct: `${username}@${DOMAIN}`, display_name: username,
        avatar: `https://${DOMAIN}/icon.png`,
        avatar_static: `https://${DOMAIN}/icon.png`,
        header: `https://${DOMAIN}/header.png`,
        header_static: `https://${DOMAIN}/header.png`,
      }
    : (() => { ... }

    return {
      id: String(row.id),
      uri: longId,
      url: longId,
      account: baseAccount,
      content: content.startsWith('<')? content : `<p>${content}</p>`,
      created_at: new Date(parseDate(row.created_at)).toISOString(),
      visibility: row.visibility || 'public', // ✅ myapp57
      reblogs_count,      // 전체 부스트 카운트 / Full boost count
      favourites_count,   // 전체 좋아요 카운트 / Full like count 
      replies_count: 0,
      favourited: !!favourited, // 전체 좋아요 / Full like
      reblogged: !!reblogged,   // 전체 부스트 / Full Boost
      muted: false, bookmarked: false, pinned: false,
      // ✅ myapp55 - Tusky 필수 / Required for Tusky 
      sensitive: false, spoiler_text: '',
      media_attachments: [],
      mentions: [],
      tags: [],
      emojis: [],
      card: null,
      poll: null,
      reblog: null,
    };
}

📁 코드 수정 / Code Modification

✔️ 데이터베이스가 수정되었기 때문에 관련된 부분을 모두 수정합니다.
Since the database has been modified, all related parts are being updated.

✔️ app/api/v1/statuses/route.ts – 글쓰기 API / Writin post API

... ...

export async function POST(req: Request) { 

... ...
    // ✅ myapp57 - Add Reply
    const inReplyToId = body.in_reply_to_id || body.inReplyToId || null;
    const inReplyToUsername = body.in_reply_to_username || body.inReplyToUsername || null;

... ...

    // ✅ myapp57 - posts 저장에 reply 컬럼 추가 / Added reply column to posts storage
    try {
      db.prepare(`INSERT INTO posts (id, content, created_at, username, visibility, in_reply_to_id, in_reply_to_username) VALUES (?,?,?,?,?,?,?)`)
        .run(id, content, now, username, visibility, inReplyToId, inReplyToUsername);
    } catch (e) {
      console.error('posts 저장 에러 / posts save error', e);
    }
... ...
   // ✅ myapp48 + myapp51 + myapp57 
   // - any로 해야 inReplyTo 추가 가능 / you need to add "any" type so then you can to use "ReplyTo"
    const note: any = {
      id: `https://${DOMAIN}/users/${username}/statuses/${id}`,
      type: 'Note',
      content: `<p>${content}</p>`,
      attributedTo: `https://${DOMAIN}/users/${username}`,
      published: new Date(now).toISOString(),
      to,
      cc,
      attachment: attachments.map(m => ({
        type: 'Document',
        mediaType: m.type,
        url: toAbsoluteUrl(m.url)
      }))
    };

}

✔️ app/api/v1/statuses/[id]/route.ts

— 기존 라우트에 GET 라우트 추가 / Add a GET route to the existing route.

// ✅ myapp57 - Pinafore에서 내 글이면 DELET E보여줌 / In Pinafore, it shows "DELETE" for my own posts.
export async function GET(
  req: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  const { id } = await params;

  const row = db.prepare(`
    SELECT p.*, u.mastodon_id FROM posts p 
    LEFT JOIN users u ON p.username=u.username 
    WHERE p.id=? 
  `).get(id) as any;

  if (!row) {
    return NextResponse.json({ error: 'not found' }, { status: 404, headers: { 'Access-Control-Allow-Origin': '*' } });
  }

  return NextResponse.json({
    id: String(row.id),
    uri: `https://${DOMAIN}/users/${row.username}/statuses/${row.id}`,
    url: `https://${DOMAIN}/users/${row.username}/statuses/${row.id}`,
    created_at: new Date(row.created_at).toISOString(),
    content: row.content?.startsWith('<') ? row.content : `<p>${row.content}</p>`,
    account: {
      id: String(row.mastodon_id || row.username), // ✅ 여기가 verify_credentials랑 같아야 Delete 생김 / The 'Delete' option only appears if this matches `verify_credentials`.
      username: row.username,
      acct: `${row.username}@${DOMAIN}`,
      display_name: row.username,
      avatar: `https://${DOMAIN}/icon.png`,
      avatar_static: `https://${DOMAIN}/icon.png`,
    },
    visibility: row.visibility || 'public',
    in_reply_to_id: row.in_reply_to_id || null,
    reblogs_count: 0, favourites_count: 0, replies_count: 0,
    favourited: false, reblogged: false, muted: false,
    sensitive: false, spoiler_text: '', 
    media_attachments: [],
    mentions: [], tags: [], emojis: [],
  }, { headers: { 'Access-Control-Allow-Origin': '*' } });
}

✔️ app/api/v1/statuses/[id]/context/route.ts – 라우트 추가 / Add route – Pinafore

... ...
// ✅ myapp57 - Pinafore에서 내 글이면 DELET E보여줌 / In Pinafore, it shows "DELETE" for my own posts.
export async function GET(
  req: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  const { id } = await params;

  const row = db.prepare(`
    SELECT p.*, u.mastodon_id FROM posts p 
    LEFT JOIN users u ON p.username=u.username 
    WHERE p.id=? 
  `).get(id) as any;

  if (!row) {
    return NextResponse.json({ error: 'not found' }, { status: 404, headers: { 'Access-Control-Allow-Origin': '*' } });
  }

  return NextResponse.json({
    id: String(row.id),
    uri: `https://${DOMAIN}/users/${row.username}/statuses/${row.id}`,
    url: `https://${DOMAIN}/users/${row.username}/statuses/${row.id}`,
    created_at: new Date(row.created_at).toISOString(),
    content: row.content?.startsWith('<') ? row.content : `<p>${row.content}</p>`,
    account: {
      id: String(row.mastodon_id || row.username), // ✅ 여기가 verify_credentials랑 같아야 Delete 생김 / The 'Delete' option only appears if this matches `verify_credentials`.
      username: row.username,
      acct: `${row.username}@${DOMAIN}`,
      display_name: row.username,
      avatar: `https://${DOMAIN}/icon.png`,
      avatar_static: `https://${DOMAIN}/icon.png`,
    },
    visibility: row.visibility || 'public',
    in_reply_to_id: row.in_reply_to_id || null,
    reblogs_count: 0, favourites_count: 0, replies_count: 0,
    favourited: false, reblogged: false, muted: false,
    sensitive: false, spoiler_text: '', 
    media_attachments: [],
    mentions: [], tags: [], emojis: [],
  }, { headers: { 'Access-Control-Allow-Origin': '*' } });
}
... ...

✔️ app/api/v1/statuses/[id]/route.ts

 export async function GET(req: Request) { ... ...  
    return {
      id: String(row.id),
      uri: longId,
      url: longId,
      account: baseAccount,
      content: content.startsWith('<')? content : `<p>${content}</p>`,
      created_at: new Date(parseDate(row.created_at)).toISOString(),
      visibility: row.visibility || 'public', // ✅ myapp57
      // ✅ myapp57 - reply 필드 추가 / Add reply fileds 
      in_reply_to_id: row.in_reply_to_id ? String(row.in_reply_to_id) : null,
      in_reply_to_account_id: row.in_reply_to_account_id ? String(row.in_reply_to_account_id) : null,
      reblogs_count,      // 전체 부스트 카운트 / Full boost count
      favourites_count,   // 전체 좋아요 카운트 / Full like count 
      replies_count: 0,
      favourited: !!favourited, // 전체 좋아요 / Full like
      reblogged: !!reblogged,   // 전체 부스트 / Full Boost
      muted: false, bookmarked: false, pinned: false,
      // ✅ myapp55 - Tusky 필수 / Required for Tusky 
      sensitive: false, spoiler_text: '',
      media_attachments: [],
      mentions: [],
      tags: [],
      emojis: [],
      card: null,
      poll: null,
      reblog: null,
    };
... ... }

✔️ app/api/v1/timelines/home/route.ts

  ... ...  
  return {
      id: String(row.id),
      uri: longId,
      url: longId,
      account: baseAccount,
      content: content.startsWith('<')? content : `<p>${content}</p>`,
      created_at: new Date(parseDate(row.created_at)).toISOString(),
      visibility: row.visibility || 'public', // ✅ myapp57
      // ✅ myapp57 - reply 필드 추가 / Add reply fileds 
      in_reply_to_id: row.in_reply_to_id ? String(row.in_reply_to_id) : null,
      in_reply_to_account_id: row.in_reply_to_account_id ? String(row.in_reply_to_account_id) : null,
      reblogs_count,      // 전체 부스트 카운트 / Full boost count
      favourites_count,   // 전체 좋아요 카운트 / Full like count 
      replies_count: 0,
      favourited: !!favourited, // 전체 좋아요 / Full like
      reblogged: !!reblogged,   // 전체 부스트 / Full Boost
      muted: false, bookmarked: false, pinned: false,
      // ✅ myapp55 - Tusky 필수 / Required for Tusky 
      sensitive: false, spoiler_text: '',
      media_attachments: (() => {
        // ✅ myapp57 - image 있으면 여기서 반환 / Return the image here if it exists.
        try {
          const medias = db.prepare(`
          SELECT ma.* FROM media_attachments ma
          JOIN post_media pm ON pm.media_id = ma.id
          WHERE pm.post_id=?
          `).all(row.id) as any[];
          return medias.map((m:any) => ({
            id: String(m.id),
            type: 'image',
            url: m.url.startsWith('http') ? m.url : `https://${DOMAIN}${m.url}`,
            preview_url: m.url.startsWith('http') ? m.url : `https://${DOMAIN}${m.url}`,
          }));
        } catch { return []; }
      })(),
      mentions: [],
      tags: [],
      emojis: [],
      card: null,
      poll: null,
      reblog: null,
    };
... ...

✔️ app/api/timeline/route.ts – 다음 프로젝트에서 수정 / Revise in the next project

📁 테스트 / Test

✔️ 답글 작성 / Write a reply

reply

✔️ 답글 확인 / Check for replies

reply

마태복음 21장 22절 / Matthew 21: 22

“너희가 기도할 때에 무엇이든지 믿고 구하는 것은 다 받으리라 하시니라”

“And everything you ask in prayer, believing, you will receive.”

Leave a Reply