Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

# Output of the go coverage tool, specifically when used with LiteIDE
*.out
artalk

# Dependency directories (remove the comment below to include it)
# vendor/
Expand Down
31 changes: 28 additions & 3 deletions internal/dao/cook.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ package dao

import (
"strings"
"time"

"github.com/artalkjs/artalk/v2/internal/entity"
"github.com/artalkjs/artalk/v2/internal/utils"
Expand All @@ -12,6 +13,20 @@ import (

const CommonDateTimeFormat = "2006-01-02 15:04:05"

type cookedTime struct {
Legacy string
Unix int64
UTC string
}

func cookTime(t time.Time) cookedTime {
return cookedTime{
Legacy: t.Local().Format(CommonDateTimeFormat),
Unix: t.Unix(),
UTC: t.UTC().Format(time.RFC3339),
}
}

// TODO: (refactor) remove this global variable
var getCommentEmailHash = func(email string) string { return utils.GetMD5Hash(strings.ToLower(email)) }

Expand Down Expand Up @@ -42,6 +57,7 @@ func (dao *Dao) CookComment(c *entity.Comment) entity.CookedComment {
}

markedContent, _ := utils.Marked(c.Content)
createdAt := cookTime(c.CreatedAt)

return entity.CookedComment{
ID: c.ID,
Expand All @@ -52,7 +68,9 @@ func (dao *Dao) CookComment(c *entity.Comment) entity.CookedComment {
EmailEncrypted: getCommentEmailHash(user.Email),
Link: user.Link,
UA: c.UA,
Date: c.CreatedAt.Local().Format(CommonDateTimeFormat),
Date: createdAt.Legacy,
DateUnix: createdAt.Unix,
DateUTC: createdAt.UTC,
IsCollapsed: c.IsCollapsed,
IsPending: c.IsPending,
IsPinned: c.IsPinned,
Expand Down Expand Up @@ -84,14 +102,15 @@ func (dao *Dao) CookCommentForEmail(c *entity.Comment) entity.CookedCommentForEm
page := dao.FetchPageForComment(c)
site := dao.FetchSiteForComment(c)
content, _ := utils.Marked(c.Content)
createdAt := cookTime(c.CreatedAt)

return entity.CookedCommentForEmail{
Content: content,
ContentRaw: c.Content,
Nick: user.Name,
Email: user.Email,
IP: c.IP,
Datetime: c.CreatedAt.Local().Format(CommonDateTimeFormat),
Datetime: createdAt.Legacy,
Date: c.CreatedAt.Local().Format("2006-01-02"),
Time: c.CreatedAt.Local().Format("15:04:05"),
PageKey: c.PageKey,
Expand All @@ -104,6 +123,8 @@ func (dao *Dao) CookCommentForEmail(c *entity.Comment) entity.CookedCommentForEm
EmailEncrypted: getCommentEmailHash(user.Email),
Link: user.Link,
UA: c.UA,
DateUnix: createdAt.Unix,
DateUTC: createdAt.UTC,
IsCollapsed: c.IsCollapsed,
IsPending: c.IsPending,
IsPinned: c.IsPinned,
Expand All @@ -120,6 +141,8 @@ func (dao *Dao) CookCommentForEmail(c *entity.Comment) entity.CookedCommentForEm
// ===============

func (dao *Dao) CookPage(p *entity.Page) entity.CookedPage {
createdAt := cookTime(p.CreatedAt)

return entity.CookedPage{
ID: p.ID,
AdminOnly: p.AdminOnly,
Expand All @@ -130,7 +153,9 @@ func (dao *Dao) CookPage(p *entity.Page) entity.CookedPage {
VoteUp: p.VoteUp,
VoteDown: p.VoteDown,
PV: p.PV,
Date: p.CreatedAt.Local().Format(CommonDateTimeFormat),
Date: createdAt.Legacy,
DateUnix: createdAt.Unix,
DateUTC: createdAt.UTC,
}
}

Expand Down
47 changes: 47 additions & 0 deletions internal/dao/cook_time_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package dao_test

import (
"encoding/json"
"testing"
"time"

"github.com/artalkjs/artalk/v2/internal/dao"
"github.com/artalkjs/artalk/v2/internal/entity"
"github.com/stretchr/testify/require"
"gorm.io/gorm"
)

func TestCookedTimestampsAcrossTimezones(t *testing.T) {
originalLocal := time.Local
t.Cleanup(func() { time.Local = originalLocal })
instant := time.Date(2025, 1, 2, 3, 4, 5, 0, time.UTC)
d := &dao.Dao{}

for _, zone := range []*time.Location{
time.UTC,
time.FixedZone("UTC+8", 8*60*60),
time.FixedZone("UTC-5", -5*60*60),
} {
t.Run(zone.String(), func(t *testing.T) {
time.Local = zone
model := gorm.Model{CreatedAt: instant.In(zone)}
page := &entity.Page{Model: model, Key: "https://example.test/page"}
comment := &entity.Comment{Model: model, Page: page, User: &entity.User{}}

for _, response := range []any{d.CookComment(comment), d.CookPage(page)} {
data, err := json.Marshal(response)
require.NoError(t, err)
var fields map[string]json.RawMessage
require.NoError(t, json.Unmarshal(data, &fields))
var unix int64
var utc, legacy string
require.NoError(t, json.Unmarshal(fields["date_unix"], &unix))
require.NoError(t, json.Unmarshal(fields["date_utc"], &utc))
require.NoError(t, json.Unmarshal(fields["date"], &legacy))
require.Equal(t, instant.Unix(), unix)
require.Equal(t, "2025-01-02T03:04:05Z", utc)
require.Equal(t, instant.In(zone).Format(dao.CommonDateTimeFormat), legacy)
}
})
}
}
2 changes: 2 additions & 0 deletions internal/entity/comment_cooked.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ type CookedComment struct {
Link string `json:"link"`
UA string `json:"ua"`
Date string `json:"date"`
DateUnix int64 `json:"date_unix"`
DateUTC string `json:"date_utc"`
IsCollapsed bool `json:"is_collapsed"`
IsPending bool `json:"is_pending"`
IsPinned bool `json:"is_pinned"`
Expand Down
2 changes: 2 additions & 0 deletions internal/entity/page_cooked.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,6 @@ type CookedPage struct {
VoteDown int `json:"vote_down"`
PV int `json:"pv"`
Date string `json:"date"`
DateUnix int64 `json:"date_unix"`
DateUTC string `json:"date_utc"`
}
12 changes: 12 additions & 0 deletions ui/artalk/src/api/v2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ export interface EntityCookedComment {
content: string
content_marked: string
date: string
date_unix: number
date_utc: string
email_encrypted: string
id: number
ip_region?: string
Expand Down Expand Up @@ -76,6 +78,8 @@ export interface EntityCookedNotify {
export interface EntityCookedPage {
admin_only: boolean
date: string
date_unix: number
date_utc: string
id: number
key: string
pv: number
Expand Down Expand Up @@ -373,6 +377,8 @@ export interface HandlerResponseCommentCreate {
content: string
content_marked: string
date: string
date_unix: number
date_utc: string
email_encrypted: string
id: number
ip_region?: string
Expand Down Expand Up @@ -414,6 +420,8 @@ export interface HandlerResponseCommentUpdate {
content: string
content_marked: string
date: string
date_unix: number
date_utc: string
email_encrypted: string
id: number
ip_region?: string
Expand Down Expand Up @@ -456,6 +464,8 @@ export interface HandlerResponseNotifyList {
export interface HandlerResponsePageFetch {
admin_only: boolean
date: string
date_unix: number
date_utc: string
id: number
key: string
pv: number
Expand Down Expand Up @@ -489,6 +499,8 @@ export interface HandlerResponsePagePV {
export interface HandlerResponsePageUpdate {
admin_only: boolean
date: string
date_unix: number
date_utc: string
id: number
key: string
pv: number
Expand Down
9 changes: 7 additions & 2 deletions ui/artalk/src/comment/comment-node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ export default class CommentNode {
constructor(data: CommentData, opts: CommentOptions) {
this.opts = opts
this.data = { ...data }
this.data.date = this.data.date.replace(/-/g, '/') // 解决 Safari 日期解析 NaN 问题
this.data.date = this.data.date.replace(/-/g, '/')

this.parent = null
this.nestCurt = 1 // 现在已嵌套 n 层
Expand Down Expand Up @@ -214,9 +214,14 @@ export default class CommentNode {
return marked(this.data.content)
}

/** Get the parsed comment creation time. */
public getCreatedAt() {
return Utils.parseDate(this.data)
}

/** 获取格式化后的日期 */
public getDateFormatted() {
const date = new Date(this.data.date)
const date = this.getCreatedAt()
return this.opts.dateFormatter?.(date) || Utils.timeAgo(date, $t)
}

Expand Down
2 changes: 1 addition & 1 deletion ui/artalk/src/comment/renders/header.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ function renderVerifyBadge(ctx: Render) {
function renderDate(ctx: Render) {
const $date = ctx.$el.querySelector<HTMLElement>('.atk-date')!
$date.innerText = ctx.comment.getDateFormatted()
$date.setAttribute('data-atk-comment-date', String(+new Date(ctx.data.date)))
$date.setAttribute('data-atk-comment-date', String(+ctx.comment.getCreatedAt()))
}

function renderUABadge(ctx: Render) {
Expand Down
26 changes: 26 additions & 0 deletions ui/artalk/src/lib/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,32 @@ export function padWithZeros(vNumber: number, width: number) {
return numAsString
}

export interface TimestampedDateInput {
date?: string
date_unix?: number
date_utc?: string
}

/**
* Parses timestamp fields returned by Artalk APIs.
*
* `date_unix` and `date_utc` are timezone-safe and take precedence over the legacy
* timezone-less `date` field, which is only used for backward compatibility.
*/
export function parseDate(input: TimestampedDateInput) {
if (typeof input.date_unix === 'number' && Number.isFinite(input.date_unix)) {
Comment thread
awaae001 marked this conversation as resolved.
Resolved
const unixDate = new Date(input.date_unix * 1000)
if (!Number.isNaN(unixDate.getTime())) return unixDate
}

if (input.date_utc) {
const utcDate = new Date(input.date_utc)
if (!Number.isNaN(utcDate.getTime())) return utcDate
}

return new Date((input.date || '').replace(/-/g, '/'))
}

export function dateFormat(date: Date) {
const vDay = padWithZeros(date.getDate(), 2)
const vMonth = padWithZeros(date.getMonth() + 1, 2)
Expand Down
5 changes: 3 additions & 2 deletions ui/artalk/src/list/nest.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { CommentData } from '@/types'
import { parseDate } from '@/lib/utils'

export type CommentNode = {
id: number
Expand Down Expand Up @@ -51,8 +52,8 @@ export function makeNestCommentNodeList(
// 排序
const sortFunc = (a: CommentNode, b: CommentNode): number => {
let v = a.id - b.id
if (sortBy === 'DATE_ASC') v = +new Date(a.comment.date) - +new Date(b.comment.date)
else if (sortBy === 'DATE_DESC') v = +new Date(b.comment.date) - +new Date(a.comment.date)
if (sortBy === 'DATE_ASC') v = +parseDate(a.comment) - +parseDate(b.comment)
else if (sortBy === 'DATE_DESC') v = +parseDate(b.comment) - +parseDate(a.comment)
else if (sortBy === 'SRC_INDEX') v = srcData.indexOf(a.comment) - srcData.indexOf(b.comment)
else if (sortBy === 'VOTE_UP_DESC') v = b.comment.vote_up - a.comment.vote_up
return v
Expand Down
6 changes: 6 additions & 0 deletions ui/artalk/src/types/data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,12 @@ export interface CommentData {
/** 评论日期 */
date: string

/** 评论日期 Unix 秒级时间戳 */
date_unix?: number

/** 评论日期 UTC RFC3339 字符串 */
date_utc?: string

/** 是否折叠 */
is_collapsed: boolean

Expand Down
72 changes: 72 additions & 0 deletions ui/artalk/tests/timestamps.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import { expect, it, vi } from 'vitest'
import CommentNode from '@/comment/comment-node'
import { Defaults } from '@/defaults'
import { parseDate } from '@/lib/utils'
import { makeNestCommentNodeList } from '@/list/nest'
import type { CommentData } from '@/types'

it('keeps timestamp parsing, comment display and date sorting compatible', () => {
const instant = Date.parse('2025-01-02T03:04:05Z')
const legacy = '2025-01-01 03:04:05'
const base: CommentData = {
id: 1,
rid: 0,
content: '',
nick: 'Synthetic user',
email_encrypted: '',
link: '',
ua: '',
date: '2025-01-08 00:00:00',
is_collapsed: false,
is_pending: false,
is_pinned: false,
is_verified: false,
is_allow_reply: true,
page_key: '/test',
visible: true,
site_name: 'test',
vote_up: 0,
vote_down: 0,
}
const opts = {
...Defaults,
flatMode: false,
getApi: vi.fn(),
replyComment: vi.fn(),
editComment: vi.fn(),
dateFormatter: (date: Date) => date.toISOString(),
}

// Unix seconds take precedence; UTC strings must also preserve the instant.
expect(+parseDate({ ...base, date_unix: instant / 1000, date_utc: '2025-01-09T00:00:00Z' })).toBe(
instant,
)
for (const date_utc of [
'2025-01-02T03:04:05Z',
'2025-01-02T11:04:05+08:00',
'2025-01-01T22:04:05-05:00',
]) {
expect(+parseDate({ ...base, date_utc })).toBe(instant)
}

const comments: CommentData[] = [
base,
{ ...base, id: 3, rid: 1, date_utc: '2025-01-03T03:04:05Z' },
{ ...base, id: 4, rid: 1, date: legacy },
{ ...base, id: 2, rid: 1, date_unix: instant / 1000, date_utc: '2025-01-09T00:00:00Z' },
]
const expected = [instant, Date.parse('2025-01-03T03:04:05Z'), +new Date(2025, 0, 1, 3, 4, 5)]
for (const [index, id] of [2, 3, 4].entries()) {
const data = comments.find((comment) => comment.id === id)!
const node = new CommentNode(data, opts)
expect(+parseDate(data)).toBe(expected[index])
expect(+node.getCreatedAt()).toBe(expected[index])
expect(node.getDateFormatted()).toBe(new Date(expected[index]).toISOString())
}
expect(makeNestCommentNodeList(comments, 'DATE_ASC')[0].children.map((node) => node.id)).toEqual([
4, 2, 3,
])
expect(makeNestCommentNodeList(comments, 'DATE_DESC')[0].children.map((node) => node.id)).toEqual(
[3, 2, 4],
)
})