Merge pull request 'Newsletter mode' (#39) from feat/newsletter into main
This commit is contained in:
commit
9a51b39eef
45 changed files with 3631 additions and 88 deletions
25
README.md
25
README.md
|
|
@ -20,6 +20,7 @@ A modern, single-binary mailing list manager: an evolution of Mailman.
|
|||
send to `list+join@domain` or `list+leave@domain`, then reply to the confirmation. A reply works once, a request
|
||||
expires after 72 hours, and a confirmation that could not be applied (closed list, database error) can be replied to again.
|
||||
A member disabled by bounces can rejoin the same way.
|
||||
- Newsletters: a `publishers` post policy, sent-post statistics, a relay rate limit and a public subscribe form.
|
||||
- Moderated lists: posts wait in a queue that the API can approve or discard.
|
||||
- VERP bounces: every recipient gets a signed return address; 3 hard bounces within 30 days disable a member.
|
||||
- Archive with full-text search (SQLite FTS5) and threading. Each list has an
|
||||
|
|
@ -56,6 +57,30 @@ The admin UI and the public archive, with demo data (`docs/screenshots/`).
|
|||
|
||||

|
||||
|
||||
## Newsletters
|
||||
|
||||
A newsletter is a list whose post policy is `publishers`: only members flagged as publishers may post, and everybody else just receives. Everything else (double opt-in, one-click unsubscribe, DKIM, archive, bounces, the queue) works as for a discussion list.
|
||||
|
||||
```sh
|
||||
parsimony list set news@example.org --post publishers
|
||||
parsimony member add news@example.org alice@example.com --publisher
|
||||
parsimony member set news@example.org alice@example.com --publisher=false # demote
|
||||
```
|
||||
|
||||
In the admin UI, pick "Publishers only (newsletter)" in the list's Settings tab and use the "Can publish" checkbox or the "Make publisher" action on the Members tab. The API uses `PATCH /api/v1/lists/{id}/members/{address}` with `{"publisher": true}`. `member import` accepts `email,name,publisher` lines. `member ls` shows each member's role.
|
||||
|
||||
A publisher's post passes the same identity check as any post: the `From` header must name the SMTP sender, or the post is held. A post from anyone else, member or not, is refused with `550 5.7.1`; it is never held, archived or queued. A publisher disabled by bounces can still post.
|
||||
|
||||
**Sent posts.** Each post queued to a list is recorded with its subject, time and number of recipients, and the queue counts how its deliveries end: **sent** (accepted by the relay), **failed** (refused, or still failing after 3 days), **dropped** (the mailbox does not exist, or the delivery was discarded) and **pending**. A count changes in the same transaction as the delivery. See them with `parsimony posts ls news@example.org`, `GET /api/v1/lists/{id}/posts`, or the Sent tab of a list, which refreshes every 5 seconds while something is pending. Posts are kept for 400 days. Parsimony does not track opens or clicks.
|
||||
|
||||
**Priority.** Newsletter deliveries go out after everything else that is due, so a big newsletter never delays discussion mail or confirmations.
|
||||
|
||||
**Rate limiting.** Relays such as Amazon SES throttle sending. Set `relay.rate_per_second` to the most sends the daemon may start in one second (default `0`, unlimited). One pacer sits in front of every send attempt, retries included, and spaces them evenly. Set it a little under your relay's limit (12 for a limit of 14). Each recipient is one message, so a post to N members takes about N divided by the rate in seconds.
|
||||
|
||||
**Subscribe form.** A list whose archive is public and whose join policy is open gets a signup page at `/subscribe/{address}` on the public web listener, linked from its archive page. It sends the usual double opt-in message. The page that follows is always the same, whether or not the address is a member or the list qualifies for mail, so the form cannot be used to find out who is subscribed. A hidden field catches bots; each IP (the TCP peer, `X-Forwarded-For` is ignored) may post 10 times per hour, then gets `429`; behind a reverse proxy every visitor shares its address, so limit at the proxy too. The body is capped at 4 KiB.
|
||||
|
||||
Not included: scheduled sends and open or click tracking.
|
||||
|
||||
## Run
|
||||
|
||||
```
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ import { NotFoundPage } from '@/pages/NotFoundPage'
|
|||
import { ArchiveTab } from '@/tabs/ArchiveTab'
|
||||
import { HeldTab } from '@/tabs/HeldTab'
|
||||
import { MembersTab } from '@/tabs/MembersTab'
|
||||
import { SentTab } from '@/tabs/SentTab'
|
||||
import { SettingsTab } from '@/tabs/SettingsTab'
|
||||
import { QueuePage } from '@/pages/QueuePage'
|
||||
import { Toaster } from '@/components/ui/sonner'
|
||||
|
|
@ -25,6 +26,7 @@ export function App() {
|
|||
<Route path="members" element={<MembersTab />} />
|
||||
<Route path="held" element={<HeldTab />} />
|
||||
<Route path="archive" element={<ArchiveTab />} />
|
||||
<Route path="sent" element={<SentTab />} />
|
||||
</Route>
|
||||
<Route path="*" element={<NotFoundPage />} />
|
||||
</Route>
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
// Typed client for the Parsimony admin REST API (/api/v1).
|
||||
|
||||
export type PostPolicy = 'members' | 'moderated'
|
||||
export type PostPolicy = 'members' | 'moderated' | 'publishers'
|
||||
export type JoinPolicy = 'open' | 'closed'
|
||||
export type ArchivePolicy = 'public' | 'private' | 'off'
|
||||
|
||||
|
|
@ -20,6 +20,8 @@ export interface Member {
|
|||
display_name: string
|
||||
disabled: boolean
|
||||
bounce_count: number
|
||||
/** May post when the list's post policy is 'publishers'. */
|
||||
publisher: boolean
|
||||
}
|
||||
|
||||
export interface Held {
|
||||
|
|
@ -79,6 +81,22 @@ export interface Queue {
|
|||
items: QueueItem[]
|
||||
}
|
||||
|
||||
/** A post queued to a list, with how far its delivery got. */
|
||||
export interface Post {
|
||||
id: number
|
||||
message_id: string
|
||||
subject: string
|
||||
created_at: string
|
||||
/** Deliveries queued: the members when it was posted. */
|
||||
recipients: number
|
||||
sent: number
|
||||
failed: number
|
||||
/** The mailbox does not exist, or the delivery was discarded. */
|
||||
dropped: number
|
||||
/** Still in the queue. */
|
||||
pending: number
|
||||
}
|
||||
|
||||
export class ApiError extends Error {
|
||||
readonly status: number
|
||||
constructor(status: number, message: string) {
|
||||
|
|
@ -154,8 +172,11 @@ export const api = {
|
|||
},
|
||||
members: {
|
||||
list: (listId: number) => request<Member[]>('GET', `/lists/${listId}/members`),
|
||||
add: (listId: number, b: { address: string; display_name?: string }) =>
|
||||
/** Without publisher an existing member keeps its flag. */
|
||||
add: (listId: number, b: { address: string; display_name?: string; publisher?: boolean }) =>
|
||||
request<Member>('POST', `/lists/${listId}/members`, b),
|
||||
setPublisher: (listId: number, address: string, publisher: boolean) =>
|
||||
request<void>('PATCH', `/lists/${listId}/members/${enc(address)}`, { publisher }),
|
||||
remove: (listId: number, address: string) =>
|
||||
request<void>('DELETE', `/lists/${listId}/members/${enc(address)}`),
|
||||
},
|
||||
|
|
@ -164,6 +185,9 @@ export const api = {
|
|||
approve: (id: number) => request<void>('POST', `/held/${id}/approve`),
|
||||
discard: (id: number) => request<void>('DELETE', `/held/${id}`),
|
||||
},
|
||||
posts: {
|
||||
list: (listId: number) => request<Post[]>('GET', `/lists/${listId}/posts`),
|
||||
},
|
||||
queue: {
|
||||
get: () => request<Queue>('GET', '/queue'),
|
||||
discard: (id: number) => request<void>('DELETE', `/queue/${id}`),
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import { Badge } from '@/components/ui/badge'
|
|||
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs'
|
||||
import { api } from '@/lib/api'
|
||||
|
||||
const tabs = ['settings', 'members', 'held', 'archive'] as const
|
||||
const tabs = ['settings', 'members', 'held', 'archive', 'sent'] as const
|
||||
|
||||
export function ListPage() {
|
||||
const params = useParams()
|
||||
|
|
@ -42,6 +42,7 @@ export function ListPage() {
|
|||
{heldCount > 0 && <Badge className="ml-1">{heldCount}</Badge>}
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="archive">Archive</TabsTrigger>
|
||||
<TabsTrigger value="sent">Sent</TabsTrigger>
|
||||
</TabsList>
|
||||
</Tabs>
|
||||
<Outlet context={list.data} />
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ const member = (address: string, over: Partial<Member> = {}): Member => ({
|
|||
display_name: '',
|
||||
disabled: false,
|
||||
bounce_count: 0,
|
||||
publisher: false,
|
||||
...over,
|
||||
})
|
||||
|
||||
|
|
@ -105,6 +106,72 @@ describe('members tab', () => {
|
|||
expect(screen.queryByRole('button', { name: /re-enable/i })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
describe('publishers', () => {
|
||||
it('shows a Publisher badge on publishers only', async () => {
|
||||
await setup([member('alice@example.com', { publisher: true }), member('bob@example.com')])
|
||||
const alice = (await screen.findByText('alice@example.com')).closest('tr')!
|
||||
expect(within(alice).getByText('Publisher')).toBeInTheDocument()
|
||||
const bob = screen.getByText('bob@example.com').closest('tr')!
|
||||
expect(within(bob).queryByText('Publisher')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('adds a publisher with the Can publish checkbox, then clears it', async () => {
|
||||
const { user, state } = await setup()
|
||||
await user.type(screen.getByLabelText(/email address/i), 'dave@example.com')
|
||||
await user.click(screen.getByRole('checkbox', { name: /can publish/i }))
|
||||
await user.click(screen.getByRole('button', { name: /add member/i }))
|
||||
const row = (await screen.findByText('dave@example.com')).closest('tr')!
|
||||
expect(await within(row).findByText('Publisher')).toBeInTheDocument()
|
||||
expect(state.members[1][0].publisher).toBe(true)
|
||||
expect(screen.getByRole('checkbox', { name: /can publish/i })).not.toBeChecked()
|
||||
})
|
||||
|
||||
it('adding without the checkbox leaves an existing publisher alone', async () => {
|
||||
const { user, state } = await setup([member('dave@example.com', { publisher: true })])
|
||||
await screen.findByText('dave@example.com')
|
||||
expect(screen.getByRole('checkbox', { name: /can publish/i })).not.toBeChecked()
|
||||
await user.type(screen.getByLabelText(/email address/i), 'dave@example.com')
|
||||
await user.type(screen.getByLabelText(/display name/i), 'Dave')
|
||||
await user.click(screen.getByRole('button', { name: /add member/i }))
|
||||
await waitFor(() => expect(state.members[1][0].display_name).toBe('Dave'))
|
||||
expect(state.members[1][0].publisher).toBe(true)
|
||||
})
|
||||
|
||||
it('re-enabling keeps the publisher flag', async () => {
|
||||
const { user, state } = await setup([member('bob@example.com', { disabled: true, publisher: true })])
|
||||
const row = (await screen.findByText('bob@example.com')).closest('tr')!
|
||||
await user.click(within(row).getByRole('button', { name: /re-enable/i }))
|
||||
await waitFor(() => expect(state.members[1][0].disabled).toBe(false))
|
||||
expect(state.members[1][0].publisher).toBe(true)
|
||||
})
|
||||
|
||||
it('makes a member a publisher and back', async () => {
|
||||
const { user, state } = await setup([member('a+b@example.com')])
|
||||
let row = (await screen.findByText('a+b@example.com')).closest('tr')!
|
||||
await user.click(within(row).getByRole('button', { name: /make publisher/i }))
|
||||
await waitFor(() => expect(state.members[1][0].publisher).toBe(true))
|
||||
expect(state.calls).toContain('PATCH /lists/1/members/a%2Bb%40example.com')
|
||||
row = screen.getByText('a+b@example.com').closest('tr')!
|
||||
expect(await within(row).findByText('Publisher')).toBeInTheDocument()
|
||||
expect(await screen.findByText(/a\+b@example.com can now publish/i)).toBeInTheDocument()
|
||||
|
||||
await user.click(within(row).getByRole('button', { name: /make subscriber/i }))
|
||||
await waitFor(() => expect(state.members[1][0].publisher).toBe(false))
|
||||
row = screen.getByText('a+b@example.com').closest('tr')!
|
||||
await waitFor(() => expect(within(row).queryByText('Publisher')).not.toBeInTheDocument())
|
||||
expect(within(row).getByRole('button', { name: /make publisher/i })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows the server error of the row action', async () => {
|
||||
const { user, state } = await setup([member('alice@example.com')])
|
||||
const row = (await screen.findByText('alice@example.com')).closest('tr')!
|
||||
state.fail['PATCH /lists/1/members/alice%40example.com'] = { status: 500, error: 'locked' }
|
||||
await user.click(within(row).getByRole('button', { name: /make publisher/i }))
|
||||
expect(await screen.findByText('locked')).toBeInTheDocument()
|
||||
expect(state.members[1][0].publisher).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('removing', () => {
|
||||
async function open() {
|
||||
const ctx = await setup([member('alice@example.com'), member('a+b@example.com')])
|
||||
|
|
|
|||
|
|
@ -36,6 +36,15 @@ export function MembersTab() {
|
|||
onError: (e: Error) => toast.error(e.message),
|
||||
})
|
||||
|
||||
const setPublisher = useMutation({
|
||||
mutationFn: (m: Member) => api.members.setPublisher(list.id, m.address, !m.publisher),
|
||||
onSuccess: async (_, m) => {
|
||||
await queryClient.invalidateQueries({ queryKey: key })
|
||||
toast.success(m.publisher ? `${m.address} is now a subscriber` : `${m.address} can now publish`)
|
||||
},
|
||||
onError: (e: Error) => toast.error(e.message),
|
||||
})
|
||||
|
||||
const all = members.data ?? []
|
||||
const q = filter.trim().toLowerCase()
|
||||
const shown = q ? all.filter((m) => m.address.includes(q) || m.display_name.toLowerCase().includes(q)) : all
|
||||
|
|
@ -76,6 +85,7 @@ export function MembersTab() {
|
|||
<TableCell className="font-medium">{m.address}</TableCell>
|
||||
<TableCell>{m.display_name}</TableCell>
|
||||
<TableCell className="space-x-2">
|
||||
{m.publisher && <Badge>Publisher</Badge>}
|
||||
{m.disabled ? <Badge variant="destructive">Disabled</Badge> : <Badge variant="secondary">Active</Badge>}
|
||||
{m.bounce_count > 0 && (
|
||||
<span className="text-sm text-muted-foreground">
|
||||
|
|
@ -89,6 +99,9 @@ export function MembersTab() {
|
|||
Re-enable
|
||||
</Button>
|
||||
)}
|
||||
<Button size="sm" variant="outline" disabled={setPublisher.isPending} onClick={() => setPublisher.mutate(m)}>
|
||||
{m.publisher ? 'Make subscriber' : 'Make publisher'}
|
||||
</Button>
|
||||
<Button size="sm" variant="outline" onClick={() => setRemoving(m)}>
|
||||
Remove
|
||||
</Button>
|
||||
|
|
@ -109,15 +122,19 @@ function AddMemberForm({ list }: { list: List }) {
|
|||
const queryClient = useQueryClient()
|
||||
const [address, setAddress] = useState('')
|
||||
const [name, setName] = useState('')
|
||||
const [publisher, setPublisher] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
const add = useMutation({
|
||||
mutationFn: () => api.members.add(list.id, { address: address.trim(), display_name: name.trim() }),
|
||||
// Unchecked sends no flag, so adding an existing publisher again does not demote it.
|
||||
mutationFn: () =>
|
||||
api.members.add(list.id, { address: address.trim(), display_name: name.trim(), ...(publisher ? { publisher: true } : {}) }),
|
||||
onSuccess: async (m) => {
|
||||
await queryClient.invalidateQueries({ queryKey: ['members', list.id] })
|
||||
toast.success(`Added ${m.address}`)
|
||||
setAddress('')
|
||||
setName('')
|
||||
setPublisher(false)
|
||||
setError(null)
|
||||
},
|
||||
onError: (e: Error) => setError(e.message),
|
||||
|
|
@ -144,6 +161,16 @@ function AddMemberForm({ list }: { list: List }) {
|
|||
<Label htmlFor="member-name">Display name</Label>
|
||||
<Input id="member-name" value={name} onChange={(e) => setName(e.target.value)} autoComplete="off" />
|
||||
</div>
|
||||
<div className="flex h-9 items-center gap-2">
|
||||
<input
|
||||
id="member-publisher"
|
||||
type="checkbox"
|
||||
className="size-4"
|
||||
checked={publisher}
|
||||
onChange={(e) => setPublisher(e.target.checked)}
|
||||
/>
|
||||
<Label htmlFor="member-publisher">Can publish</Label>
|
||||
</div>
|
||||
<Button type="submit" disabled={add.isPending}>
|
||||
Add member
|
||||
</Button>
|
||||
|
|
|
|||
113
admin/src/tabs/SentTab.test.tsx
Normal file
113
admin/src/tabs/SentTab.test.tsx
Normal file
|
|
@ -0,0 +1,113 @@
|
|||
import { act, screen, within } from '@testing-library/react'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { Post } from '@/lib/api'
|
||||
import { aList, installFakeApi, newState } from '@/test/fakeApi'
|
||||
import { renderApp } from '@/test/render'
|
||||
|
||||
const post = (id: number, over: Partial<Post> = {}): Post => ({
|
||||
id,
|
||||
message_id: `<${id}@example.org>`,
|
||||
subject: `Issue ${id}`,
|
||||
created_at: '2030-01-02T03:04:05Z',
|
||||
recipients: 4,
|
||||
sent: 4,
|
||||
failed: 0,
|
||||
dropped: 0,
|
||||
pending: 0,
|
||||
...over,
|
||||
})
|
||||
|
||||
async function setup(posts: Post[]) {
|
||||
const state = installFakeApi(newState({ lists: [aList({ id: 1 })], posts: { 1: posts } }))
|
||||
const ctx = renderApp('/lists/1/sent', { token: 'good' })
|
||||
await screen.findByRole('heading', { name: /sent posts/i, level: 2 })
|
||||
return { ...ctx, state }
|
||||
}
|
||||
|
||||
const postCalls = (calls: string[]) => calls.filter((c) => c === 'GET /lists/1/posts').length
|
||||
|
||||
afterEach(() => vi.useRealTimers())
|
||||
|
||||
describe('sent tab', () => {
|
||||
it('is a tab of the list page', async () => {
|
||||
installFakeApi(newState({ lists: [aList({ id: 1 })], posts: { 1: [post(1)] } }))
|
||||
const { user } = renderApp('/lists/1', { token: 'good' })
|
||||
await user.click(await screen.findByRole('tab', { name: /^sent$/i }))
|
||||
expect(await screen.findByRole('heading', { name: /sent posts/i, level: 2 })).toBeInTheDocument()
|
||||
expect(await screen.findByText('Issue 1')).toBeInTheDocument()
|
||||
expect(screen.getByRole('tab', { name: /^sent$/i })).toHaveAttribute('aria-selected', 'true')
|
||||
})
|
||||
|
||||
it('says when nothing was sent yet', async () => {
|
||||
await setup([])
|
||||
expect(await screen.findByText(/nothing has been sent to this list yet/i)).toBeInTheDocument()
|
||||
expect(screen.queryByRole('table')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows each post with its counts and progress', async () => {
|
||||
await setup([
|
||||
post(2, { subject: '', recipients: 10, sent: 6, failed: 1, dropped: 1, pending: 2 }),
|
||||
post(1),
|
||||
])
|
||||
const row = (await screen.findByText('(no subject)')).closest('tr')!
|
||||
expect(within(row).getByText('2030-01-02 03:04 UTC')).toBeInTheDocument()
|
||||
const bar = within(row).getByRole('progressbar')
|
||||
expect(bar).toHaveAttribute('aria-valuenow', '6')
|
||||
expect(bar).toHaveAttribute('aria-valuemax', '10')
|
||||
expect(within(row).getByText('6 of 10')).toBeInTheDocument()
|
||||
const cells = within(row).getAllByRole('cell').map((c) => c.textContent)
|
||||
expect(cells.slice(3)).toEqual(['10', '2', '1', '1'])
|
||||
const headers = screen.getAllByRole('columnheader').map((h) => h.textContent)
|
||||
expect(headers).toEqual(['Subject', 'Date', 'Sent', 'Recipients', 'Pending', 'Failed', 'Dropped'])
|
||||
const done = screen.getByText('Issue 1').closest('tr')!
|
||||
expect(within(done).getByRole('progressbar')).toHaveAttribute('aria-valuenow', '4')
|
||||
const rows = screen.getAllByRole('row').slice(1).map((r) => r.textContent ?? '')
|
||||
expect(rows[0]).toContain('(no subject)') // the order of the server: newest first
|
||||
})
|
||||
|
||||
it('shows a post nobody received without a progress bar', async () => {
|
||||
await setup([post(1, { recipients: 0, sent: 0 })])
|
||||
const row = (await screen.findByText('Issue 1')).closest('tr')!
|
||||
expect(within(row).queryByRole('progressbar')).not.toBeInTheDocument()
|
||||
expect(within(row).getByText(/no recipients/i)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows subjects as text', async () => {
|
||||
await setup([post(1, { subject: '<img src=x onerror="alert(1)">' })])
|
||||
expect(await screen.findByText('<img src=x onerror="alert(1)">')).toBeInTheDocument()
|
||||
expect(document.querySelector('img[src="x"]')).toBeNull()
|
||||
})
|
||||
|
||||
it('refreshes every few seconds while a post is being sent', async () => {
|
||||
vi.useFakeTimers({ shouldAdvanceTime: true })
|
||||
const { state } = await setup([post(1, { sent: 1, pending: 3 })])
|
||||
await screen.findByText('1 of 4')
|
||||
state.posts[1] = [post(1)]
|
||||
await act(async () => {
|
||||
await vi.advanceTimersByTimeAsync(6000)
|
||||
})
|
||||
expect(await screen.findByText('4 of 4')).toBeInTheDocument()
|
||||
// Everything is sent: no more polling.
|
||||
const before = postCalls(state.calls)
|
||||
await act(async () => {
|
||||
await vi.advanceTimersByTimeAsync(12000)
|
||||
})
|
||||
expect(postCalls(state.calls)).toBe(before)
|
||||
})
|
||||
|
||||
it('does not refresh when nothing is pending', async () => {
|
||||
vi.useFakeTimers({ shouldAdvanceTime: true })
|
||||
const { state } = await setup([post(1)])
|
||||
await screen.findByText('4 of 4')
|
||||
await act(async () => {
|
||||
await vi.advanceTimersByTimeAsync(12000)
|
||||
})
|
||||
expect(postCalls(state.calls)).toBe(1)
|
||||
})
|
||||
|
||||
it('shows a loading error', async () => {
|
||||
installFakeApi(newState({ lists: [aList({ id: 1 })], fail: { 'GET /lists/1/posts': { status: 500, error: 'database is locked' } } }))
|
||||
renderApp('/lists/1/sent', { token: 'good' })
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent('database is locked')
|
||||
})
|
||||
})
|
||||
81
admin/src/tabs/SentTab.tsx
Normal file
81
admin/src/tabs/SentTab.tsx
Normal file
|
|
@ -0,0 +1,81 @@
|
|||
import { useQuery } from '@tanstack/react-query'
|
||||
import { useOutletContext } from 'react-router'
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
|
||||
import { api, type List, type Post } from '@/lib/api'
|
||||
import { formatDate } from '@/lib/format'
|
||||
|
||||
/** How often the tab reloads by itself while a post is still being sent. */
|
||||
export const REFRESH_MS = 5000
|
||||
|
||||
export function SentTab() {
|
||||
const list = useOutletContext<List>()
|
||||
const posts = useQuery({
|
||||
queryKey: ['posts', list.id],
|
||||
queryFn: () => api.posts.list(list.id),
|
||||
refetchInterval: (q) => (q.state.data?.some((p) => p.pending > 0) ? REFRESH_MS : false),
|
||||
})
|
||||
const items = posts.data ?? []
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<h2 className="text-lg font-semibold">Sent posts</h2>
|
||||
{posts.isPending && <p className="text-muted-foreground">Loading…</p>}
|
||||
{posts.isError && <p role="alert" className="text-destructive">{posts.error.message}</p>}
|
||||
{posts.data && items.length === 0 && (
|
||||
<p className="text-muted-foreground">Nothing has been sent to this list yet.</p>
|
||||
)}
|
||||
{items.length > 0 && (
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Subject</TableHead>
|
||||
<TableHead>Date</TableHead>
|
||||
<TableHead>Sent</TableHead>
|
||||
<TableHead>Recipients</TableHead>
|
||||
<TableHead>Pending</TableHead>
|
||||
<TableHead>Failed</TableHead>
|
||||
<TableHead>Dropped</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{items.map((p) => (
|
||||
<TableRow key={p.id}>
|
||||
<TableCell className="max-w-xs whitespace-normal font-medium">{p.subject || '(no subject)'}</TableCell>
|
||||
<TableCell>{formatDate(p.created_at)}</TableCell>
|
||||
<TableCell>
|
||||
<Progress post={p} />
|
||||
</TableCell>
|
||||
<TableCell>{p.recipients}</TableCell>
|
||||
<TableCell>{p.pending}</TableCell>
|
||||
<TableCell>{p.failed}</TableCell>
|
||||
<TableCell>{p.dropped}</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function Progress({ post }: { post: Post }) {
|
||||
if (post.recipients === 0) return <span className="text-muted-foreground">No recipients</span>
|
||||
const pct = Math.round((100 * post.sent) / post.recipients)
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<div
|
||||
role="progressbar"
|
||||
aria-label={`Sent to ${post.sent} of ${post.recipients}`}
|
||||
aria-valuemin={0}
|
||||
aria-valuemax={post.recipients}
|
||||
aria-valuenow={post.sent}
|
||||
className="h-2 w-24 overflow-hidden rounded-full bg-muted"
|
||||
>
|
||||
<div className="h-full bg-primary" style={{ width: `${pct}%` }} />
|
||||
</div>
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{post.sent} of {post.recipients}
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
24
admin/src/tabs/SettingsTab.test.tsx
Normal file
24
admin/src/tabs/SettingsTab.test.tsx
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
import { screen, waitFor } from '@testing-library/react'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { aList, installFakeApi, newState } from '@/test/fakeApi'
|
||||
import { renderApp } from '@/test/render'
|
||||
|
||||
describe('settings tab: newsletter', () => {
|
||||
it('shows the publishers policy', async () => {
|
||||
installFakeApi(newState({ lists: [aList({ id: 1, post_policy: 'publishers' })] }))
|
||||
renderApp('/lists/1', { token: 'good' })
|
||||
await screen.findByLabelText(/^title$/i)
|
||||
expect(screen.getByRole('combobox', { name: /posting/i })).toHaveTextContent('Publishers only (newsletter)')
|
||||
})
|
||||
|
||||
it('turns a list into a newsletter', async () => {
|
||||
const state = installFakeApi(newState({ lists: [aList({ id: 1 })] }))
|
||||
const { user } = renderApp('/lists/1', { token: 'good' })
|
||||
await screen.findByLabelText(/^title$/i)
|
||||
await user.click(screen.getByRole('combobox', { name: /posting/i }))
|
||||
await user.click(await screen.findByRole('option', { name: 'Publishers only (newsletter)' }))
|
||||
await user.click(screen.getByRole('button', { name: /save changes/i }))
|
||||
await waitFor(() => expect(state.lists[0].post_policy).toBe('publishers'))
|
||||
expect(state.lists[0].join_policy).toBe('open')
|
||||
})
|
||||
})
|
||||
|
|
@ -21,6 +21,7 @@ import { api, type ArchivePolicy, type JoinPolicy, type List, type PostPolicy }
|
|||
const postOptions: Option<PostPolicy>[] = [
|
||||
{ value: 'members', label: 'Members only' },
|
||||
{ value: 'moderated', label: 'Moderated (hold every post)' },
|
||||
{ value: 'publishers', label: 'Publishers only (newsletter)' },
|
||||
]
|
||||
const joinOptions: Option<JoinPolicy>[] = [
|
||||
{ value: 'open', label: 'Open (confirmed by email)' },
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
// An in-memory stand-in for the Parsimony API, used by component tests.
|
||||
import { vi } from 'vitest'
|
||||
import type { Held, List, Member, Message, QueueItem } from '@/lib/api'
|
||||
import type { Held, List, Member, Message, Post, QueueItem } from '@/lib/api'
|
||||
|
||||
export interface FakeState {
|
||||
token: string
|
||||
|
|
@ -9,6 +9,7 @@ export interface FakeState {
|
|||
held: Record<number, Held[]>
|
||||
archive: Record<number, Message[]>
|
||||
queue: QueueItem[]
|
||||
posts: Record<number, Post[]>
|
||||
/** Like the server, the queue listing is capped. */
|
||||
queueLimit: number
|
||||
/** Content types seen on archive imports. */
|
||||
|
|
@ -23,7 +24,7 @@ export interface FakeState {
|
|||
}
|
||||
|
||||
export function newState(overrides: Partial<FakeState> = {}): FakeState {
|
||||
return { token: 'good', lists: [], members: {}, held: {}, archive: {}, queue: [], queueLimit: 100, importTypes: [], nextId: 100, calls: [], fail: {}, ...overrides }
|
||||
return { token: 'good', lists: [], members: {}, held: {}, archive: {}, queue: [], posts: {}, queueLimit: 100, importTypes: [], nextId: 100, calls: [], fail: {}, ...overrides }
|
||||
}
|
||||
|
||||
export function aList(over: Partial<List> = {}): List {
|
||||
|
|
@ -112,11 +113,20 @@ export function installFakeApi(state: FakeState) {
|
|||
if (method === 'GET') return json(200, ms)
|
||||
if (method === 'POST') {
|
||||
if (!/^[^@\s]+@[^@\s]+$/.test(body.address ?? '')) return err(400, 'a valid email address is required')
|
||||
const mem: Member = { address: body.address.toLowerCase(), display_name: body.display_name ?? '', disabled: false, bounce_count: 0 }
|
||||
const address = body.address.toLowerCase()
|
||||
const publisher = body.publisher ?? ms.find((x) => x.address === address)?.publisher ?? false
|
||||
const mem: Member = { address, display_name: body.display_name ?? '', disabled: false, bounce_count: 0, publisher }
|
||||
state.members[id] = [...ms.filter((x) => x.address !== mem.address), mem]
|
||||
return json(201, mem)
|
||||
}
|
||||
}
|
||||
if ((m = path.match(/^\/lists\/(\d+)\/members\/(.+)$/)) && method === 'PATCH') {
|
||||
const mem = (state.members[Number(m[1])] ?? []).find((x) => x.address === decodeURIComponent(m![2]).toLowerCase())
|
||||
if (!mem) return err(404, 'not found')
|
||||
if (typeof body.publisher !== 'boolean') return err(400, 'publisher (true or false) is required')
|
||||
mem.publisher = body.publisher
|
||||
return json(204)
|
||||
}
|
||||
if ((m = path.match(/^\/lists\/(\d+)\/members\/(.+)$/)) && method === 'DELETE') {
|
||||
const id = Number(m[1])
|
||||
const addr = decodeURIComponent(m[2])
|
||||
|
|
@ -125,6 +135,11 @@ export function installFakeApi(state: FakeState) {
|
|||
state.members[id] = before.filter((x) => x.address !== addr)
|
||||
return json(204)
|
||||
}
|
||||
if ((m = path.match(/^\/lists\/(\d+)\/posts$/)) && method === 'GET') {
|
||||
const id = Number(m[1])
|
||||
if (!state.lists.some((l) => l.id === id)) return err(404, 'not found')
|
||||
return json(200, state.posts[id] ?? [])
|
||||
}
|
||||
if ((m = path.match(/^\/lists\/(\d+)\/held$/)) && method === 'GET') return json(200, state.held[Number(m[1])] ?? [])
|
||||
if ((m = path.match(/^\/held\/(\d+)(\/approve)?$/))) {
|
||||
const id = Number(m[1])
|
||||
|
|
|
|||
|
|
@ -20,7 +20,7 @@ components:
|
|||
domain: {type: string}
|
||||
title: {type: string}
|
||||
address: {type: string}
|
||||
post_policy: {type: string, enum: [members, moderated]}
|
||||
post_policy: {type: string, enum: [members, moderated, publishers], description: "publishers: a newsletter, only members flagged publisher may post"}
|
||||
join_policy: {type: string, enum: [open, closed]}
|
||||
archive_policy: {type: string, enum: [public, private, off], description: "public: browsable on the web; private: API only (default); off: not stored"}
|
||||
Message:
|
||||
|
|
@ -52,6 +52,7 @@ components:
|
|||
display_name: {type: string}
|
||||
disabled: {type: boolean, description: Disabled after 3 hard bounces within 30 days; re-adding the member re-enables it}
|
||||
bounce_count: {type: integer, description: Recent hard bounces (restarts at 1 when the last one is older than 30 days)}
|
||||
publisher: {type: boolean, description: May post when the list's post_policy is publishers}
|
||||
Held:
|
||||
type: object
|
||||
properties:
|
||||
|
|
@ -142,7 +143,7 @@ paths:
|
|||
type: object
|
||||
properties:
|
||||
title: {type: string, minLength: 1, maxLength: 200, description: A single line without control characters.}
|
||||
post_policy: {type: string, enum: [members, moderated]}
|
||||
post_policy: {type: string, enum: [members, moderated, publishers], description: "publishers: a newsletter, only members flagged publisher may post"}
|
||||
join_policy: {type: string, enum: [open, closed]}
|
||||
archive_policy: {type: string, enum: [public, private, off]}
|
||||
responses:
|
||||
|
|
@ -182,6 +183,7 @@ paths:
|
|||
properties:
|
||||
address: {type: string}
|
||||
display_name: {type: string}
|
||||
publisher: {type: boolean, description: "Absent: an existing member keeps its flag (a new one is not a publisher); true or false: set it"}
|
||||
responses:
|
||||
'201':
|
||||
description: Created
|
||||
|
|
@ -199,6 +201,21 @@ paths:
|
|||
responses:
|
||||
'204': {description: Removed}
|
||||
'404': {$ref: '#/components/responses/Error'}
|
||||
patch:
|
||||
summary: Make a member a publisher or a plain subscriber
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
required: [publisher]
|
||||
properties:
|
||||
publisher: {type: boolean}
|
||||
responses:
|
||||
'204': {description: Updated}
|
||||
'400': {$ref: '#/components/responses/Error'}
|
||||
'404': {$ref: '#/components/responses/Error'}
|
||||
/lists/{id}/held:
|
||||
parameters:
|
||||
- {name: id, in: path, required: true, schema: {type: integer}}
|
||||
|
|
@ -287,6 +304,7 @@ paths:
|
|||
- {name: id, in: path, required: true, schema: {type: integer}}
|
||||
delete:
|
||||
summary: Discard a queued delivery
|
||||
description: A waiting delivery of a post counts as dropped in the post's counters; a failed one stays counted as failed.
|
||||
responses:
|
||||
'204': {description: Discarded}
|
||||
'404': {$ref: '#/components/responses/Error'}
|
||||
|
|
@ -319,3 +337,34 @@ paths:
|
|||
errors: {type: array, items: {type: string}, description: The first 20 failures}
|
||||
'400': {$ref: '#/components/responses/Error'}
|
||||
'404': {$ref: '#/components/responses/Error'}
|
||||
/lists/{id}/posts:
|
||||
parameters:
|
||||
- {name: id, in: path, required: true, schema: {type: integer}}
|
||||
get:
|
||||
summary: Posts queued to the list with their delivery counters, newest first
|
||||
description: >
|
||||
One entry per post queued to the list (delivered or approved), kept for 400 days. Confirmation mail is not a post.
|
||||
Bodies are never read.
|
||||
parameters:
|
||||
- {name: limit, in: query, schema: {type: integer, default: 50, maximum: 200}, description: 0 means the default; more than 200 gives 200}
|
||||
responses:
|
||||
'200':
|
||||
description: OK
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: array
|
||||
items:
|
||||
type: object
|
||||
properties:
|
||||
id: {type: integer}
|
||||
message_id: {type: string, description: The Message-ID header, at most 200 characters; empty when there was none}
|
||||
subject: {type: string, description: Decoded, at most 200 characters, control characters removed}
|
||||
created_at: {type: string, format: date-time}
|
||||
recipients: {type: integer, description: Deliveries queued (members at the time of the post)}
|
||||
sent: {type: integer, description: Accepted by the relay}
|
||||
failed: {type: integer, description: Given up for good (refused by the relay, or still failing after 3 days)}
|
||||
dropped: {type: integer, description: The mailbox does not exist, or the delivery was discarded}
|
||||
pending: {type: integer, description: "Still in the queue: recipients - sent - failed - dropped"}
|
||||
'400': {$ref: '#/components/responses/Error'}
|
||||
'404': {$ref: '#/components/responses/Error'}
|
||||
|
|
|
|||
|
|
@ -68,6 +68,7 @@ func (s *server) routes() []route {
|
|||
{"GET /api/v1/lists/{id}/members", s.auth(s.listMembers)},
|
||||
{"POST /api/v1/lists/{id}/members", s.auth(s.addMember)},
|
||||
{"DELETE /api/v1/lists/{id}/members/{address}", s.auth(s.removeMember)},
|
||||
{"PATCH /api/v1/lists/{id}/members/{address}", s.auth(s.updateMember)},
|
||||
{"GET /api/v1/lists/{id}/archive", s.auth(s.listArchive)},
|
||||
{"POST /api/v1/lists/{id}/archive/import", s.auth(s.importArchive)},
|
||||
{"GET /api/v1/archive/{id}", s.auth(s.getArchived)},
|
||||
|
|
@ -75,6 +76,7 @@ func (s *server) routes() []route {
|
|||
{"GET /api/v1/queue", s.auth(s.getQueue)},
|
||||
{"DELETE /api/v1/queue/{id}", s.auth(s.discardQueued)},
|
||||
{"GET /api/v1/lists/{id}/held", s.auth(s.listHeld)},
|
||||
{"GET /api/v1/lists/{id}/posts", s.auth(s.listPosts)},
|
||||
{"POST /api/v1/held/{id}/approve", s.auth(s.approveHeld)},
|
||||
{"DELETE /api/v1/held/{id}", s.auth(s.discardHeld)},
|
||||
}
|
||||
|
|
@ -124,6 +126,7 @@ type memberDTO struct {
|
|||
DisplayName string `json:"display_name"`
|
||||
Disabled bool `json:"disabled"`
|
||||
BounceCount int `json:"bounce_count"`
|
||||
Publisher bool `json:"publisher"`
|
||||
}
|
||||
|
||||
// Helpers.
|
||||
|
|
@ -322,10 +325,10 @@ func (s *server) updateList(w http.ResponseWriter, r *http.Request) {
|
|||
l.ArchivePolicy = *in.ArchivePolicy
|
||||
}
|
||||
// Validate before writing anything.
|
||||
if (l.PostPolicy != store.PostMembers && l.PostPolicy != store.PostModerated) ||
|
||||
if (l.PostPolicy != store.PostMembers && l.PostPolicy != store.PostModerated && l.PostPolicy != store.PostPublishers) ||
|
||||
(l.JoinPolicy != store.JoinOpen && l.JoinPolicy != store.JoinClosed) ||
|
||||
(l.ArchivePolicy != store.ArchivePublic && l.ArchivePolicy != store.ArchivePrivate && l.ArchivePolicy != store.ArchiveOff) {
|
||||
writeError(w, http.StatusBadRequest, "post_policy must be members or moderated; join_policy open or closed; archive_policy public, private or off")
|
||||
writeError(w, http.StatusBadRequest, "post_policy must be members, moderated or publishers; join_policy open or closed; archive_policy public, private or off")
|
||||
return
|
||||
}
|
||||
if err := s.store.UpdateList(id, l.Title); err != nil {
|
||||
|
|
@ -369,7 +372,7 @@ func (s *server) listMembers(w http.ResponseWriter, r *http.Request) {
|
|||
}
|
||||
out := make([]memberDTO, 0, len(ms))
|
||||
for _, m := range ms {
|
||||
out = append(out, memberDTO{Address: m.Address, DisplayName: m.DisplayName, Disabled: m.Disabled, BounceCount: m.BounceCount})
|
||||
out = append(out, memberDTO{Address: m.Address, DisplayName: m.DisplayName, Disabled: m.Disabled, BounceCount: m.BounceCount, Publisher: m.Publisher})
|
||||
}
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
}
|
||||
|
|
@ -379,7 +382,11 @@ func (s *server) addMember(w http.ResponseWriter, r *http.Request) {
|
|||
if !ok {
|
||||
return
|
||||
}
|
||||
var in memberDTO
|
||||
// publisher is optional: absent leaves an existing member's flag as it is.
|
||||
var in struct {
|
||||
memberDTO
|
||||
Publisher *bool `json:"publisher"`
|
||||
}
|
||||
if !decodeBody(w, r, &in) {
|
||||
return
|
||||
}
|
||||
|
|
@ -400,7 +407,41 @@ func (s *server) addMember(w http.ResponseWriter, r *http.Request) {
|
|||
storeError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, memberDTO{Address: strings.ToLower(a.Address), DisplayName: in.DisplayName})
|
||||
if in.Publisher != nil {
|
||||
if err := s.store.SetPublisher(id, a.Address, *in.Publisher); err != nil {
|
||||
storeError(w, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
pub, err := s.store.IsPublisher(id, a.Address)
|
||||
if err != nil {
|
||||
storeError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, memberDTO{Address: strings.ToLower(a.Address), DisplayName: in.DisplayName, Publisher: pub})
|
||||
}
|
||||
|
||||
// updateMember changes the publisher flag of a member.
|
||||
func (s *server) updateMember(w http.ResponseWriter, r *http.Request) {
|
||||
id, ok := listID(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var in struct {
|
||||
Publisher *bool `json:"publisher"`
|
||||
}
|
||||
if !decodeBody(w, r, &in) {
|
||||
return
|
||||
}
|
||||
if in.Publisher == nil {
|
||||
writeError(w, http.StatusBadRequest, "publisher (true or false) is required")
|
||||
return
|
||||
}
|
||||
if err := s.store.SetPublisher(id, r.PathValue("address"), *in.Publisher); err != nil {
|
||||
storeError(w, err)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (s *server) removeMember(w http.ResponseWriter, r *http.Request) {
|
||||
|
|
@ -627,7 +668,7 @@ func (s *server) discardQueued(w http.ResponseWriter, r *http.Request) {
|
|||
if !ok {
|
||||
return
|
||||
}
|
||||
if err := s.store.CompleteOutbox(id); err != nil {
|
||||
if err := s.store.DropOutbox(id); err != nil {
|
||||
storeError(w, err)
|
||||
return
|
||||
}
|
||||
|
|
@ -661,3 +702,45 @@ func (s *server) importArchive(w http.ResponseWriter, r *http.Request) {
|
|||
}
|
||||
writeJSON(w, http.StatusOK, sum)
|
||||
}
|
||||
|
||||
// Handlers: posts.
|
||||
|
||||
type postDTO struct {
|
||||
ID int64 `json:"id"`
|
||||
MessageID string `json:"message_id"`
|
||||
Subject string `json:"subject"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
Recipients int `json:"recipients"`
|
||||
Sent int `json:"sent"`
|
||||
Failed int `json:"failed"`
|
||||
Dropped int `json:"dropped"`
|
||||
Pending int `json:"pending"`
|
||||
}
|
||||
|
||||
// listPosts returns the posts queued to a list with their delivery counters, newest first.
|
||||
func (s *server) listPosts(w http.ResponseWriter, r *http.Request) {
|
||||
id, ok := listID(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
limit, ok := intParam(r, "limit", 0) // 0: the store's default
|
||||
if !ok {
|
||||
writeError(w, http.StatusBadRequest, "limit must be a non-negative integer")
|
||||
return
|
||||
}
|
||||
if _, err := s.store.GetList(id); err != nil {
|
||||
storeError(w, err)
|
||||
return
|
||||
}
|
||||
ps, err := s.store.ListPosts(id, limit)
|
||||
if err != nil {
|
||||
storeError(w, err)
|
||||
return
|
||||
}
|
||||
out := make([]postDTO, 0, len(ps))
|
||||
for _, p := range ps {
|
||||
out = append(out, postDTO{ID: p.ID, MessageID: p.MessageID, Subject: p.Subject, CreatedAt: p.CreatedAt,
|
||||
Recipients: p.Recipients, Sent: p.Sent, Failed: p.Failed, Dropped: p.Dropped, Pending: p.Pending})
|
||||
}
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
}
|
||||
|
|
|
|||
103
internal/api/posts_test.go
Normal file
103
internal/api/posts_test.go
Normal file
|
|
@ -0,0 +1,103 @@
|
|||
package api
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"codeberg.org/squidd/parsimony/internal/store"
|
||||
)
|
||||
|
||||
type postJSON struct {
|
||||
ID int64 `json:"id"`
|
||||
MessageID string `json:"message_id"`
|
||||
Subject string `json:"subject"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
Recipients int `json:"recipients"`
|
||||
Sent int `json:"sent"`
|
||||
Failed int `json:"failed"`
|
||||
Dropped int `json:"dropped"`
|
||||
Pending int `json:"pending"`
|
||||
}
|
||||
|
||||
func TestListPosts(t *testing.T) {
|
||||
h, s := queueServer(t)
|
||||
now := time.Unix(1_700_000_000, 0)
|
||||
s.Now = func() time.Time { return now }
|
||||
l, _ := s.CreateList("dev", "example.org", "Dev")
|
||||
rcpts := []store.NewOutbound{{From: "b@x.org", Rcpt: "a@x.com"}, {From: "b@x.org", Rcpt: "b@x.com"}, {From: "b@x.org", Rcpt: "c@x.com"}}
|
||||
s.EnqueuePost(l.ID, "mid:<1@x>", []byte("Message-ID: <1@x>\r\nSubject: first\r\n\r\nsecret body"), rcpts)
|
||||
now = now.Add(time.Minute)
|
||||
s.EnqueuePost(l.ID, "mid:<2@x>", []byte("Message-ID: <2@x>\r\nSubject: second\r\n\r\nsecret body"), rcpts[:1])
|
||||
due, _ := s.DueOutbox(10)
|
||||
s.CompleteOutbox(due[0].ID)
|
||||
s.FailOutbox(due[1].ID, "no")
|
||||
|
||||
rec := do(t, h, "GET", fmt.Sprintf("/api/v1/lists/%d/posts", l.ID), "", true)
|
||||
expect(t, rec, 200)
|
||||
var ps []postJSON
|
||||
decode(t, rec, &ps)
|
||||
if len(ps) != 2 || ps[0].Subject != "second" || ps[1].Subject != "first" {
|
||||
t.Fatalf("newest first: %+v", ps)
|
||||
}
|
||||
p := ps[1]
|
||||
if p.ID == 0 || p.MessageID != "<1@x>" || !p.CreatedAt.Equal(now.Add(-time.Minute)) || p.Recipients != 3 ||
|
||||
p.Sent != 1 || p.Failed != 1 || p.Dropped != 0 || p.Pending != 1 {
|
||||
t.Fatalf("post: %+v", p)
|
||||
}
|
||||
if strings.Contains(rec.Body.String(), "secret body") {
|
||||
t.Fatal("bodies are never listed")
|
||||
}
|
||||
|
||||
decode(t, do(t, h, "GET", fmt.Sprintf("/api/v1/lists/%d/posts?limit=1", l.ID), "", true), &ps)
|
||||
if len(ps) != 1 || ps[0].Subject != "second" {
|
||||
t.Fatalf("limit=1: %+v", ps)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListPostsEmptyIsAnArray(t *testing.T) {
|
||||
h, s := queueServer(t)
|
||||
l, _ := s.CreateList("dev", "example.org", "Dev")
|
||||
rec := do(t, h, "GET", fmt.Sprintf("/api/v1/lists/%d/posts", l.ID), "", true)
|
||||
expect(t, rec, 200)
|
||||
if strings.TrimSpace(rec.Body.String()) != "[]" {
|
||||
t.Fatalf("body %q", rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestListPostsLimit(t *testing.T) {
|
||||
h, s := queueServer(t)
|
||||
l, _ := s.CreateList("dev", "example.org", "Dev")
|
||||
for i := 0; i < 60; i++ {
|
||||
s.EnqueuePost(l.ID, fmt.Sprintf("mid:%d", i), []byte("Subject: x\r\n\r\n"), nil)
|
||||
}
|
||||
path := fmt.Sprintf("/api/v1/lists/%d/posts", l.ID)
|
||||
var ps []postJSON
|
||||
decode(t, do(t, h, "GET", path, "", true), &ps)
|
||||
if len(ps) != 50 {
|
||||
t.Fatalf("default 50: %d", len(ps))
|
||||
}
|
||||
for _, bad := range []string{"-1", "x", "1.5"} {
|
||||
expect(t, do(t, h, "GET", path+"?limit="+bad, "", true), 400)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListPostsUnknownListAndAuth(t *testing.T) {
|
||||
h, _ := queueServer(t)
|
||||
expect(t, do(t, h, "GET", "/api/v1/lists/99/posts", "", true), 404)
|
||||
expect(t, do(t, h, "GET", "/api/v1/lists/abc/posts", "", true), 404)
|
||||
expect(t, do(t, h, "GET", "/api/v1/lists/99/posts", "", false), 401)
|
||||
}
|
||||
|
||||
func TestDiscardingADeliveryOfAPostCountsAsDropped(t *testing.T) {
|
||||
h, s := queueServer(t)
|
||||
l, _ := s.CreateList("dev", "example.org", "Dev")
|
||||
s.EnqueuePost(l.ID, "mid:<1@x>", []byte("Subject: x\r\n\r\n"), []store.NewOutbound{{From: "b@x.org", Rcpt: "a@x.com"}})
|
||||
due, _ := s.DueOutbox(10)
|
||||
expect(t, do(t, h, "DELETE", fmt.Sprintf("/api/v1/queue/%d", due[0].ID), "", true), 204)
|
||||
ps, _ := s.ListPosts(l.ID, 0)
|
||||
if len(ps) != 1 || ps[0].Dropped != 1 || ps[0].Sent != 0 || ps[0].Pending != 0 {
|
||||
t.Fatalf("posts: %+v", ps)
|
||||
}
|
||||
}
|
||||
112
internal/api/publisher_test.go
Normal file
112
internal/api/publisher_test.go
Normal file
|
|
@ -0,0 +1,112 @@
|
|||
package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type publisherJSON struct {
|
||||
Address string `json:"address"`
|
||||
Publisher bool `json:"publisher"`
|
||||
}
|
||||
|
||||
// publishers returns the publisher flag of every member of list 1, by address.
|
||||
func publishers(t *testing.T, h http.Handler) map[string]bool {
|
||||
t.Helper()
|
||||
rec := do(t, h, "GET", "/api/v1/lists/1/members", "", true)
|
||||
expect(t, rec, 200)
|
||||
var ms []publisherJSON
|
||||
decode(t, rec, &ms)
|
||||
out := map[string]bool{}
|
||||
for _, m := range ms {
|
||||
out[m.Address] = m.Publisher
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func TestAddMemberWithThePublisherFlag(t *testing.T) {
|
||||
h := newServer(t)
|
||||
createList(t, h)
|
||||
rec := do(t, h, "POST", "/api/v1/lists/1/members", `{"address":"a@x.com","publisher":true}`, true)
|
||||
expect(t, rec, 201)
|
||||
var m publisherJSON
|
||||
decode(t, rec, &m)
|
||||
if !m.Publisher {
|
||||
t.Fatalf("created: %+v", m)
|
||||
}
|
||||
expect(t, do(t, h, "POST", "/api/v1/lists/1/members", `{"address":"b@x.com"}`, true), 201)
|
||||
if got := publishers(t, h); !got["a@x.com"] || got["b@x.com"] {
|
||||
t.Fatalf("publishers: %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAddMemberLeavesThePublisherFlagAloneWhenAbsent(t *testing.T) {
|
||||
h := newServer(t)
|
||||
createList(t, h)
|
||||
expect(t, do(t, h, "POST", "/api/v1/lists/1/members", `{"address":"a@x.com","publisher":true}`, true), 201)
|
||||
rec := do(t, h, "POST", "/api/v1/lists/1/members", `{"address":"a@x.com","display_name":"A"}`, true)
|
||||
expect(t, rec, 201)
|
||||
var m publisherJSON
|
||||
decode(t, rec, &m)
|
||||
if !m.Publisher || !publishers(t, h)["a@x.com"] {
|
||||
t.Fatalf("re-adding keeps the flag: %+v %v", m, publishers(t, h))
|
||||
}
|
||||
// An explicit false demotes an existing member.
|
||||
rec = do(t, h, "POST", "/api/v1/lists/1/members", `{"address":"a@x.com","publisher":false}`, true)
|
||||
expect(t, rec, 201)
|
||||
decode(t, rec, &m)
|
||||
if m.Publisher || publishers(t, h)["a@x.com"] {
|
||||
t.Fatalf("demoted: %+v %v", m, publishers(t, h))
|
||||
}
|
||||
}
|
||||
|
||||
func TestPatchMemberSetsThePublisherFlag(t *testing.T) {
|
||||
h := newServer(t)
|
||||
createList(t, h)
|
||||
expect(t, do(t, h, "POST", "/api/v1/lists/1/members", `{"address":"a@x.com"}`, true), 201)
|
||||
expect(t, do(t, h, "PATCH", "/api/v1/lists/1/members/A%40X.com", `{"publisher":true}`, true), 204)
|
||||
if !publishers(t, h)["a@x.com"] {
|
||||
t.Fatal("promoted")
|
||||
}
|
||||
expect(t, do(t, h, "PATCH", "/api/v1/lists/1/members/a%40x.com", `{"publisher":false}`, true), 204)
|
||||
if publishers(t, h)["a@x.com"] {
|
||||
t.Fatal("demoted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPatchMemberErrors(t *testing.T) {
|
||||
h := newServer(t)
|
||||
createList(t, h)
|
||||
expect(t, do(t, h, "POST", "/api/v1/lists/1/members", `{"address":"a@x.com"}`, true), 201)
|
||||
expect(t, do(t, h, "PATCH", "/api/v1/lists/1/members/b%40x.com", `{"publisher":true}`, true), 404)
|
||||
expect(t, do(t, h, "PATCH", "/api/v1/lists/99/members/a%40x.com", `{"publisher":true}`, true), 404)
|
||||
rec := do(t, h, "PATCH", "/api/v1/lists/1/members/a%40x.com", `{}`, true)
|
||||
expect(t, rec, 400)
|
||||
if !strings.Contains(rec.Body.String(), "publisher") {
|
||||
t.Fatalf("the error names the field: %s", rec.Body.String())
|
||||
}
|
||||
expect(t, do(t, h, "PATCH", "/api/v1/lists/1/members/a%40x.com", `{"publisher":"yes"}`, true), 400)
|
||||
expect(t, do(t, h, "PATCH", "/api/v1/lists/1/members/a%40x.com", `{"publisher":true,"x":1}`, true), 400)
|
||||
expect(t, do(t, h, "PATCH", "/api/v1/lists/1/members/a%40x.com", `{"publisher":true}`, false), 401)
|
||||
if publishers(t, h)["a@x.com"] {
|
||||
t.Fatal("nothing changed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestThePublishersPostPolicyViaAPI(t *testing.T) {
|
||||
h := newServer(t)
|
||||
createList(t, h)
|
||||
rec := do(t, h, "PATCH", "/api/v1/lists/1", `{"post_policy":"publishers"}`, true)
|
||||
expect(t, rec, 200)
|
||||
var l listJSON
|
||||
decode(t, rec, &l)
|
||||
if l.PostPolicy != "publishers" {
|
||||
t.Fatalf("patched: %+v", l)
|
||||
}
|
||||
rec = do(t, h, "PATCH", "/api/v1/lists/1", `{"post_policy":"bogus"}`, true)
|
||||
expect(t, rec, 400)
|
||||
if !strings.Contains(rec.Body.String(), "members, moderated or publishers") {
|
||||
t.Fatalf("the message lists the policies: %s", rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
|
@ -229,6 +229,7 @@ func Start(cfg config.Config, apiToken string) (*App, error) {
|
|||
Username: cfg.Relay.Username, Password: relayPassword, Helo: heloName(cfg.Relay.Helo),
|
||||
},
|
||||
Concurrency: cfg.Relay.Concurrency,
|
||||
Rate: float64(cfg.Relay.RatePerSecond),
|
||||
Sign: sign,
|
||||
}
|
||||
rt.OnEnqueue = worker.Wake
|
||||
|
|
|
|||
|
|
@ -1310,3 +1310,52 @@ func TestHTTPServersCarryTheTimeouts(t *testing.T) {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheRelayRateReachesTheWorker(t *testing.T) {
|
||||
relayAddr, relay := startSink(t)
|
||||
cfg := testConfig(t, relayAddr)
|
||||
cfg.Relay.RatePerSecond = 20 // 50 ms between two sends
|
||||
a, err := Start(cfg, "tok")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { a.Close() })
|
||||
call(t, a, "POST", "/api/v1/lists", `{"name":"dev","domain":"example.org"}`, "tok")
|
||||
const members = 8
|
||||
for i := 0; i < members; i++ {
|
||||
call(t, a, "POST", "/api/v1/lists/1/members", fmt.Sprintf(`{"address":"m%d@example.com"}`, i), "tok")
|
||||
}
|
||||
start := time.Now()
|
||||
msg := "From: M0 <m0@example.com>\r\nSubject: paced\r\nMessage-ID: <p1@x>\r\n\r\nbody\r\n"
|
||||
if err := lmtpSend(t, a.LMTPAddr, "m0@example.com", "dev@example.org", msg); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
relay.waitCount(t, members)
|
||||
// 8 sends started 50 ms apart: the last one cannot start before 350 ms.
|
||||
if took := time.Since(start); took < 330*time.Millisecond {
|
||||
t.Fatalf("%d deliveries took %v: the rate did not reach the worker", members, took)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWithoutARateTheRelayIsNotPaced(t *testing.T) {
|
||||
relayAddr, relay := startSink(t)
|
||||
a, err := Start(testConfig(t, relayAddr), "tok")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { a.Close() })
|
||||
call(t, a, "POST", "/api/v1/lists", `{"name":"dev","domain":"example.org"}`, "tok")
|
||||
const members = 8
|
||||
for i := 0; i < members; i++ {
|
||||
call(t, a, "POST", "/api/v1/lists/1/members", fmt.Sprintf(`{"address":"m%d@example.com"}`, i), "tok")
|
||||
}
|
||||
start := time.Now()
|
||||
msg := "From: M0 <m0@example.com>\r\nSubject: free\r\nMessage-ID: <p2@x>\r\n\r\nbody\r\n"
|
||||
if err := lmtpSend(t, a.LMTPAddr, "m0@example.com", "dev@example.org", msg); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
relay.waitCount(t, members)
|
||||
if took := time.Since(start); took > 3*time.Second {
|
||||
t.Fatalf("%d deliveries took %v without a rate", members, took)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -29,15 +29,20 @@ Administration (talks to the REST API):
|
|||
list ls show all lists
|
||||
list add <name@domain> [--title T] create a list
|
||||
list show <list> show one list
|
||||
list set <list> [--title T] [--post members|moderated]
|
||||
list set <list> [--title T] [--post members|moderated|publishers]
|
||||
[--join open|closed] [--archive public|private|off]
|
||||
list rm <list> --yes delete a list with its members and archive
|
||||
|
||||
member ls <list> [--emails] show subscribers
|
||||
member add <list> <email> [--name N] subscribe (or re-enable) an address
|
||||
member ls <list> [--emails] show subscribers and publishers
|
||||
member add <list> <email> [--name N] [--publisher]
|
||||
subscribe (or re-enable) an address;
|
||||
--publisher lets it post to a publishers list,
|
||||
--publisher=false takes that away
|
||||
member set <list> <email> --publisher=true|false
|
||||
make a member a publisher or a plain subscriber
|
||||
member rm <list> <email> unsubscribe an address
|
||||
member import <list> <file|-> subscribe addresses from a file or stdin,
|
||||
one "email[,name]" per line
|
||||
one "email[,name[,publisher]]" per line
|
||||
|
||||
held ls <list> messages waiting for moderation
|
||||
held approve <id> deliver a held message
|
||||
|
|
@ -49,6 +54,8 @@ Administration (talks to the REST API):
|
|||
archive import <list> <file|-> add the messages of an mbox file (Mailman export);
|
||||
safe to repeat, threads are rebuilt
|
||||
|
||||
posts ls <list> [--limit N] posts sent to a list with their delivery counts
|
||||
|
||||
queue ls outbound queue
|
||||
queue rm <id> discard one queued delivery
|
||||
|
||||
|
|
@ -101,10 +108,11 @@ func Run(args []string, io IO, getenv func(string) string) int {
|
|||
|
||||
commands := map[string]map[string]func([]string) int{
|
||||
"list": {"ls": c.listLs, "add": c.listAdd, "show": c.listShow, "set": c.listSet, "rm": c.listRm},
|
||||
"member": {"ls": c.memberLs, "add": c.memberAdd, "rm": c.memberRm, "import": c.memberImport},
|
||||
"member": {"ls": c.memberLs, "add": c.memberAdd, "set": c.memberSet, "rm": c.memberRm, "import": c.memberImport},
|
||||
"held": {"ls": c.heldLs, "approve": c.heldApprove, "discard": c.heldDiscard},
|
||||
"archive": {"ls": c.archiveLs, "show": c.archiveShow, "rm": c.archiveRm, "import": c.archiveImport},
|
||||
"queue": {"ls": c.queueLs, "rm": c.queueRm},
|
||||
"posts": {"ls": c.postsLs},
|
||||
"dkim": {"keygen": c.dkimKeygen, "record": c.dkimRecord, "check": c.dkimCheck},
|
||||
}
|
||||
group, ok := commands[rest[0]]
|
||||
|
|
|
|||
|
|
@ -274,7 +274,7 @@ func TestMembers(t *testing.T) {
|
|||
func TestMemberImport(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
e.ok(t, "list", "add", "dev@example.org")
|
||||
input := "# subscribers exported from Mailman\n\nalice@example.com, Alice Smith\nbob@example.com\n carol@example.com ,Carol \nnot-an-address\ndave@example.com,Dave,extra\n"
|
||||
input := "# subscribers exported from Mailman\n\nalice@example.com, Alice Smith\nbob@example.com\n carol@example.com ,Carol \nnot-an-address\ndave@example.com,Dave,Publisher\n"
|
||||
code, out, errs := e.runEnv(t, map[string]string{"PARSIMONY_API_TOKEN": token, "PARSIMONY_URL": e.srv.URL}, input, "member", "import", "dev@example.org", "-")
|
||||
if code != 1 {
|
||||
t.Fatalf("a failed line must make the exit code non-zero, got %d", code)
|
||||
|
|
|
|||
|
|
@ -179,6 +179,14 @@ type member struct {
|
|||
DisplayName string `json:"display_name"`
|
||||
Disabled bool `json:"disabled"`
|
||||
BounceCount int `json:"bounce_count"`
|
||||
Publisher bool `json:"publisher"`
|
||||
}
|
||||
|
||||
func (m member) role() string {
|
||||
if m.Publisher {
|
||||
return "publisher"
|
||||
}
|
||||
return "subscriber"
|
||||
}
|
||||
|
||||
func (m member) status() string {
|
||||
|
|
@ -228,9 +236,9 @@ func (c *cmd) memberLs(args []string) int {
|
|||
fmt.Fprintln(c.io.Out, "No members yet.")
|
||||
return 0
|
||||
}
|
||||
rows := [][]string{{"ADDRESS", "NAME", "STATUS"}}
|
||||
rows := [][]string{{"ADDRESS", "NAME", "ROLE", "STATUS"}}
|
||||
for _, m := range ms {
|
||||
rows = append(rows, []string{m.Address, m.DisplayName, m.status()})
|
||||
rows = append(rows, []string{m.Address, m.DisplayName, m.role(), m.status()})
|
||||
}
|
||||
c.table(rows)
|
||||
return 0
|
||||
|
|
@ -239,18 +247,19 @@ func (c *cmd) memberLs(args []string) int {
|
|||
func (c *cmd) memberAdd(args []string) int {
|
||||
fs := newFlagSet("member add")
|
||||
name := fs.String("name", "", "")
|
||||
pub := fs.Bool("publisher", false, "")
|
||||
pos, err := parseArgs(fs, args)
|
||||
if err != nil {
|
||||
return c.usageError("%v", err)
|
||||
}
|
||||
if len(pos) != 2 {
|
||||
return c.usageError("usage: parsimony member add <list> <email> [--name NAME]")
|
||||
return c.usageError("usage: parsimony member add <list> <email> [--name NAME] [--publisher]")
|
||||
}
|
||||
l, err := c.resolveList(pos[0])
|
||||
if err != nil {
|
||||
return c.fail(err)
|
||||
}
|
||||
raw, err := c.addMember(l.ID, pos[1], *name)
|
||||
raw, err := c.addMember(l.ID, pos[1], *name, flagBool(fs, "publisher", *pub))
|
||||
if err != nil {
|
||||
return c.fail(err)
|
||||
}
|
||||
|
|
@ -259,16 +268,65 @@ func (c *cmd) memberAdd(args []string) int {
|
|||
}
|
||||
var m member
|
||||
json.Unmarshal(raw, &m)
|
||||
fmt.Fprintf(c.io.Out, "Added %s to %s\n", printable(m.Address), printable(l.Address))
|
||||
as := ""
|
||||
if m.Publisher {
|
||||
as = " as a publisher"
|
||||
}
|
||||
fmt.Fprintf(c.io.Out, "Added %s to %s%s\n", printable(m.Address), printable(l.Address), as)
|
||||
return 0
|
||||
}
|
||||
|
||||
func (c *cmd) addMember(listID int64, address, name string) (json.RawMessage, error) {
|
||||
// flagBool returns &v when the flag was given on the command line, nil otherwise.
|
||||
func flagBool(fs *flag.FlagSet, name string, v bool) *bool {
|
||||
set := false
|
||||
fs.Visit(func(f *flag.Flag) { set = set || f.Name == name })
|
||||
if !set {
|
||||
return nil
|
||||
}
|
||||
return &v
|
||||
}
|
||||
|
||||
// addMember subscribes an address; a nil publisher leaves the flag of an existing member alone.
|
||||
func (c *cmd) addMember(listID int64, address, name string, publisher *bool) (json.RawMessage, error) {
|
||||
cl, err := c.client()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return cl.do("POST", fmt.Sprintf("/lists/%d/members", listID), map[string]string{"address": address, "display_name": name})
|
||||
body := map[string]any{"address": address, "display_name": name}
|
||||
if publisher != nil {
|
||||
body["publisher"] = *publisher
|
||||
}
|
||||
return cl.do("POST", fmt.Sprintf("/lists/%d/members", listID), body)
|
||||
}
|
||||
|
||||
func (c *cmd) memberSet(args []string) int {
|
||||
fs := newFlagSet("member set")
|
||||
pub := fs.Bool("publisher", false, "")
|
||||
pos, err := parseArgs(fs, args)
|
||||
if err != nil {
|
||||
return c.usageError("%v", err)
|
||||
}
|
||||
if len(pos) != 2 {
|
||||
return c.usageError("usage: parsimony member set <list> <email> --publisher=true|false")
|
||||
}
|
||||
publisher := flagBool(fs, "publisher", *pub)
|
||||
if publisher == nil {
|
||||
return c.usageError("nothing to change: give --publisher=true or --publisher=false")
|
||||
}
|
||||
l, err := c.resolveList(pos[0])
|
||||
if err != nil {
|
||||
return c.fail(err)
|
||||
}
|
||||
cl, _ := c.client()
|
||||
path := fmt.Sprintf("/lists/%d/members/%s", l.ID, url.PathEscape(pos[1]))
|
||||
if _, err := cl.do("PATCH", path, map[string]bool{"publisher": *publisher}); err != nil {
|
||||
return c.fail(err)
|
||||
}
|
||||
role := "a subscriber"
|
||||
if *publisher {
|
||||
role = "a publisher"
|
||||
}
|
||||
return c.done(fmt.Sprintf("%s is now %s of %s", strings.ToLower(pos[1]), role, l.Address))
|
||||
}
|
||||
|
||||
func (c *cmd) memberRm(args []string) int {
|
||||
|
|
@ -325,7 +383,20 @@ func (c *cmd) memberImport(args []string) int {
|
|||
if len(parts) > 1 {
|
||||
name = strings.TrimSpace(parts[1])
|
||||
}
|
||||
if _, err := c.addMember(l.ID, address, name); err != nil {
|
||||
// The optional third column is the keyword "publisher"; an empty one is no column.
|
||||
var publisher *bool
|
||||
if len(parts) > 2 {
|
||||
switch kw := strings.TrimSpace(parts[2]); {
|
||||
case strings.EqualFold(kw, "publisher"):
|
||||
yes := true
|
||||
publisher = &yes
|
||||
case kw != "":
|
||||
failed++
|
||||
fmt.Fprintf(c.io.Err, "line %d: %s\n", n, printable(fmt.Sprintf("%s: the third column may only be \"publisher\"", line)))
|
||||
continue
|
||||
}
|
||||
}
|
||||
if _, err := c.addMember(l.ID, address, name, publisher); err != nil {
|
||||
failed++
|
||||
fmt.Fprintf(c.io.Err, "line %d: %s\n", n, printable(fmt.Sprintf("%s: %v", line, err)))
|
||||
continue
|
||||
|
|
@ -683,3 +754,56 @@ func (c *cmd) queueRm(args []string) int {
|
|||
return err
|
||||
}, "Discarded queued delivery %d")
|
||||
}
|
||||
|
||||
// postsLs shows the posts queued to a list, newest first, with how far their delivery got.
|
||||
func (c *cmd) postsLs(args []string) int {
|
||||
fs := newFlagSet("posts ls")
|
||||
limit := fs.Int("limit", 50, "")
|
||||
pos, err := parseArgs(fs, args)
|
||||
if err != nil {
|
||||
return c.usageError("%v", err)
|
||||
}
|
||||
if len(pos) != 1 {
|
||||
return c.usageError("usage: parsimony posts ls <list> [--limit N]")
|
||||
}
|
||||
l, err := c.resolveList(pos[0])
|
||||
if err != nil {
|
||||
return c.fail(err)
|
||||
}
|
||||
cl, _ := c.client()
|
||||
raw, err := cl.do("GET", fmt.Sprintf("/lists/%d/posts?limit=%d", l.ID, *limit), nil)
|
||||
if err != nil {
|
||||
return c.fail(err)
|
||||
}
|
||||
if c.json {
|
||||
return c.printJSON(raw)
|
||||
}
|
||||
var ps []struct {
|
||||
ID int64 `json:"id"`
|
||||
Subject string `json:"subject"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
Recipients int `json:"recipients"`
|
||||
Sent int `json:"sent"`
|
||||
Failed int `json:"failed"`
|
||||
Dropped int `json:"dropped"`
|
||||
Pending int `json:"pending"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &ps); err != nil {
|
||||
return c.fail(err)
|
||||
}
|
||||
if len(ps) == 0 {
|
||||
fmt.Fprintln(c.io.Out, "No posts yet.")
|
||||
return 0
|
||||
}
|
||||
rows := [][]string{{"ID", "DATE", "SUBJECT", "RECIPIENTS", "SENT", "PENDING", "FAILED", "DROPPED"}}
|
||||
for _, p := range ps {
|
||||
subject := p.Subject
|
||||
if subject == "" {
|
||||
subject = "(no subject)"
|
||||
}
|
||||
rows = append(rows, []string{strconv.FormatInt(p.ID, 10), formatDate(p.CreatedAt), subject, strconv.Itoa(p.Recipients),
|
||||
strconv.Itoa(p.Sent), strconv.Itoa(p.Pending), strconv.Itoa(p.Failed), strconv.Itoa(p.Dropped)})
|
||||
}
|
||||
c.table(rows)
|
||||
return 0
|
||||
}
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue