diff --git a/.devproxy/api-specs/sharepoint.yaml b/.devproxy/api-specs/sharepoint.yaml index 45cde8ac3f7..f5d060dc03f 100644 --- a/.devproxy/api-specs/sharepoint.yaml +++ b/.devproxy/api-specs/sharepoint.yaml @@ -84,6 +84,35 @@ paths: responses: 200: description: OK + /_api/Lists(guid{listId})/items({itemId})/Archive: + post: + parameters: + - name: listId + in: path + required: true + description: list GUID + schema: + type: string + example: "'b2307a39-e878-458b-bc90-03bc578531d6'" + - name: itemId + in: path + required: true + description: list item ID + schema: + type: integer + example: 1 + security: + - delegated: + - AllSites.Write + - AllSites.Manage + - AllSites.FullControl + - application: + - Sites.ReadWrite.All + - Sites.Manage.All + - Sites.FullControl.All + responses: + 200: + description: OK /_api/SP_TenantSettings_Current: get: security: @@ -238,6 +267,30 @@ paths: responses: 200: description: OK + /_api/web/GetFileByServerRelativePath(DecodedUrl={filePath}): + get: + parameters: + - name: filePath + in: path + required: true + description: URL-encoded server-relative path to the file + schema: + type: string + example: "'%2Fsites%2FM365SOBA%2Fshared%20documents%2Fgeneral%2Fdocument.docx'" + security: + - delegated: + - AllSites.Read + - AllSites.Write + - AllSites.Manage + - AllSites.FullControl + - application: + - Sites.Read.All + - Sites.ReadWrite.All + - Sites.Manage.All + - Sites.FullControl.All + responses: + 200: + description: OK /_api/web/GetFileByServerRelativePath(DecodedUrl={filePath})/$value: get: parameters: diff --git a/docs/docs/cmd/spo/file/file-archive.mdx b/docs/docs/cmd/spo/file/file-archive.mdx new file mode 100644 index 00000000000..c338fd36be1 --- /dev/null +++ b/docs/docs/cmd/spo/file/file-archive.mdx @@ -0,0 +1,106 @@ +import Global from '../../_global.mdx'; +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +# spo file archive + +Archives a file + +## Usage + +```sh +m365 spo file archive [options] +``` + +## Options + +```md definition-list +`-u, --webUrl ` +: The URL of the site where the file is located. + +`--url [url]` +: The server- or site-relative decoded URL of the file to archive. Specify either `url` or `id`, but not both. + +`-i, --id [id]` +: The UniqueId (GUID) of the file to archive. Specify either `url` or `id`, but not both. + +`-f, --force` +: Don't prompt for confirmation. +``` + + + +## Permissions + + + + + | Resource | Permissions | + |------------|----------------| + | SharePoint | AllSites.Write | + + + + + | Resource | Permissions | + |------------|---------------------| + | SharePoint | Sites.ReadWrite.All | + + + + +## Examples + +Archive a file without prompting for confirmation + +```sh +m365 spo file archive --webUrl https://contoso.sharepoint.com/sites/Marketing --id 7a8c9207-7745-4cda-b0e2-be2618ee3030 --force +``` + +Archive a file by URL with prompting for confirmation + +```sh +m365 spo file archive --webUrl https://contoso.sharepoint.com/sites/Marketing --url '/sites/Marketing/shared documents/document.docx' +``` + +## Response + + + + + ```json + { + "value": "fullyArchived" + } + ``` + + + + + ```text + value: fullyArchived + ``` + + + + + ```csv + value + fullyArchived + ``` + + + + + ```md + # spo file archive --debug "false" --verbose "false" --webUrl "https://afonline.sharepoint.com/sites/M365SOBA" --url "/sites/M365SOBA/shared documents/general/M365 responsibility.pptx" --force "true" + + Date: 4/4/2026 + + Property | Value + ---------|------- + value | fullyArchived + ``` + + + diff --git a/docs/src/config/sidebars.ts b/docs/src/config/sidebars.ts index e0f837d676a..b04d4ade73c 100644 --- a/docs/src/config/sidebars.ts +++ b/docs/src/config/sidebars.ts @@ -2686,6 +2686,11 @@ const sidebars: SidebarsConfig = { label: 'file add', id: 'cmd/spo/file/file-add' }, + { + type: 'doc', + label: 'file archive', + id: 'cmd/spo/file/file-archive' + }, { type: 'doc', label: 'file checkin', diff --git a/src/m365/spo/commands.ts b/src/m365/spo/commands.ts index 238ce27cb9e..42b1a78e4c3 100644 --- a/src/m365/spo/commands.ts +++ b/src/m365/spo/commands.ts @@ -62,6 +62,7 @@ export default { FIELD_REMOVE: `${prefix} field remove`, FIELD_SET: `${prefix} field set`, FILE_ADD: `${prefix} file add`, + FILE_ARCHIVE: `${prefix} file archive`, FILE_CHECKIN: `${prefix} file checkin`, FILE_CHECKOUT: `${prefix} file checkout`, FILE_CHECKOUT_UNDO: `${prefix} file checkout undo`, diff --git a/src/m365/spo/commands/file/file-archive.spec.ts b/src/m365/spo/commands/file/file-archive.spec.ts new file mode 100644 index 00000000000..7cb133353b1 --- /dev/null +++ b/src/m365/spo/commands/file/file-archive.spec.ts @@ -0,0 +1,249 @@ +import assert from 'assert'; +import sinon from 'sinon'; +import auth from '../../../../Auth.js'; +import { cli } from '../../../../cli/cli.js'; +import { CommandInfo } from '../../../../cli/CommandInfo.js'; +import { Logger } from '../../../../cli/Logger.js'; +import { CommandError } from '../../../../Command.js'; +import request from '../../../../request.js'; +import { telemetry } from '../../../../telemetry.js'; +import { pid } from '../../../../utils/pid.js'; +import { session } from '../../../../utils/session.js'; +import { sinonUtil } from '../../../../utils/sinonUtil.js'; +import { z } from 'zod'; +import commands from '../../commands.js'; +import command from './file-archive.js'; + +describe(commands.FILE_ARCHIVE, () => { + let log: any[]; + let logger: Logger; + let loggerLogSpy: sinon.SinonSpy; + let commandInfo: CommandInfo; + let commandOptionsSchema: z.ZodTypeAny; + let confirmationPromptStub: sinon.SinonStub; + + const successResponse = { + value: "fullyArchived" + }; + + before(() => { + sinon.stub(auth, 'restoreAuth').resolves(); + sinon.stub(telemetry, 'trackEvent').resolves(); + sinon.stub(pid, 'getProcessName').returns(''); + sinon.stub(session, 'getId').returns(''); + + auth.connection.active = true; + auth.connection.spoUrl = 'https://contoso.sharepoint.com'; + commandInfo = cli.getCommandInfo(command); + commandOptionsSchema = commandInfo.command.getSchemaToParse()!; + }); + + beforeEach(() => { + log = []; + logger = { + log: async (msg: string) => { + log.push(msg); + }, + logRaw: async (msg: string) => { + log.push(msg); + }, + logToStderr: async (msg: string) => { + log.push(msg); + } + }; + loggerLogSpy = sinon.spy(logger, 'log'); + confirmationPromptStub = sinon.stub(cli, 'promptForConfirmation').resolves(false); + }); + + afterEach(() => { + sinonUtil.restore([ + request.get, + request.post, + cli.promptForConfirmation + ]); + }); + + after(() => { + sinon.restore(); + auth.connection.active = false; + auth.connection.spoUrl = undefined; + }); + + it('has correct name', () => { + assert.strictEqual(command.name, commands.FILE_ARCHIVE); + }); + + it('has a description', () => { + assert.notStrictEqual(command.description, null); + }); + + it('excludes options from URL processing', () => { + assert.deepStrictEqual((command as any).getExcludedOptionsWithUrls(), ['url']); + }); + + it('fails validation if webUrl is not a valid SharePoint URL', async () => { + const actual = commandOptionsSchema.safeParse({ + webUrl: 'invalid-url', + id: '00000000-0000-0000-0000-000000000000', + force: true + }); + assert.strictEqual(actual.success, false); + }); + + it('fails validation if both url and id are specified', async () => { + const actual = commandOptionsSchema.safeParse({ + webUrl: 'https://contoso.sharepoint.com', + url: '/sites/test/Shared documents/document.docx', + id: '00000000-0000-0000-0000-000000000000', + force: true + }); + assert.strictEqual(actual.success, false); + }); + + it('fails validation if neither url nor id are specified', async () => { + const actual = commandOptionsSchema.safeParse({ + webUrl: 'https://contoso.sharepoint.com', + force: true + }); + assert.strictEqual(actual.success, false); + }); + + it('fails validation if the id option is not a valid GUID', async () => { + const actual = commandOptionsSchema.safeParse({ + webUrl: 'https://contoso.sharepoint.com', + id: 'invalid-guid', + force: true + }); + assert.strictEqual(actual.success, false); + }); + + it('passes validation with valid options (url)', async () => { + const actual = commandOptionsSchema.safeParse({ + webUrl: 'https://contoso.sharepoint.com', + url: '/sites/test/Shared documents/document.docx', + force: true + }); + assert.strictEqual(actual.success, true); + }); + + it('passes validation with valid options (id)', async () => { + const actual = commandOptionsSchema.safeParse({ + webUrl: 'https://contoso.sharepoint.com', + id: '00000000-0000-0000-0000-000000000000', + force: true + }); + assert.strictEqual(actual.success, true); + }); + + it('prompts before archiving file when confirmation argument not passed', async () => { + await command.action(logger, { + options: { + webUrl: 'https://contoso.sharepoint.com', + id: '00000000-0000-0000-0000-000000000000' + } + }); + assert(confirmationPromptStub.calledOnce); + }); + + it('aborts archiving file when prompt not confirmed', async () => { + await command.action(logger, { + options: { + webUrl: 'https://contoso.sharepoint.com', + url: '/sites/test/Shared documents/document.docx' + } + }); + assert(loggerLogSpy.notCalled); + }); + + it('archives file by url', async () => { + sinon.stub(request, 'get').callsFake(async (opts) => { + if (opts.url === `https://contoso.sharepoint.com/sites/test/_api/web/GetFileByServerRelativePath(DecodedUrl=@f)?$select=ListId&$expand=ListItemAllFields&@f='%2Fsites%2Ftest%2FShared%20documents%2Fdocument.docx'`) { + return { + ListId: 'b2307a39-e878-458b-bc90-03bc578531d6', + ListItemAllFields: { + Id: 1 + } + }; + } + + throw 'Invalid request'; + }); + + sinon.stub(request, 'post').callsFake(async (opts) => { + if (opts.url === `https://contoso.sharepoint.com/sites/test/_api/Lists(guid'b2307a39-e878-458b-bc90-03bc578531d6')/items(1)/Archive`) { + return successResponse; + } + + throw 'Invalid request'; + }); + + await command.action(logger, { + options: { + webUrl: 'https://contoso.sharepoint.com/sites/test', + url: '/sites/test/Shared documents/document.docx', + force: true + } + }); + + assert(loggerLogSpy.calledOnceWithExactly(successResponse)); + }); + + it('archives file by id', async () => { + sinon.stub(request, 'get').callsFake(async (opts) => { + if (opts.url === `https://contoso.sharepoint.com/sites/test/_api/web/GetFileById('00000000-0000-0000-0000-000000000000')?$select=ListId&$expand=ListItemAllFields`) { + return { + ListId: 'b2307a39-e878-458b-bc90-03bc578531d6', + ListItemAllFields: { + Id: 1 + } + }; + } + + throw 'Invalid request'; + } + ); + + sinon.stub(request, 'post').callsFake(async (opts) => { + if (opts.url === `https://contoso.sharepoint.com/sites/test/_api/Lists(guid'b2307a39-e878-458b-bc90-03bc578531d6')/items(1)/Archive`) { + return successResponse; + } + + throw 'Invalid request'; + }); + + await command.action(logger, { + options: { + webUrl: 'https://contoso.sharepoint.com/sites/test', + id: '00000000-0000-0000-0000-000000000000', + verbose: true, + force: true + } + }); + + assert(loggerLogSpy.calledOnceWithExactly(successResponse)); + }); + + it('handles error correctly', async () => { + const error = { + error: { + 'odata.error': { + code: "-2130575338, Microsoft.SharePoint.SPException", + message: { + lang: "en-US", + value: 'The file /sites/test/Shared documents/document.docx does not exist.' + } + } + } + }; + + sinon.stub(request, 'get').rejects(error); + + await assert.rejects(command.action(logger, { + options: { + webUrl: 'https://contoso.sharepoint.com/sites/test', + url: '/sites/test/Shared documents/document.docx', + force: true + } + }), new CommandError(error.error['odata.error'].message.value)); + }); +}); diff --git a/src/m365/spo/commands/file/file-archive.ts b/src/m365/spo/commands/file/file-archive.ts new file mode 100644 index 00000000000..aacb8126cfa --- /dev/null +++ b/src/m365/spo/commands/file/file-archive.ts @@ -0,0 +1,111 @@ +import commands from '../../commands.js'; +import { Logger } from '../../../../cli/Logger.js'; +import SpoCommand from '../../../base/SpoCommand.js'; +import { globalOptionsZod } from '../../../../Command.js'; +import { z } from 'zod'; +import { validation } from '../../../../utils/validation.js'; +import { cli } from '../../../../cli/cli.js'; +import { urlUtil } from '../../../../utils/urlUtil.js'; +import request, { CliRequestOptions } from '../../../../request.js'; +import { formatting } from '../../../../utils/formatting.js'; + +export const options = z.strictObject({ + ...globalOptionsZod.shape, + webUrl: z.string() + .refine(url => validation.isValidSharePointUrl(url) === true, { + error: e => `'${e.input}' is not a valid SharePoint Online site URL.` + }) + .alias('u'), + url: z.string().optional(), + id: z.uuid().optional().alias('i'), + force: z.boolean().optional().alias('f') +}); + +declare type Options = z.infer; + +interface CommandArgs { + options: Options; +} + +class SpoFileArchiveCommand extends SpoCommand { + public get name(): string { + return commands.FILE_ARCHIVE; + } + + public get description(): string { + return 'Archives a file'; + } + + public get schema(): z.ZodType | undefined { + return options; + } + + public getRefinedSchema(schema: typeof options): z.ZodObject | undefined { + return schema + .refine(options => [options.url, options.id].filter(o => o !== undefined).length === 1, { + error: `Specify 'url' or 'id', but not both.` + }); + } + + protected getExcludedOptionsWithUrls(): string[] | undefined { + return ['url']; + } + + public async commandAction(logger: Logger, args: CommandArgs): Promise { + const { webUrl, url, id, force, verbose } = args.options; + + if (!force) { + const result = await cli.promptForConfirmation({ message: `Are you sure you want to archive the file ${url || id} at site ${webUrl}?` }); + if (!result) { + return; + } + } + + try { + if (verbose) { + await logger.logToStderr(`Archiving file ${url || id} at site ${webUrl}...`); + } + + let requestUrl: string = ''; + + if (id) { + requestUrl = `${webUrl}/_api/web/GetFileById('${formatting.encodeQueryParameter(id)}')`; + } + else if (url) { + requestUrl = `${webUrl}/_api/web/GetFileByServerRelativePath(DecodedUrl=@f)`; + } + + let queryString: string = '?$select=ListId&$expand=ListItemAllFields'; + + if (url) { + const serverRelativePath = urlUtil.getServerRelativePath(webUrl, url); + queryString += `&@f='${formatting.encodeQueryParameter(serverRelativePath)}'`; + } + + const fileInfo = await request.get<{ ListId: string; ListItemAllFields: { Id: number } }>({ + url: requestUrl + queryString, + headers: { + accept: 'application/json;odata=nometadata' + }, + responseType: 'json' + }); + + const archiveUrl = `${webUrl}/_api/Lists(guid'${fileInfo.ListId}')/items(${fileInfo.ListItemAllFields.Id})/Archive`; + const requestOptions: CliRequestOptions = { + url: archiveUrl, + headers: { + accept: 'application/json;odata=nometadata' + }, + responseType: 'json' + }; + + const response = await request.post(requestOptions); + await logger.log(response); + } + catch (err: any) { + this.handleRejectedODataJsonPromise(err); + } + } +} + +export default new SpoFileArchiveCommand(); \ No newline at end of file