diff --git a/package-lock.json b/package-lock.json index 3566f96..dd7913d 100644 --- a/package-lock.json +++ b/package-lock.json @@ -19,6 +19,7 @@ "@tanstack/react-query-persist-client": "^5.104.1", "expo": "~57.0.27", "expo-constants": "~57.0.21", + "expo-document-picker": "~57.0.3", "expo-font": "~57.0.4", "expo-haptics": "~57.0.3", "expo-image": "~57.0.5", @@ -44,6 +45,7 @@ "react-native-screens": "~4.26.0", "react-native-svg": "15.15.4", "react-native-web": "~0.21.0", + "react-native-webview": "13.16.1", "react-native-worklets": "0.10.1", "zustand": "^5.0.15" }, @@ -7172,6 +7174,15 @@ "react-native": "*" } }, + "node_modules/expo-document-picker": { + "version": "57.0.3", + "resolved": "https://registry.npmjs.org/expo-document-picker/-/expo-document-picker-57.0.3.tgz", + "integrity": "sha512-XlxdZ0zzv44JRD8O15DISgIO8FTaZ581oc4kQp6MJoR7vdahjcY+2qCuDt5k1J8/lc0YR+bXon/v81norciuxw==", + "license": "MIT", + "peerDependencies": { + "expo": "*" + } + }, "node_modules/expo-file-system": { "version": "57.0.7", "resolved": "https://registry.npmjs.org/expo-file-system/-/expo-file-system-57.0.7.tgz", @@ -13187,6 +13198,20 @@ "integrity": "sha512-rkpe71W0N0c0Xz6QD0eJETuWAJGnJ9afsl1srmwPrI+yBCkge5EycXXbYRyvL29zZVUWQCY7InPRCv3GDXuZNw==", "license": "MIT" }, + "node_modules/react-native-webview": { + "version": "13.16.1", + "resolved": "https://registry.npmjs.org/react-native-webview/-/react-native-webview-13.16.1.tgz", + "integrity": "sha512-If0eHhoEdOYDcHsX+xBFwHMbWBGK1BvGDQDQdVkwtSIXiq1uiqjkpWVP2uQ1as94J0CzvFE9PUNDuhiX0Z6ubw==", + "license": "MIT", + "dependencies": { + "escape-string-regexp": "^4.0.0", + "invariant": "2.2.4" + }, + "peerDependencies": { + "react": "*", + "react-native": "*" + } + }, "node_modules/react-native-worklets": { "version": "0.10.1", "resolved": "https://registry.npmjs.org/react-native-worklets/-/react-native-worklets-0.10.1.tgz", diff --git a/package.json b/package.json index 047cc21..f04ffab 100644 --- a/package.json +++ b/package.json @@ -15,6 +15,7 @@ "@tanstack/react-query-persist-client": "^5.104.1", "expo": "~57.0.27", "expo-constants": "~57.0.21", + "expo-document-picker": "~57.0.3", "expo-font": "~57.0.4", "expo-haptics": "~57.0.3", "expo-image": "~57.0.5", @@ -40,6 +41,7 @@ "react-native-screens": "~4.26.0", "react-native-svg": "15.15.4", "react-native-web": "~0.21.0", + "react-native-webview": "13.16.1", "react-native-worklets": "0.10.1", "zustand": "^5.0.15" }, diff --git a/src/core/api/client.ts b/src/core/api/client.ts index 02f66a0..caf8390 100644 --- a/src/core/api/client.ts +++ b/src/core/api/client.ts @@ -177,6 +177,82 @@ export class GiteaClient { return text; } + /** + * Uploads a multipart/form-data body (e.g. a release asset) and parses the + * JSON response. The multipart boundary is set by the platform, so we never + * set `Content-Type` ourselves. Errors are normalized like {@link raw}. + */ + async postForm( + path: string, + form: FormData, + options: Omit = {}, + ): Promise { + const url = `${this.apiRoot}${path}${buildQuery(options.query ?? {})}`; + const headers: Record = { Accept: 'application/json' }; + if (this.token) headers.Authorization = `token ${this.token}`; + + const controller = new AbortController(); + let timedOut = false; + const timeoutMs = options.timeoutMs ?? this.timeoutMs ?? 120_000; + const timer = setTimeout(() => { + timedOut = true; + controller.abort(); + }, timeoutMs); + const onCallerAbort = () => controller.abort(); + if (options.signal) { + if (options.signal.aborted) { + clearTimeout(timer); + throw new ApiError({ kind: 'aborted', status: 0, message: 'Request cancelled.' }); + } + options.signal.addEventListener('abort', onCallerAbort); + } + + let response: Response; + try { + response = await this.fetchImpl(url, { + method: 'POST', + headers, + body: form as unknown as BodyInit, + signal: controller.signal, + }); + } catch (error) { + if (timedOut) { + throw new ApiError({ kind: 'timeout', status: 0, message: 'The upload took too long.' }); + } + if (options.signal?.aborted) { + throw new ApiError({ kind: 'aborted', status: 0, message: 'Request cancelled.' }); + } + throw toApiError(error); + } finally { + clearTimeout(timer); + options.signal?.removeEventListener('abort', onCallerAbort); + } + + const text = await response.text(); + let parsed: unknown = undefined; + if (text.length > 0) { + try { + parsed = JSON.parse(text); + } catch { + parsed = undefined; + } + } + if (!response.ok) { + const serverMessage = + parsed && typeof parsed === 'object' && 'message' in parsed + ? String((parsed as { message: unknown }).message) + : null; + const kind = ApiError.kindForStatus(response.status); + throw new ApiError({ + kind, + status: response.status, + serverMessage, + message: messageForStatus(kind, response.status, serverMessage), + }); + } + return parsed as T; + } + /** * Performs a request and returns data plus pagination metadata. * `hasMore` uses `X-Total-Count` when present, otherwise a length heuristic diff --git a/src/core/api/endpoints.test.ts b/src/core/api/endpoints.test.ts index 00ea3f6..4d09081 100644 --- a/src/core/api/endpoints.test.ts +++ b/src/core/api/endpoints.test.ts @@ -8,13 +8,19 @@ import { GiteaClient } from './client'; import { addRepoKey, + addIssueReaction, createOrg, createRelease, + createRepoVariable, createPullReview, + deletePackageVersion, + fetchRepoTree, listActionRuns, listReviewComments, mergePull, + putRepoSecret, replyToReviewComment, + transferRepo, updateRepo, updateUserSettings, } from './endpoints'; @@ -122,4 +128,53 @@ describe('endpoint request bodies', () => { ); expect(postedBody(fetchImpl)).toMatchObject({ body: 'thanks' }); }); + + it('transfers a repository', async () => { + const { fetchImpl, client } = capture(); + await transferRepo(client, 'octo', 'repo', 'newowner'); + expect(fetchImpl.mock.calls[0][0]).toBe('https://codeberg.org/api/v1/repos/octo/repo/transfer'); + expect(postedBody(fetchImpl)).toMatchObject({ new_owner: 'newowner' }); + }); + + it('writes an Actions secret and a variable', async () => { + const { fetchImpl, client } = capture(); + await putRepoSecret(client, 'octo', 'repo', 'TOKEN', 's3cr3t'); + expect(fetchImpl.mock.calls[0][0]).toBe( + 'https://codeberg.org/api/v1/repos/octo/repo/actions/secrets/TOKEN', + ); + expect(postedBody(fetchImpl)).toMatchObject({ data: 's3cr3t' }); + + fetchImpl.mockClear(); + await createRepoVariable(client, 'octo', 'repo', 'ENV', 'prod'); + expect(fetchImpl.mock.calls[0][0]).toBe( + 'https://codeberg.org/api/v1/repos/octo/repo/actions/variables/ENV', + ); + expect(postedBody(fetchImpl)).toMatchObject({ value: 'prod' }); + }); + + it('adds an issue reaction', async () => { + const { fetchImpl, client } = capture(); + await addIssueReaction(client, 'octo', 'repo', 5, '+1'); + expect(fetchImpl.mock.calls[0][0]).toBe( + 'https://codeberg.org/api/v1/repos/octo/repo/issues/5/reactions', + ); + expect(postedBody(fetchImpl)).toMatchObject({ content: '+1' }); + }); + + it('deletes a specific package version', async () => { + const { fetchImpl, client } = capture(); + await deletePackageVersion(client, 'octo', 'npm', 'pkg', '1.0.0'); + expect(fetchImpl.mock.calls[0][0]).toBe( + 'https://codeberg.org/api/v1/packages/octo/npm/pkg/1.0.0', + ); + expect(fetchImpl.mock.calls[0][1].method).toBe('DELETE'); + }); + + it('fetches the recursive git tree for file search', async () => { + const { fetchImpl, client } = capture(); + await fetchRepoTree(client, 'octo', 'repo', 'main'); + const url = fetchImpl.mock.calls[0][0] as string; + expect(url).toContain('/repos/octo/repo/git/trees/main'); + expect(url).toContain('recursive=true'); + }); }); diff --git a/src/core/api/endpoints.ts b/src/core/api/endpoints.ts index b90783b..fcb7afe 100644 --- a/src/core/api/endpoints.ts +++ b/src/core/api/endpoints.ts @@ -13,8 +13,10 @@ import { ApiError } from './errors'; import type { GiteaClient, RequestOptions } from './client'; import type { AccessToken, + ActionArtifact, ActionRun, ActionRunJob, + ActionVariable, ActionWorkflow, Activity, Branch, @@ -25,6 +27,7 @@ import type { Commit, ContentsEntry, DeployKey, + GitTree, GpgKey, Issue, Label, @@ -33,16 +36,21 @@ import type { NotificationThread, Organization, Package, + Project, PublicKey, PullRequest, PullReview, PullReviewComment, + Reaction, Release, + ReleaseAsset, Repository, ReviewEvent, + Secret, ServerVersion, Subscription, Tag, + Team, User, UserSettings, Webhook, @@ -1180,10 +1188,18 @@ export function replyToReviewComment( ); } +export interface CreateReviewCommentInput { + body: string; + path: string; + new_position?: number; + old_position?: number; +} + export interface CreateReviewInput { event: ReviewEvent; body?: string; commitId?: string; + comments?: CreateReviewCommentInput[]; } export function createPullReview( @@ -1196,7 +1212,12 @@ export function createPullReview( ): Promise { return client.post( `${repoPath(owner, repo)}/pulls/${index}/reviews`, - { event: input.event, body: input.body ?? '', commit_id: input.commitId }, + { + event: input.event, + body: input.body ?? '', + commit_id: input.commitId, + comments: input.comments, + }, options, ); } @@ -1395,3 +1416,327 @@ export function listUserActivity( query: { page: params.page ?? 1, limit: params.limit ?? 20 }, }); } + +// --------------------------------------------------------------------------- +// Release assets (multipart) +// --------------------------------------------------------------------------- + +export interface UploadFile { + /** Local file URI (from expo-document-picker / expo-image-picker). */ + uri: string; + name: string; + type: string; +} + +export function uploadReleaseAsset( + client: GiteaClient, + owner: string, + repo: string, + releaseId: number, + file: UploadFile, + options?: Omit, +): Promise { + const form = new FormData(); + // React Native accepts the {uri, name, type} shape for file parts. + form.append('attachment', { uri: file.uri, name: file.name, type: file.type } as unknown as Blob); + return client.postForm( + `${repoPath(owner, repo)}/releases/${releaseId}/assets`, + form, + { ...options, query: { ...options?.query, name: file.name } }, + ); +} + +export function deleteReleaseAsset( + client: GiteaClient, + owner: string, + repo: string, + releaseId: number, + assetId: number, + options?: RequestOptions, +): Promise { + return client.delete( + `${repoPath(owner, repo)}/releases/${releaseId}/assets/${assetId}`, + options, + ); +} + +// --------------------------------------------------------------------------- +// Repository transfer +// --------------------------------------------------------------------------- + +export function transferRepo( + client: GiteaClient, + owner: string, + repo: string, + newOwner: string, + options?: RequestOptions, +): Promise { + return client.post(`${repoPath(owner, repo)}/transfer`, { new_owner: newOwner }, options); +} + +// --------------------------------------------------------------------------- +// Actions secrets / variables / artifacts / workflow dispatch +// --------------------------------------------------------------------------- + +export function listRepoSecrets( + client: GiteaClient, + owner: string, + repo: string, + params: PageParams = {}, + options?: RequestOptions, +) { + return client.raw(`${repoPath(owner, repo)}/actions/secrets`, { + ...options, + query: { page: params.page ?? 1, limit: params.limit ?? 50 }, + }); +} + +export function putRepoSecret( + client: GiteaClient, + owner: string, + repo: string, + name: string, + data: string, + options?: RequestOptions, +): Promise { + return client.put( + `${repoPath(owner, repo)}/actions/secrets/${enc(name)}`, + { data }, + options, + ); +} + +export function deleteRepoSecret( + client: GiteaClient, + owner: string, + repo: string, + name: string, + options?: RequestOptions, +): Promise { + return client.delete(`${repoPath(owner, repo)}/actions/secrets/${enc(name)}`, options); +} + +export function listRepoVariables( + client: GiteaClient, + owner: string, + repo: string, + params: PageParams = {}, + options?: RequestOptions, +) { + return client.raw(`${repoPath(owner, repo)}/actions/variables`, { + ...options, + query: { page: params.page ?? 1, limit: params.limit ?? 50 }, + }); +} + +export function createRepoVariable( + client: GiteaClient, + owner: string, + repo: string, + name: string, + value: string, + options?: RequestOptions, +): Promise { + return client.post( + `${repoPath(owner, repo)}/actions/variables/${enc(name)}`, + { value }, + options, + ); +} + +export function deleteRepoVariable( + client: GiteaClient, + owner: string, + repo: string, + name: string, + options?: RequestOptions, +): Promise { + return client.delete(`${repoPath(owner, repo)}/actions/variables/${enc(name)}`, options); +} + +export function listRunArtifacts( + client: GiteaClient, + owner: string, + repo: string, + run: number, + options?: RequestOptions, +): Promise<{ artifacts?: ActionArtifact[] }> { + return client.get<{ artifacts?: ActionArtifact[] }>( + `${repoPath(owner, repo)}/actions/runs/${run}/artifacts`, + options, + ); +} + +export interface DispatchWorkflowInput { + ref: string; + inputs?: Record; +} + +export function dispatchWorkflow( + client: GiteaClient, + owner: string, + repo: string, + workflowId: string, + input: DispatchWorkflowInput, + options?: RequestOptions, +): Promise { + return client.post( + `${repoPath(owner, repo)}/actions/workflows/${enc(workflowId)}/dispatches`, + input, + options, + ); +} + +// --------------------------------------------------------------------------- +// Teams, projects, tree (file search) +// --------------------------------------------------------------------------- + +export function listOrgTeams( + client: GiteaClient, + org: string, + params: PageParams = {}, + options?: RequestOptions, +) { + return client.raw(`/orgs/${enc(org)}/teams`, { + ...options, + query: { page: params.page ?? 1, limit: params.limit ?? 50 }, + }); +} + +export function listRepoProjects( + client: GiteaClient, + owner: string, + repo: string, + params: PageParams = {}, + options?: RequestOptions, +) { + return client.raw(`${repoPath(owner, repo)}/projects`, { + ...options, + query: { page: params.page ?? 1, limit: params.limit ?? 50, state: 'all' }, + }); +} + +/** Recursive git tree for a ref โ€” powers the "find file" search. */ +export function fetchRepoTree( + client: GiteaClient, + owner: string, + repo: string, + ref: string, + options?: RequestOptions, +): Promise { + return client.get( + `${repoPath(owner, repo)}/git/trees/${enc(ref)}`, + { ...options, query: { recursive: true, per_page: 1000 } }, + ); +} + +// --------------------------------------------------------------------------- +// Issue reactions & attachments +// --------------------------------------------------------------------------- + +export function listIssueReactions( + client: GiteaClient, + owner: string, + repo: string, + index: number, + options?: RequestOptions, +): Promise { + return client.get(`${repoPath(owner, repo)}/issues/${index}/reactions`, options); +} + +export function addIssueReaction( + client: GiteaClient, + owner: string, + repo: string, + index: number, + content: string, + options?: RequestOptions, +): Promise { + return client.post( + `${repoPath(owner, repo)}/issues/${index}/reactions`, + { content }, + options, + ); +} + +export function removeIssueReaction( + client: GiteaClient, + owner: string, + repo: string, + index: number, + content: string, + options?: RequestOptions, +): Promise { + return client.delete( + `${repoPath(owner, repo)}/issues/${index}/reactions`, + { ...options, body: { content } }, + ); +} + +export function listIssueAttachments( + client: GiteaClient, + owner: string, + repo: string, + index: number, + options?: RequestOptions, +): Promise<{ id?: number; name?: string; size?: number; browser_download_url?: string }[]> { + return client.get( + `${repoPath(owner, repo)}/issues/${index}/assets`, + options, + ); +} + +// --------------------------------------------------------------------------- +// Admin (read-only) +// --------------------------------------------------------------------------- + +export function listAdminUsers( + client: GiteaClient, + params: PageParams = {}, + options?: RequestOptions, +) { + return client.raw('/admin/users', { + ...options, + query: { page: params.page ?? 1, limit: params.limit ?? 30 }, + }); +} + +export function listAdminOrgs( + client: GiteaClient, + params: PageParams = {}, + options?: RequestOptions, +) { + return client.raw('/admin/orgs', { + ...options, + query: { page: params.page ?? 1, limit: params.limit ?? 30 }, + }); +} + +export function listAdminRepos( + client: GiteaClient, + params: PageParams = {}, + options?: RequestOptions, +) { + return client.raw('/admin/repos', { + ...options, + query: { page: params.page ?? 1, limit: params.limit ?? 30 }, + }); +} + +// --------------------------------------------------------------------------- +// Package version deletion +// --------------------------------------------------------------------------- + +export function deletePackageVersion( + client: GiteaClient, + owner: string, + type: string, + name: string, + version: string, + options?: RequestOptions, +): Promise { + return client.delete( + `/packages/${enc(owner)}/${enc(type)}/${enc(name)}/${enc(version)}`, + options, + ); +} diff --git a/src/core/api/query-keys.ts b/src/core/api/query-keys.ts index 2d5109c..b1fae65 100644 --- a/src/core/api/query-keys.ts +++ b/src/core/api/query-keys.ts @@ -66,6 +66,27 @@ export const queryKeys = { repoKeys: (accountId: string, owner: string, name: string) => [...queryKeys.repo(accountId, owner, name), 'keys'] as const, + repoProjects: (accountId: string, owner: string, name: string) => + [...queryKeys.repo(accountId, owner, name), 'projects'] as const, + + repoTree: (accountId: string, owner: string, name: string, ref: string) => + [...queryKeys.repo(accountId, owner, name), 'tree', ref] as const, + + repoSecrets: (accountId: string, owner: string, name: string) => + [...queryKeys.repo(accountId, owner, name), 'actions', 'secrets'] as const, + + repoVariables: (accountId: string, owner: string, name: string) => + [...queryKeys.repo(accountId, owner, name), 'actions', 'variables'] as const, + + runArtifacts: (accountId: string, owner: string, name: string, run: number) => + [...queryKeys.repo(accountId, owner, name), 'actions', 'run', run, 'artifacts'] as const, + + issueReactions: (accountId: string, owner: string, name: string, index: number) => + [...queryKeys.issue(accountId, owner, name, index), 'reactions'] as const, + + issueAttachments: (accountId: string, owner: string, name: string, index: number) => + [...queryKeys.issue(accountId, owner, name, index), 'attachments'] as const, + // --- actions ------------------------------------------------------------- actionsRoot: (accountId: string, owner: string, name: string) => [...queryKeys.repo(accountId, owner, name), 'actions'] as const, diff --git a/src/core/api/types.ts b/src/core/api/types.ts index 6bf08ef..4d2a2f3 100644 --- a/src/core/api/types.ts +++ b/src/core/api/types.ts @@ -568,6 +568,84 @@ export interface UserSettings { theme?: string; } +// --------------------------------------------------------------------------- +// Actions secrets / variables / artifacts, teams, projects, tree, reactions +// --------------------------------------------------------------------------- + +export interface Secret { + name?: string; + description?: string; + created_at?: string; +} + +export interface ActionVariable { + name?: string; + data?: string; + description?: string; +} + +export interface ActionArtifact { + id?: number; + name?: string; + size_in_bytes?: number; + expired?: boolean; + expires_at?: string; + created_at?: string; + archive_download_url?: string; + workflow_run?: ActionRun; +} + +export interface Reaction { + content?: string; + user?: User; + created_at?: string; +} + +export interface Team { + id?: number; + name?: string; + description?: string; + permission?: string; + organization?: Organization; + visibility?: string; + units?: string[]; +} + +export interface Project { + id?: number; + title?: string; + description?: string; + state?: string; + type?: string; + card_type?: string; + is_closed?: boolean; + num_issues?: number; + num_open_issues?: number; + num_closed_issues?: number; + html_url?: string; + created_at?: string; + updated_at?: string; + creator?: User; +} + +export interface GitTreeEntry { + path?: string; + mode?: string; + type?: string; + size?: number; + sha?: string; + url?: string; +} + +export interface GitTree { + sha?: string; + url?: string; + truncated?: boolean; + page?: number; + total_count?: number; + entries?: GitTreeEntry[]; +} + export interface Activity { id?: number; user_id?: number; diff --git a/src/features/actions/queries.ts b/src/features/actions/queries.ts index 7d4f1c2..fe96f02 100644 --- a/src/features/actions/queries.ts +++ b/src/features/actions/queries.ts @@ -16,12 +16,13 @@ import { fetchActionRun, listActionRunJobs, listActionRuns, + listRunArtifacts, listWorkflows, rerunActionRun, type ListActionRunsParams, } from '@/core/api/endpoints'; import { queryKeys } from '@/core/api/query-keys'; -import type { ActionRun, ActionRunJob, ActionWorkflow } from '@/core/api/types'; +import type { ActionArtifact, ActionRun, ActionRunJob, ActionWorkflow } from '@/core/api/types'; import { useSession } from '@/features/accounts/use-session'; export function useWorkflows(owner: string, name: string) { @@ -114,6 +115,20 @@ export function useActionRunControl(owner: string, name: string, run: number) { return { rerun, cancel }; } +/** Artifacts produced by a workflow run. */ +export function useRunArtifacts(owner: string, name: string, run: number) { + const { client, account } = useSession(); + const accountId = account?.id ?? ''; + + return useQuery({ + queryKey: queryKeys.runArtifacts(accountId, owner, name, run), + enabled: Boolean(client) && Boolean(accountId) && run > 0, + queryFn: ({ signal }) => + listRunArtifacts(client!, owner, name, run, { signal }).then((r) => r.artifacts ?? []), + staleTime: 60_000, + }); +} + export function useActionJobLogs(owner: string, name: string, jobId: number, enabled = true) { const { client, account } = useSession(); const accountId = account?.id ?? ''; diff --git a/src/features/issues/queries.ts b/src/features/issues/queries.ts index 0c95221..8bed485 100644 --- a/src/features/issues/queries.ts +++ b/src/features/issues/queries.ts @@ -18,6 +18,7 @@ import { import type { RawResponse } from '@/core/api/client'; import { + addIssueReaction, createIssue, createIssueComment, createPull, @@ -28,7 +29,9 @@ import { fetchPull, fetchPullDiff, listCollaborators, + listIssueAttachments, listIssueComments, + listIssueReactions, listMilestones, listPullFiles, listPullReviews, @@ -37,6 +40,7 @@ import { listPulls, listReviewComments, mergePull, + removeIssueReaction, replyToReviewComment, searchIssues, updateIssue, @@ -59,6 +63,7 @@ import type { PullRequest, PullReview, PullReviewComment, + Reaction, User, } from '@/core/api/types'; import { useSession } from '@/features/accounts/use-session'; @@ -491,3 +496,53 @@ export function useCreatePull(owner: string, name: string) { export type { Issue, Label, PullRequest }; export type { ChangedFile, CombinedStatus, Comment, Milestone, PullReview, User }; + +// --------------------------------------------------------------------------- +// Issue reactions & attachments +// --------------------------------------------------------------------------- + +export function useIssueReactions(owner: string, name: string, index: number) { + const { client, account } = useSession(); + const accountId = account?.id ?? ''; + + return useQuery({ + queryKey: queryKeys.issueReactions(accountId, owner, name, index), + enabled: Boolean(client) && Boolean(accountId) && index > 0, + queryFn: ({ signal }) => listIssueReactions(client!, owner, name, index, { signal }), + staleTime: 30_000, + }); +} + +/** Adds the reaction when absent, removes it when already present. */ +export function useToggleIssueReaction(owner: string, name: string, index: number) { + const { client, account } = useSession(); + const queryClient = useQueryClient(); + const accountId = account?.id ?? ''; + + return useMutation({ + mutationFn: async ({ content, mine }: { content: string; mine: boolean }): Promise => { + if (mine) { + await removeIssueReaction(client!, owner, name, index, content); + } else { + await addIssueReaction(client!, owner, name, index, content); + } + }, + onSuccess: () => { + void queryClient.invalidateQueries({ + queryKey: queryKeys.issueReactions(accountId, owner, name, index), + }); + }, + }); +} + +export function useIssueAttachments(owner: string, name: string, index: number) { + const { client, account } = useSession(); + const accountId = account?.id ?? ''; + + return useQuery<{ id?: number; name?: string; size?: number; browser_download_url?: string }[]>({ + queryKey: queryKeys.issueAttachments(accountId, owner, name, index), + enabled: Boolean(client) && Boolean(accountId) && index > 0, + queryFn: ({ signal }) => listIssueAttachments(client!, owner, name, index, { signal }), + staleTime: 60_000, + }); +} diff --git a/src/features/profile/queries.ts b/src/features/profile/queries.ts index c31317f..a475acb 100644 --- a/src/features/profile/queries.ts +++ b/src/features/profile/queries.ts @@ -6,7 +6,12 @@ import type { RawResponse } from '@/core/api/client'; import { createOrg, deletePackage, + deletePackageVersion, + fetchAuthenticatedUser, fetchUserSettings, + listAdminOrgs, + listAdminRepos, + listAdminUsers, listOrgRepos, listPackages, listUserGpgKeys, @@ -24,6 +29,7 @@ import type { Package, PublicKey, Repository, + User, UserSettings, } from '@/core/api/types'; import { useSession } from '@/features/accounts/use-session'; @@ -49,6 +55,18 @@ function useAccountList( }); } +/** The signed-in user (used to gate admin-only UI on `is_admin`). */ +export function useCurrentUser() { + const { client, account } = useSession(); + const accountId = account?.id ?? ''; + return useQuery({ + queryKey: queryKeys.me(accountId), + enabled: Boolean(client) && Boolean(accountId), + queryFn: ({ signal }) => fetchAuthenticatedUser(client!, { signal }), + staleTime: 5 * 60_000, + }); +} + export function useUserOrgs(limit = 30) { const { client, account } = useSession(); const accountId = account?.id ?? ''; @@ -152,3 +170,47 @@ export function useDeletePackage() { }, }); } + +export function useDeletePackageVersion() { + const { client, account } = useSession(); + const queryClient = useQueryClient(); + const accountId = account?.id ?? ''; + return useMutation({ + mutationFn: ({ owner, type, name, version }: { owner: string; type: string; name: string; version: string }) => + deletePackageVersion(client!, owner, type, name, version), + onSuccess: () => { + void queryClient.invalidateQueries({ queryKey: queryKeys.account(accountId) }); + }, + }); +} + +// --------------------------------------------------------------------------- +// Admin (read-only) +// --------------------------------------------------------------------------- + +export function useAdminUsers(limit = 30) { + const { client, account } = useSession(); + const accountId = account?.id ?? ''; + return useAccountList( + [...queryKeys.account(accountId), 'admin', 'users', { limit }], + (page, signal) => listAdminUsers(client!, { page, limit }, { signal }), + ); +} + +export function useAdminOrgs(limit = 30) { + const { client, account } = useSession(); + const accountId = account?.id ?? ''; + return useAccountList( + [...queryKeys.account(accountId), 'admin', 'orgs', { limit }], + (page, signal) => listAdminOrgs(client!, { page, limit }, { signal }), + ); +} + +export function useAdminRepos(limit = 30) { + const { client, account } = useSession(); + const accountId = account?.id ?? ''; + return useAccountList( + [...queryKeys.account(accountId), 'admin', 'repos', { limit }], + (page, signal) => listAdminRepos(client!, { page, limit }, { signal }), + ); +} diff --git a/src/features/profile/screens/admin-screen.tsx b/src/features/profile/screens/admin-screen.tsx new file mode 100644 index 0000000..886ed73 --- /dev/null +++ b/src/features/profile/screens/admin-screen.tsx @@ -0,0 +1,114 @@ +import { useState } from 'react'; +import { StyleSheet, View } from 'react-native'; +import { useTranslation } from 'react-i18next'; + +import { QueryList } from '@/components/layout/query-list'; +import { Screen } from '@/components/layout/screen'; +import { AppText } from '@/components/ui/app-text'; +import { Badge } from '@/components/ui/badge'; +import { SegmentedControl } from '@/components/ui/segmented'; +import { EmptyState } from '@/components/ui/state-views'; +import type { Organization, Repository, User } from '@/core/api/types'; +import { flattenPages } from '@/core/utils/infinite'; +import { useAdminOrgs, useAdminRepos, useAdminUsers } from '@/features/profile/queries'; +import { spacing } from '@/theme/tokens'; + +type Tab = 'users' | 'orgs' | 'repos'; + +/** Instance administration (read-only) for instance admins. */ +export function AdminScreen() { + const { t } = useTranslation(); + const [tab, setTab] = useState('users'); + + const users = useAdminUsers(); + const orgs = useAdminOrgs(); + const repos = useAdminRepos(); + + return ( + + + + value={tab} + onChange={setTab} + accessibilityLabel={t('admin.title')} + options={[ + { value: 'users', label: t('admin.users') }, + { value: 'orgs', label: t('admin.orgs') }, + { value: 'repos', label: t('admin.repos') }, + ]} + /> + + + {tab === 'users' ? ( + + query={users} + items={flattenPages(users.data)} + keyExtractor={(user) => String(user.id ?? user.login)} + renderItem={(user) => ( + + + + {user.login} + + {user.full_name ? ( + + {user.full_name} + + ) : null} + + {user.is_admin ? {t('admin.adminBadge')} : null} + + )} + empty={} + /> + ) : null} + + {tab === 'orgs' ? ( + + query={orgs} + items={flattenPages(orgs.data)} + keyExtractor={(org) => String(org.id ?? org.username)} + renderItem={(org) => ( + + + {org.username ?? org.name} + + + )} + empty={} + /> + ) : null} + + {tab === 'repos' ? ( + + query={repos} + items={flattenPages(repos.data)} + keyExtractor={(repo) => String(repo.id)} + renderItem={(repo) => ( + + + + {repo.full_name} + + {repo.private ? {t('repositories.private')} : null} + + + )} + empty={} + /> + ) : null} + + ); +} + +const styles = StyleSheet.create({ + tabs: { paddingHorizontal: spacing.lg, paddingVertical: spacing.sm }, + row: { + flexDirection: 'row', + alignItems: 'center', + gap: spacing.md, + paddingHorizontal: spacing.lg, + paddingVertical: spacing.md, + }, + body: { flex: 1, gap: 2 }, +}); diff --git a/src/features/profile/screens/org-teams-screen.tsx b/src/features/profile/screens/org-teams-screen.tsx new file mode 100644 index 0000000..0c5c53e --- /dev/null +++ b/src/features/profile/screens/org-teams-screen.tsx @@ -0,0 +1,63 @@ +import { StyleSheet, View } from 'react-native'; +import { useRoute, type RouteProp } from '@react-navigation/native'; +import { useTranslation } from 'react-i18next'; + +import { Screen } from '@/components/layout/screen'; +import { AppText } from '@/components/ui/app-text'; +import { Badge } from '@/components/ui/badge'; +import { Card } from '@/components/ui/card'; +import { EmptyState, ErrorState, LoadingView } from '@/components/ui/state-views'; +import { apiErrorMessage } from '@/core/api/error-text'; +import { useOrgTeams } from '@/features/repositories/settings-queries'; +import { spacing } from '@/theme/tokens'; +import type { SettingsStackParamList } from '@/navigation/types'; + +/** Teams within an organization (read-only). */ +export function OrgTeamsScreen() { + const { t } = useTranslation(); + const route = useRoute>(); + const { org } = route.params; + const query = useOrgTeams(org); + + if (query.isPending) return ; + if (query.isError) { + return ( + void query.refetch()} + /> + ); + } + + const teams = query.data ?? []; + if (teams.length === 0) return ; + + return ( + + {teams.map((team) => ( + + + + + {team.name} + + {team.description ? ( + + {team.description} + + ) : null} + + {team.permission ? {team.permission} : null} + + + ))} + + ); +} + +const styles = StyleSheet.create({ + row: { flexDirection: 'row', alignItems: 'center', gap: spacing.md }, + body: { flex: 1, gap: 2 }, +}); diff --git a/src/features/profile/screens/organizations-screen.tsx b/src/features/profile/screens/organizations-screen.tsx index d5c31a8..3e73caa 100644 --- a/src/features/profile/screens/organizations-screen.tsx +++ b/src/features/profile/screens/organizations-screen.tsx @@ -7,6 +7,7 @@ import { QueryList } from '@/components/layout/query-list'; import { AppText } from '@/components/ui/app-text'; import { Avatar } from '@/components/ui/avatar'; import { Button } from '@/components/ui/button'; +import { IconButton } from '@/components/ui/icon-button'; import { EmptyState } from '@/components/ui/state-views'; import type { Organization } from '@/core/api/types'; import { flattenPages } from '@/core/utils/infinite'; @@ -57,6 +58,11 @@ export function OrganizationsScreen() { ) : null} + navigation.navigate('OrgTeams', { org: login })} + accessibilityLabel={t('organizations.teams')} + /> ); }} diff --git a/src/features/profile/screens/packages-screen.tsx b/src/features/profile/screens/packages-screen.tsx index 6103f59..3b8cca8 100644 --- a/src/features/profile/screens/packages-screen.tsx +++ b/src/features/profile/screens/packages-screen.tsx @@ -10,7 +10,7 @@ import { apiErrorMessage } from '@/core/api/error-text'; import type { Package } from '@/core/api/types'; import { flattenPages } from '@/core/utils/infinite'; import { formatRelativeTime } from '@/core/utils/format'; -import { useDeletePackage, usePackages } from '@/features/profile/queries'; +import { useDeletePackage, useDeletePackageVersion, usePackages } from '@/features/profile/queries'; import { useSession } from '@/features/accounts/use-session'; import { spacing } from '@/theme/tokens'; @@ -21,21 +21,35 @@ export function PackagesScreen() { const login = account?.login ?? ''; const query = usePackages(login); const deletePackage = useDeletePackage(); + const deleteVersion = useDeletePackageVersion(); const packages: Package[] = flattenPages(query.data); const confirmDelete = (pkg: Package) => { - Alert.alert(t('packages.deleteTitle'), t('packages.deleteBody', { name: pkg.name ?? '' }), [ - { text: t('common.cancel'), style: 'cancel' }, + const buttons = [ + { text: t('common.cancel'), style: 'cancel' as const }, + ...(pkg.version + ? [ + { + text: t('packages.deleteVersion'), + onPress: () => + deleteVersion.mutate( + { owner: login, type: pkg.type ?? '', name: pkg.name ?? '', version: pkg.version as string }, + { onError: (error: unknown) => Alert.alert(t('errors.title'), apiErrorMessage(error, t)) }, + ), + }, + ] + : []), { - text: t('common.delete'), - style: 'destructive', + text: t('packages.deleteAll'), + style: 'destructive' as const, onPress: () => deletePackage.mutate( { owner: login, type: pkg.type ?? '', name: pkg.name ?? '' }, - { onError: (error) => Alert.alert(t('errors.title'), apiErrorMessage(error, t)) }, + { onError: (error: unknown) => Alert.alert(t('errors.title'), apiErrorMessage(error, t)) }, ), }, - ]); + ]; + Alert.alert(t('packages.deleteTitle'), t('packages.deleteBody', { name: pkg.name ?? '' }), buttons); }; return ( diff --git a/src/features/repositories/queries.ts b/src/features/repositories/queries.ts index db46f0b..d21fd5f 100644 --- a/src/features/repositories/queries.ts +++ b/src/features/repositories/queries.ts @@ -32,10 +32,14 @@ import { createRelease, updateRelease, deleteRelease, + uploadReleaseAsset, + deleteReleaseAsset, + fetchRepoTree, type ForkRepoInput, type ListMyReposParams, type ReleaseInput, type SearchReposParams, + type UploadFile, } from '@/core/api/endpoints'; import type { RawResponse } from '@/core/api/client'; import { queryKeys } from '@/core/api/query-keys'; @@ -282,3 +286,43 @@ export function useDeleteRelease(owner: string, name: string, id: number) { onSuccess: () => invalidateReleases(queryClient, accountId, owner, name), }); } + +export function useUploadReleaseAsset(owner: string, name: string, releaseId: number) { + const { client, account } = useSession(); + const queryClient = useQueryClient(); + const accountId = account?.id ?? ''; + + return useMutation({ + mutationFn: (file: UploadFile) => uploadReleaseAsset(client!, owner, name, releaseId, file), + onSuccess: () => { + void queryClient.invalidateQueries({ queryKey: queryKeys.release(accountId, owner, name, releaseId) }); + void queryClient.invalidateQueries({ queryKey: queryKeys.repo(accountId, owner, name) }); + }, + }); +} + +export function useDeleteReleaseAsset(owner: string, name: string, releaseId: number) { + const { client, account } = useSession(); + const queryClient = useQueryClient(); + const accountId = account?.id ?? ''; + + return useMutation({ + mutationFn: (assetId: number) => deleteReleaseAsset(client!, owner, name, releaseId, assetId), + onSuccess: () => { + void queryClient.invalidateQueries({ queryKey: queryKeys.release(accountId, owner, name, releaseId) }); + }, + }); +} + +/** Recursive file tree for the "find file" search (keyed by ref). */ +export function useRepoTree(owner: string, name: string, ref: string | undefined) { + const { client, account } = useSession(); + const accountId = account?.id ?? ''; + + return useQuery({ + queryKey: queryKeys.repoTree(accountId, owner, name, ref ?? ''), + enabled: Boolean(client) && Boolean(accountId) && Boolean(ref), + queryFn: ({ signal }) => fetchRepoTree(client!, owner, name, ref!, { signal }), + staleTime: 5 * 60_000, + }); +} diff --git a/src/features/repositories/settings-queries.ts b/src/features/repositories/settings-queries.ts index d43d450..c4b11d4 100644 --- a/src/features/repositories/settings-queries.ts +++ b/src/features/repositories/settings-queries.ts @@ -7,16 +7,25 @@ import { addRepoKey, createBranchProtection, createRepo, + createRepoVariable, createWebhook, deleteBranchProtection, deleteRepo, deleteRepoKey, + deleteRepoSecret, + deleteRepoVariable, deleteWebhook, listBranchProtections, listCollaborators, + listOrgTeams, listRepoKeys, + listRepoProjects, + listRepoSecrets, + listRepoVariables, listWebhooks, + putRepoSecret, removeCollaborator, + transferRepo, updateRepo, type AddRepoKeyInput, type CollaboratorPermission, @@ -26,7 +35,16 @@ import { type UpdateRepoInput, } from '@/core/api/endpoints'; import { queryKeys } from '@/core/api/query-keys'; -import type { BranchProtection, DeployKey, User, Webhook } from '@/core/api/types'; +import type { + ActionVariable, + BranchProtection, + DeployKey, + Project, + Secret, + Team, + User, + Webhook, +} from '@/core/api/types'; import { useSession } from '@/features/accounts/use-session'; export function useCollaboratorsList(owner: string, name: string) { @@ -226,3 +244,131 @@ export function useDeleteRepoKey(owner: string, name: string) { void queryClient.invalidateQueries({ queryKey: queryKeys.repoKeys(accountId, owner, name) }), }); } + +// --------------------------------------------------------------------------- +// Transfer +// --------------------------------------------------------------------------- + +export function useTransferRepo(owner: string, name: string) { + const { client, account } = useSession(); + const queryClient = useQueryClient(); + const accountId = account?.id ?? ''; + + return useMutation({ + mutationFn: (newOwner: string) => transferRepo(client!, owner, name, newOwner), + onSuccess: () => { + void queryClient.invalidateQueries({ queryKey: queryKeys.account(accountId) }); + }, + }); +} + +// --------------------------------------------------------------------------- +// Actions secrets & variables +// --------------------------------------------------------------------------- + +export function useRepoSecrets(owner: string, name: string) { + const { client, account } = useSession(); + const accountId = account?.id ?? ''; + + return useQuery({ + queryKey: queryKeys.repoSecrets(accountId, owner, name), + enabled: Boolean(client) && Boolean(accountId), + queryFn: ({ signal }) => + listRepoSecrets(client!, owner, name, { limit: 50 }, { signal }).then((r) => r.data), + staleTime: 30_000, + }); +} + +export function usePutRepoSecret(owner: string, name: string) { + const { client, account } = useSession(); + const queryClient = useQueryClient(); + const accountId = account?.id ?? ''; + + return useMutation({ + mutationFn: ({ key, value }: { key: string; value: string }) => + putRepoSecret(client!, owner, name, key, value), + onSuccess: () => + void queryClient.invalidateQueries({ queryKey: queryKeys.repoSecrets(accountId, owner, name) }), + }); +} + +export function useDeleteRepoSecret(owner: string, name: string) { + const { client, account } = useSession(); + const queryClient = useQueryClient(); + const accountId = account?.id ?? ''; + + return useMutation({ + mutationFn: (key: string) => deleteRepoSecret(client!, owner, name, key), + onSuccess: () => + void queryClient.invalidateQueries({ queryKey: queryKeys.repoSecrets(accountId, owner, name) }), + }); +} + +export function useRepoVariables(owner: string, name: string) { + const { client, account } = useSession(); + const accountId = account?.id ?? ''; + + return useQuery({ + queryKey: queryKeys.repoVariables(accountId, owner, name), + enabled: Boolean(client) && Boolean(accountId), + queryFn: ({ signal }) => + listRepoVariables(client!, owner, name, { limit: 50 }, { signal }).then((r) => r.data), + staleTime: 30_000, + }); +} + +export function useCreateRepoVariable(owner: string, name: string) { + const { client, account } = useSession(); + const queryClient = useQueryClient(); + const accountId = account?.id ?? ''; + + return useMutation({ + mutationFn: ({ key, value }: { key: string; value: string }) => + createRepoVariable(client!, owner, name, key, value), + onSuccess: () => + void queryClient.invalidateQueries({ + queryKey: queryKeys.repoVariables(accountId, owner, name), + }), + }); +} + +export function useDeleteRepoVariable(owner: string, name: string) { + const { client, account } = useSession(); + const queryClient = useQueryClient(); + const accountId = account?.id ?? ''; + + return useMutation({ + mutationFn: (key: string) => deleteRepoVariable(client!, owner, name, key), + onSuccess: () => + void queryClient.invalidateQueries({ + queryKey: queryKeys.repoVariables(accountId, owner, name), + }), + }); +} + +/** Read-only project list for the repository. */ +export function useRepoProjects(owner: string, name: string) { + const { client, account } = useSession(); + const accountId = account?.id ?? ''; + + return useQuery({ + queryKey: queryKeys.repoProjects(accountId, owner, name), + enabled: Boolean(client) && Boolean(accountId), + queryFn: ({ signal }) => + listRepoProjects(client!, owner, name, { limit: 50 }, { signal }).then((r) => r.data), + staleTime: 60_000, + }); +} + +export function useOrgTeams(org: string) { + const { client, account } = useSession(); + const accountId = account?.id ?? ''; + + return useQuery({ + queryKey: [...queryKeys.account(accountId), 'org', org, 'teams'], + enabled: Boolean(client) && Boolean(accountId) && org.length > 0, + queryFn: ({ signal }) => + listOrgTeams(client!, org, { limit: 50 }, { signal }).then((r) => r.data), + staleTime: 60_000, + }); +} diff --git a/src/features/repository/screens/action-run-detail-screen.tsx b/src/features/repository/screens/action-run-detail-screen.tsx index 1c7a431..aa95e1c 100644 --- a/src/features/repository/screens/action-run-detail-screen.tsx +++ b/src/features/repository/screens/action-run-detail-screen.tsx @@ -11,12 +11,13 @@ import { ListItem } from '@/components/ui/list-item'; import { ErrorState, LoadingView } from '@/components/ui/state-views'; import { apiErrorMessage } from '@/core/api/error-text'; import type { ActionRunJob } from '@/core/api/types'; -import { formatDateTime } from '@/core/utils/format'; +import { formatBytes, formatDateTime } from '@/core/utils/format'; import { useActionJobLogs, useActionRun, useActionRunControl, useActionRunJobs, + useRunArtifacts, } from '@/features/actions/queries'; import { useTheme } from '@/theme/theme-provider'; import { spacing } from '@/theme/tokens'; @@ -42,6 +43,7 @@ export function ActionRunDetailScreen({ route }: Props) { const runQuery = useActionRun(owner, name, id); const jobsQuery = useActionRunJobs(owner, name, id); const control = useActionRunControl(owner, name, id); + const artifactsQuery = useRunArtifacts(owner, name, id); if (runQuery.isPending) return ; if (runQuery.isError) { @@ -57,6 +59,7 @@ export function ActionRunDetailScreen({ route }: Props) { const run = runQuery.data; const jobs: ActionRunJob[] = jobsQuery.data ?? []; + const artifacts = artifactsQuery.data ?? []; const state = run?.conclusion || run?.status || ''; const running = run?.status === 'running' || run?.status === 'waiting'; const canRerun = Boolean(run) && !running; @@ -123,6 +126,30 @@ export function ActionRunDetailScreen({ route }: Props) { ) : ( jobs.map((job) => ) )} + + {artifacts.length > 0 ? ( + <> + {t('actions.artifacts')} + + {artifacts.map((artifact) => ( + + artifact.archive_download_url + ? void Linking.openURL(artifact.archive_download_url).catch(() => undefined) + : undefined + } + /> + ))} + + + ) : null} ); } diff --git a/src/features/repository/screens/actions-screen.tsx b/src/features/repository/screens/actions-screen.tsx index 6a8599d..294edb0 100644 --- a/src/features/repository/screens/actions-screen.tsx +++ b/src/features/repository/screens/actions-screen.tsx @@ -5,6 +5,7 @@ import { useTranslation } from 'react-i18next'; import { QueryList } from '@/components/layout/query-list'; import { AppText } from '@/components/ui/app-text'; import { Badge, type BadgeTone } from '@/components/ui/badge'; +import { Button } from '@/components/ui/button'; import { SegmentedControl } from '@/components/ui/segmented'; import { EmptyState } from '@/components/ui/state-views'; import type { ActionRun } from '@/core/api/types'; @@ -55,6 +56,15 @@ export function ActionsScreen({ navigation, route }: Props) { { value: 'running', label: t('actions.filterRunning') }, ]} /> + +