Merge pull request #1533 from aakashbhardwaj619/reactsaveattachments
New Sample: React Save Attachments
This commit is contained in:
commit
679e6313fb
|
@ -0,0 +1,61 @@
|
|||
# React Save Attachments
|
||||
|
||||
## Summary
|
||||
|
||||
This SPFx Outlook Add-In lets users save any email attachments to a OneDrive folder. The users can select any OneDrive folder/subfolder and choose the attachments that need to be saved. It uses Microsoft Graph API to fetch the OneDrive folders and upload the attachment files.
|
||||
|
||||
![Save Attachments](./assets/ReactSaveAttachments.gif)
|
||||
|
||||
## Used SharePoint Framework Version
|
||||
|
||||
![SPFx 1.10](https://img.shields.io/badge/version-1.10.0-green.svg)
|
||||
|
||||
## Features
|
||||
|
||||
This web part illustrates the below features for creating Outlook Add-Ins using SPFx.
|
||||
|
||||
* Select Office context and attributes of currently selected mail
|
||||
* Requesting **Mail.Read** and **Files.ReadWrite** permission scopes for Microsoft Graph through the `webApiPermissionRequests` property in `package-solution.json`
|
||||
* Use Microsoft Graph to retrieve folders and sub-folders for OneDrive
|
||||
* Use Microsoft Graph to retrieve complete mail `mimestream` by given `ID`
|
||||
* Use Microsoft Graph to save normal or big files (in size bigger 4MB) with different concepts
|
||||
|
||||
## Solution
|
||||
|
||||
Solution|Author(s)
|
||||
--------|---------
|
||||
react-save-attachments | [Aakash Bhardwaj](https://twitter.com/aakash_316)
|
||||
|
||||
|
||||
## Version history
|
||||
|
||||
Version|Date|Comments
|
||||
-------|----|--------
|
||||
1.0|October 4, 2020|Initial release
|
||||
|
||||
## Minimal Path to Awesome
|
||||
|
||||
* Clone this repository
|
||||
* In the command line run:
|
||||
* Restore dependencies: `npm install`
|
||||
From here you can also follow the deployment steps from the official [Microsoft Tutorial](https://docs.microsoft.com/en-us/sharepoint/dev/spfx/web-parts/get-started/office-addins-tutorial#packaging-and-deploying-your-solution-to-sharepoint)
|
||||
* Build solution `gulp build --ship`
|
||||
* Bundle solution: `gulp bundle --ship`
|
||||
* Package solution: `gulp package-solution --ship`
|
||||
* Locate solution at `.\sharepoint\solution\react-save-attachments.sppkg`
|
||||
* Upload it to your tenant app catalog
|
||||
* Go to your Outlook Web Access then double-click an e-mail to open it in a window
|
||||
* Choose **...** and **Get Add-ins**
|
||||
* Choose **My Add-ins** from left menu
|
||||
* Under **Custom add-ins**, choose **+ Add a custom add-in**, then **Add from file...**
|
||||
* Upload the manifest xml file from `\officeAddin` folder
|
||||
* Click **Install** on the warning message to get your add-in available on the tenant
|
||||
* Go to the **API Management** section in the new SharePoint Admin Center (*https://{tenantname}-admin.sharepoint.com/_layouts/15/online/AdminHome.aspx#/webApiPermissionManagement*)
|
||||
* **Approve** the permission request for **Mail.ReadWrite** and **Files.ReadWrite** to **Microsoft Graph**
|
||||
|
||||
## Disclaimer
|
||||
|
||||
**THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.**
|
||||
|
||||
---
|
||||
<img src="https://telemetry.sharepointpnp.com/sp-dev-fx-webparts/samples/react-save-attachments" />
|
Binary file not shown.
After Width: | Height: | Size: 878 KiB |
|
@ -0,0 +1,18 @@
|
|||
{
|
||||
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/config.2.0.schema.json",
|
||||
"version": "2.0",
|
||||
"bundles": {
|
||||
"save-attachments-web-part": {
|
||||
"components": [
|
||||
{
|
||||
"entrypoint": "./lib/webparts/saveAttachments/SaveAttachmentsWebPart.js",
|
||||
"manifest": "./src/webparts/saveAttachments/SaveAttachmentsWebPart.manifest.json"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"externals": {},
|
||||
"localizedResources": {
|
||||
"SaveAttachmentsWebPartStrings": "lib/webparts/saveAttachments/loc/{locale}.js"
|
||||
}
|
||||
}
|
|
@ -0,0 +1,4 @@
|
|||
{
|
||||
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/copy-assets.schema.json",
|
||||
"deployCdnPath": "temp/deploy"
|
||||
}
|
|
@ -0,0 +1,7 @@
|
|||
{
|
||||
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/deploy-azure-storage.schema.json",
|
||||
"workingDir": "./temp/deploy/",
|
||||
"account": "<!-- STORAGE ACCOUNT NAME -->",
|
||||
"container": "react-save-attachments",
|
||||
"accessKey": "<!-- ACCESS KEY -->"
|
||||
}
|
|
@ -0,0 +1,24 @@
|
|||
{
|
||||
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/package-solution.schema.json",
|
||||
"solution": {
|
||||
"name": "react-save-attachments-client-side-solution",
|
||||
"id": "b0a9dfa8-9221-472c-88d7-a1542bf21d8d",
|
||||
"version": "1.0.0.0",
|
||||
"includeClientSideAssets": true,
|
||||
"skipFeatureDeployment": true,
|
||||
"isDomainIsolated": false,
|
||||
"webApiPermissionRequests": [
|
||||
{
|
||||
"resource": "Microsoft Graph",
|
||||
"scope": "Mail.Read"
|
||||
},
|
||||
{
|
||||
"resource": "Microsoft Graph",
|
||||
"scope": "Files.ReadWrite"
|
||||
}
|
||||
]
|
||||
},
|
||||
"paths": {
|
||||
"zippedPackage": "solution/react-save-attachments.sppkg"
|
||||
}
|
||||
}
|
|
@ -0,0 +1,10 @@
|
|||
{
|
||||
"$schema": "https://developer.microsoft.com/json-schemas/core-build/serve.schema.json",
|
||||
"port": 4321,
|
||||
"https": true,
|
||||
"initialPage": "https://localhost:5432/workbench",
|
||||
"api": {
|
||||
"port": 5432,
|
||||
"entryPath": "node_modules/@microsoft/sp-webpart-workbench/lib/api/"
|
||||
}
|
||||
}
|
|
@ -0,0 +1,4 @@
|
|||
{
|
||||
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/write-manifests.schema.json",
|
||||
"cdnBasePath": "<!-- PATH TO CDN -->"
|
||||
}
|
|
@ -0,0 +1,7 @@
|
|||
'use strict';
|
||||
|
||||
const build = require('@microsoft/sp-build-web');
|
||||
|
||||
build.addSuppression(`Warning - [sass] The local CSS class 'ms-Grid' is not camelCase and will not be type-safe.`);
|
||||
|
||||
build.initialize(require('gulp'));
|
|
@ -0,0 +1,91 @@
|
|||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<OfficeApp xmlns="http://schemas.microsoft.com/office/appforoffice/1.1"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns:bt="http://schemas.microsoft.com/office/officeappbasictypes/1.0"
|
||||
xmlns:mailappor="http://schemas.microsoft.com/office/mailappversionoverrides/1.0"
|
||||
xsi:type="MailApp">
|
||||
<Id>04634d50-d72c-45ec-81d0-7b1f803800da</Id>
|
||||
<Version>1.0.0.0</Version>
|
||||
<ProviderName>SPFx Provider</ProviderName>
|
||||
<DefaultLocale>en-US</DefaultLocale>
|
||||
<DisplayName DefaultValue="Save Attachments"/>
|
||||
<Description DefaultValue="An SPFx Outlook addin that lets users copy email attachments to OneDrive folders."/>
|
||||
<IconUrl DefaultValue="https://cdn.graph.office.net/prod/media/shared/addin-icon.png"/>
|
||||
<HighResolutionIconUrl DefaultValue="https://cdn.graph.office.net/prod/media/shared/addin-icon.png"/>
|
||||
<SupportUrl DefaultValue="https://localhost:4321/help"/>
|
||||
<AppDomains>
|
||||
<AppDomain>https://login.microsoftonline.com</AppDomain>
|
||||
<AppDomain>https://login.windows.net</AppDomain>
|
||||
</AppDomains>
|
||||
<Hosts>
|
||||
<Host Name="Mailbox" />
|
||||
</Hosts>
|
||||
<Requirements>
|
||||
<Sets>
|
||||
<Set Name="Mailbox" MinVersion="1.4" />
|
||||
<Set Name="SharePointHostedAddin" MinVersion="1.1" />
|
||||
</Sets>
|
||||
</Requirements>
|
||||
<FormSettings>
|
||||
<Form xsi:type="ItemRead">
|
||||
<DesktopSettings>
|
||||
<SourceLocation DefaultValue="https://_SharePointTenantUrl_/_layouts/15/outlookhostedapp.aspx?componentId=04634d50-d72c-45ec-81d0-7b1f803800da"/>
|
||||
<RequestedHeight>250</RequestedHeight>
|
||||
</DesktopSettings>
|
||||
</Form>
|
||||
</FormSettings>
|
||||
<Permissions>ReadWriteMailbox</Permissions>
|
||||
<Rule xsi:type="RuleCollection" Mode="Or">
|
||||
<Rule xsi:type="ItemIs" ItemType="Message" FormType="Read" />
|
||||
</Rule>
|
||||
<DisableEntityHighlighting>false</DisableEntityHighlighting>
|
||||
<VersionOverrides xmlns="http://schemas.microsoft.com/office/mailappversionoverrides" xsi:type="VersionOverridesV1_0">
|
||||
<VersionOverrides xmlns="http://schemas.microsoft.com/office/mailappversionoverrides/1.1" xsi:type="VersionOverridesV1_1">
|
||||
<Hosts>
|
||||
<Host xsi:type="MailHost">
|
||||
<DesktopFormFactor>
|
||||
<ExtensionPoint xsi:type="MessageReadCommandSurface">
|
||||
<OfficeTab id="TabDefault">
|
||||
<Group id="msgReadGroup">
|
||||
<Label resid="GroupLabel" />
|
||||
<Control xsi:type="Button" id="msgReadOpenPaneButton">
|
||||
<Label resid="TaskpaneButton.Label" />
|
||||
<Supertip>
|
||||
<Title resid="TaskpaneButton.Label" />
|
||||
<Description resid="TaskpaneButton.Tooltip" />
|
||||
</Supertip>
|
||||
<Icon>
|
||||
<bt:Image size="16" resid="Icon.16x16" />
|
||||
<bt:Image size="32" resid="Icon.32x32" />
|
||||
<bt:Image size="80" resid="Icon.80x80" />
|
||||
</Icon>
|
||||
<Action xsi:type="ShowTaskpane">
|
||||
<SourceLocation resid="Taskpane.Url" />
|
||||
</Action>
|
||||
</Control>
|
||||
</Group>
|
||||
</OfficeTab>
|
||||
</ExtensionPoint>
|
||||
</DesktopFormFactor>
|
||||
</Host>
|
||||
</Hosts>
|
||||
<Resources>
|
||||
<bt:Images>
|
||||
<bt:Image id="Icon.16x16" DefaultValue="https://cdn.graph.office.net/prod/media/shared/addin-icon.png"/>
|
||||
<bt:Image id="Icon.32x32" DefaultValue="https://cdn.graph.office.net/prod/media/shared/addin-icon.png"/>
|
||||
<bt:Image id="Icon.80x80" DefaultValue="https://cdn.graph.office.net/prod/media/shared/addin-icon.png"/>
|
||||
</bt:Images>
|
||||
<bt:Urls>
|
||||
<bt:Url id="Taskpane.Url" DefaultValue="https://_SharePointTenantUrl_/_layouts/15/outlookhostedapp.aspx?componentId=04634d50-d72c-45ec-81d0-7b1f803800da" />
|
||||
</bt:Urls>
|
||||
<bt:ShortStrings>
|
||||
<bt:String id="GroupLabel" DefaultValue="Add-in groupLabel"/>
|
||||
<bt:String id="TaskpaneButton.Label" DefaultValue="Show Taskpane"/>
|
||||
</bt:ShortStrings>
|
||||
<bt:LongStrings>
|
||||
<bt:String id="TaskpaneButton.Tooltip" DefaultValue="Opens taskpane."/>
|
||||
</bt:LongStrings>
|
||||
</Resources>
|
||||
</VersionOverrides>
|
||||
</VersionOverrides>
|
||||
</OfficeApp>
|
File diff suppressed because it is too large
Load Diff
|
@ -0,0 +1,43 @@
|
|||
{
|
||||
"name": "react-save-attachments",
|
||||
"version": "0.0.1",
|
||||
"private": true,
|
||||
"main": "lib/index.js",
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "gulp bundle",
|
||||
"clean": "gulp clean",
|
||||
"test": "gulp test"
|
||||
},
|
||||
"dependencies": {
|
||||
"react": "16.8.5",
|
||||
"react-dom": "16.8.5",
|
||||
"@types/react": "16.8.8",
|
||||
"@types/react-dom": "16.8.3",
|
||||
"office-ui-fabric-react": "6.189.2",
|
||||
"@microsoft/sp-core-library": "1.10.0-plusbeta",
|
||||
"@microsoft/sp-property-pane": "1.10.0-plusbeta",
|
||||
"@microsoft/sp-webpart-base": "1.10.0-plusbeta",
|
||||
"@microsoft/sp-lodash-subset": "1.10.0-plusbeta",
|
||||
"@microsoft/sp-office-ui-fabric-core": "1.10.0-plusbeta",
|
||||
"@types/webpack-env": "1.13.1",
|
||||
"@types/es6-promise": "0.0.33"
|
||||
},
|
||||
"resolutions": {
|
||||
"@types/react": "16.8.8"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@microsoft/rush-stack-compiler-3.3": "0.3.5",
|
||||
"@microsoft/sp-build-web": "1.10.0-plusbeta",
|
||||
"@microsoft/sp-module-interfaces": "1.10.0-plusbeta",
|
||||
"@microsoft/sp-tslint-rules": "1.10.0-plusbeta",
|
||||
"@microsoft/sp-webpart-workbench": "1.10.0-plusbeta",
|
||||
"@types/chai": "3.4.34",
|
||||
"@types/mocha": "2.2.38",
|
||||
"@types/office-js": "^1.0.123",
|
||||
"ajv": "~5.2.2",
|
||||
"gulp": "~3.9.1"
|
||||
}
|
||||
}
|
|
@ -0,0 +1 @@
|
|||
// A file is required to be in the root of the /src directory by the TypeScript compiler
|
|
@ -0,0 +1,7 @@
|
|||
export interface IFolder {
|
||||
id: string;
|
||||
name: string;
|
||||
driveID: string;
|
||||
parentFolder: IFolder;
|
||||
webUrl: string;
|
||||
}
|
|
@ -0,0 +1,4 @@
|
|||
export interface IMail {
|
||||
id: string;
|
||||
attachments: any[];
|
||||
}
|
|
@ -0,0 +1,127 @@
|
|||
import { MSGraphClient } from '@microsoft/sp-http';
|
||||
import { IFolder } from '../models/IFolder';
|
||||
|
||||
export class GraphHelper {
|
||||
private graphClient: MSGraphClient;
|
||||
|
||||
constructor(_graphClient: MSGraphClient) {
|
||||
this.graphClient = _graphClient;
|
||||
}
|
||||
|
||||
public getOneDriveFolders(): Promise<IFolder[]> {
|
||||
return this.graphClient
|
||||
.api('me/drive/root/children')
|
||||
.version('v1.0')
|
||||
.filter('folder ne null')
|
||||
.select('id, name, parentReference, webUrl')
|
||||
.get()
|
||||
.then((response): any => {
|
||||
let folders: IFolder[] = [];
|
||||
response.value.map((item) => {
|
||||
folders.push({
|
||||
id: item.id,
|
||||
name: item.name,
|
||||
driveID: item.parentReference.driveId,
|
||||
parentFolder: null,
|
||||
webUrl: item.webUrl
|
||||
});
|
||||
});
|
||||
console.log('One Drive Folders: ', folders);
|
||||
return folders;
|
||||
});
|
||||
}
|
||||
|
||||
public getSubFolder(folder: IFolder): Promise<IFolder[]> {
|
||||
return this.graphClient
|
||||
.api(`me/drive/items/${folder.id}/children`)
|
||||
.version('v1.0')
|
||||
.filter('folder ne null')
|
||||
.select('id, name, parentReference, webUrl')
|
||||
.get()
|
||||
.then((response): any => {
|
||||
let folders: Array<IFolder> = new Array<IFolder>();
|
||||
response.value.forEach((item) => {
|
||||
folders.push({
|
||||
id: item.id,
|
||||
name: item.name,
|
||||
driveID: item.parentReference.driveId,
|
||||
parentFolder: folder,
|
||||
webUrl: item.webUrl
|
||||
});
|
||||
});
|
||||
console.log(`One Drive Sub-Folders for ${folder.name}: `, folders);
|
||||
return folders;
|
||||
});
|
||||
}
|
||||
|
||||
public async getAttachmentContent(messageId: string, attachmentId: string) {
|
||||
const attachmentContent: any = await this.graphClient
|
||||
.api(`me/messages/${messageId}/attachments/${attachmentId}/$value`)
|
||||
.version('v1.0')
|
||||
.responseType('blob')
|
||||
.get();
|
||||
console.log(`Attachment Content for ${attachmentId}: `, attachmentContent);
|
||||
return attachmentContent;
|
||||
}
|
||||
|
||||
public async saveAttachment(mimeStream: string, fileName: string, folderId: string): Promise<string> {
|
||||
const odApi = folderId === '' ? `/me/drive/root:/${fileName}:/content` : `/me/drive/items/${folderId}:/${fileName}:/content`;
|
||||
const saveResult = await this.graphClient
|
||||
.api(odApi)
|
||||
.put(mimeStream);
|
||||
console.log(`Save Attachment result for ${fileName}: `, saveResult);
|
||||
return saveResult;
|
||||
}
|
||||
|
||||
public async saveLargeAttachment(mimeStream: any, fileName: string, folderId: string) {
|
||||
const sessionOptions = {
|
||||
"item": {
|
||||
"@microsoft.graph.conflictBehavior": "rename"
|
||||
}
|
||||
};
|
||||
const apiUrl = folderId !== '' ? `/me/drive/items/${folderId}:/${fileName}:/createUploadSession` : `/me/drive/root:/${fileName}:/createUploadSession`;
|
||||
return this.graphClient
|
||||
.api(apiUrl)
|
||||
.post(JSON.stringify(sessionOptions))
|
||||
.then(async (response): Promise<any> => {
|
||||
try {
|
||||
console.log(`Upload URL created for ${fileName}: ${response.uploadUrl}`);
|
||||
const resp = await this.saveToUploadSession(mimeStream, response.uploadUrl);
|
||||
console.log(`Save Large Attachment result for ${fileName}: `, resp);
|
||||
return resp;
|
||||
}
|
||||
catch (err) {
|
||||
return null;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private async saveToUploadSession(mimeStream: any, uploadUrl: string) {
|
||||
let minSize = 0;
|
||||
let maxSize = 5 * 327680; //https://docs.microsoft.com/en-us/graph/api/driveitem-createuploadsession?view=graph-rest-1.0#upload-bytes-to-the-upload-session
|
||||
while (mimeStream.size > minSize) {
|
||||
const fileSlice = mimeStream.slice(minSize, maxSize);
|
||||
const resp = await this.uploadIndividualSlice(uploadUrl, minSize, maxSize, mimeStream.size, fileSlice);
|
||||
minSize = maxSize;
|
||||
maxSize += 5 * 327680;
|
||||
if (maxSize > mimeStream.size) {
|
||||
maxSize = mimeStream.size;
|
||||
}
|
||||
if (resp.id !== undefined) {
|
||||
return resp;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async uploadIndividualSlice(uploadUrl: string, minSize: number, maxSize: number, totalSize: number, fileSlice: string) {
|
||||
const header = {
|
||||
"Content-Length": `${maxSize - minSize}`,
|
||||
"Content-Range": `bytes ${minSize}-${maxSize - 1}/${totalSize}`,
|
||||
};
|
||||
const saveResult = await this.graphClient
|
||||
.api(uploadUrl)
|
||||
.headers(header)
|
||||
.put(fileSlice);
|
||||
return saveResult;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,27 @@
|
|||
{
|
||||
"$schema": "https://developer.microsoft.com/json-schemas/spfx/client-side-web-part-manifest.schema.json",
|
||||
"id": "04634d50-d72c-45ec-81d0-7b1f803800da",
|
||||
"alias": "SaveAttachmentsWebPart",
|
||||
"componentType": "WebPart",
|
||||
|
||||
// The "*" signifies that the version should be taken from the package.json
|
||||
"version": "*",
|
||||
"manifestVersion": 2,
|
||||
|
||||
// If true, the component can only be installed on sites where Custom Script is allowed.
|
||||
// Components that allow authors to embed arbitrary script code should set this to true.
|
||||
// https://support.office.com/en-us/article/Turn-scripting-capabilities-on-or-off-1f2c515f-5d7e-448a-9fd7-835da935584f
|
||||
"requiresCustomScript": false,
|
||||
"supportedHosts": ["SharePointWebPart"],
|
||||
|
||||
"preconfiguredEntries": [{
|
||||
"groupId": "5c03119e-3074-46fd-976b-c60198311f70", // Other
|
||||
"group": { "default": "Other" },
|
||||
"title": { "default": "SaveAttachments" },
|
||||
"description": { "default": "SaveAttachments description" },
|
||||
"officeFabricIconFontName": "Page",
|
||||
"properties": {
|
||||
"description": "SaveAttachments"
|
||||
}
|
||||
}]
|
||||
}
|
|
@ -0,0 +1,95 @@
|
|||
import * as React from 'react';
|
||||
import * as ReactDom from 'react-dom';
|
||||
import { Version } from '@microsoft/sp-core-library';
|
||||
import {
|
||||
IPropertyPaneConfiguration,
|
||||
PropertyPaneTextField
|
||||
} from '@microsoft/sp-property-pane';
|
||||
import { BaseClientSideWebPart } from '@microsoft/sp-webpart-base';
|
||||
import { GraphHelper } from '../../services/GraphHelper';
|
||||
import * as strings from 'SaveAttachmentsWebPartStrings';
|
||||
import { SaveAttachments } from './components/SaveAttachments';
|
||||
import { ISaveAttachmentsProps } from './components/ISaveAttachmentsProps';
|
||||
import { IMail } from '../../models/IMail';
|
||||
|
||||
export interface ISaveAttachmentsWebPartProps {
|
||||
description: string;
|
||||
}
|
||||
|
||||
export default class SaveAttachmentsWebPart extends BaseClientSideWebPart<ISaveAttachmentsWebPartProps> {
|
||||
private graphHelper: GraphHelper;
|
||||
public render(): void {
|
||||
let mail: IMail = null;
|
||||
if (this.context.sdks.office) {
|
||||
const item = this.context.sdks.office.context.mailbox.item;
|
||||
const itemId = this.context.sdks.office.context.mailbox.convertToRestId(item.itemId, 'v2.0');
|
||||
if (item !== null) {
|
||||
mail = {
|
||||
id: itemId,
|
||||
attachments: item.attachments
|
||||
};
|
||||
}
|
||||
} else {
|
||||
mail = {
|
||||
id: '1',
|
||||
attachments: [
|
||||
{
|
||||
id: '1',
|
||||
name: 'Sample 1'
|
||||
},
|
||||
{
|
||||
id: '2',
|
||||
name: 'Sample 2'
|
||||
}
|
||||
]
|
||||
};
|
||||
}
|
||||
|
||||
const element: React.ReactElement<ISaveAttachmentsProps> = React.createElement(
|
||||
SaveAttachments,
|
||||
{
|
||||
description: this.properties.description,
|
||||
mail,
|
||||
graphHelper: this.graphHelper
|
||||
}
|
||||
);
|
||||
|
||||
ReactDom.render(element, this.domElement);
|
||||
}
|
||||
|
||||
public async onInit() {
|
||||
await super.onInit();
|
||||
|
||||
this.graphHelper = new GraphHelper(await this.context.msGraphClientFactory.getClient());
|
||||
}
|
||||
|
||||
protected onDispose(): void {
|
||||
ReactDom.unmountComponentAtNode(this.domElement);
|
||||
}
|
||||
|
||||
protected get dataVersion(): Version {
|
||||
return Version.parse('1.0');
|
||||
}
|
||||
|
||||
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
|
||||
return {
|
||||
pages: [
|
||||
{
|
||||
header: {
|
||||
description: strings.PropertyPaneDescription
|
||||
},
|
||||
groups: [
|
||||
{
|
||||
groupName: strings.BasicGroupName,
|
||||
groupFields: [
|
||||
PropertyPaneTextField('description', {
|
||||
label: strings.DescriptionFieldLabel
|
||||
})
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
};
|
||||
}
|
||||
}
|
|
@ -0,0 +1,8 @@
|
|||
import { GraphHelper } from "../../../services/GraphHelper";
|
||||
import { IMail } from "../../../models/IMail";
|
||||
|
||||
export interface ISaveAttachmentsProps {
|
||||
description: string;
|
||||
mail: IMail;
|
||||
graphHelper: GraphHelper;
|
||||
}
|
|
@ -0,0 +1,107 @@
|
|||
@import '~office-ui-fabric-react/dist/sass/References.scss';
|
||||
|
||||
.saveAttachments {
|
||||
.container {
|
||||
margin: 0px auto;
|
||||
}
|
||||
|
||||
.row {
|
||||
@include ms-Grid-row;
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.column {
|
||||
@include ms-Grid-col;
|
||||
@include ms-lg10;
|
||||
@include ms-xl8;
|
||||
@include ms-xlPush2;
|
||||
@include ms-lgPush1;
|
||||
}
|
||||
|
||||
.checkboxGroup {
|
||||
margin-left: 9px;
|
||||
}
|
||||
|
||||
.checkboxRow {
|
||||
padding-top: 5px;
|
||||
}
|
||||
|
||||
.title {
|
||||
@include ms-font-xl;
|
||||
}
|
||||
|
||||
.subTitle {
|
||||
@include ms-font-l;
|
||||
padding-top: 5px;
|
||||
padding-bottom: 5px;
|
||||
}
|
||||
|
||||
.folderTitle {
|
||||
@include ms-font-m;
|
||||
padding-top: 5px;
|
||||
padding-bottom: 10px;
|
||||
}
|
||||
|
||||
.folderBreadcrumb {
|
||||
display: flex;
|
||||
}
|
||||
|
||||
.status {
|
||||
display: flex;
|
||||
}
|
||||
|
||||
.statusText {
|
||||
padding-top: 3px;
|
||||
@include ms-font-l;
|
||||
}
|
||||
|
||||
.loaderText {
|
||||
text-align: center;
|
||||
@include ms-font-l;
|
||||
}
|
||||
|
||||
.checkIcon {
|
||||
padding: 4px 5px;
|
||||
color: green;
|
||||
}
|
||||
|
||||
.description {
|
||||
@include ms-font-l;
|
||||
@include ms-fontColor-white;
|
||||
}
|
||||
|
||||
.button {
|
||||
// Our button
|
||||
text-decoration: none;
|
||||
height: 32px;
|
||||
|
||||
// Primary Button
|
||||
min-width: 80px;
|
||||
background-color: $ms-color-themePrimary;
|
||||
border-color: $ms-color-themePrimary;
|
||||
color: $ms-color-white;
|
||||
|
||||
// Basic Button
|
||||
outline: transparent;
|
||||
position: relative;
|
||||
font-family: "Segoe UI WestEuropean","Segoe UI",-apple-system,BlinkMacSystemFont,Roboto,"Helvetica Neue",sans-serif;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
font-size: $ms-font-size-m;
|
||||
font-weight: $ms-font-weight-regular;
|
||||
border-width: 0;
|
||||
text-align: center;
|
||||
cursor: pointer;
|
||||
display: inline-block;
|
||||
padding: 0 16px;
|
||||
|
||||
.label {
|
||||
font-weight: $ms-font-weight-semibold;
|
||||
font-size: $ms-font-size-m;
|
||||
height: 32px;
|
||||
line-height: 32px;
|
||||
margin: 0 4px;
|
||||
vertical-align: top;
|
||||
display: inline-block;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,144 @@
|
|||
import * as React from 'react';
|
||||
import { useState, useEffect } from 'react';
|
||||
import styles from './SaveAttachments.module.scss';
|
||||
import { IFolder } from '../../../models/IFolder';
|
||||
import { ISaveAttachmentsProps } from './ISaveAttachmentsProps';
|
||||
import { PrimaryButton, ActionButton } from 'office-ui-fabric-react/lib/Button';
|
||||
import { Checkbox } from 'office-ui-fabric-react/lib/Checkbox';
|
||||
import { Spinner } from 'office-ui-fabric-react/lib/Spinner';
|
||||
import { Icon } from 'office-ui-fabric-react/lib/Icon';
|
||||
import { initializeIcons } from 'office-ui-fabric-react/lib/Icons';
|
||||
initializeIcons();
|
||||
|
||||
export const SaveAttachments: React.FunctionComponent<ISaveAttachmentsProps> = (props) => {
|
||||
const [folders, setFolders] = useState<IFolder[]>([]);
|
||||
const [selectedFolder, updateSelectedFolder] = useState<IFolder>(null);
|
||||
const [checkedAttachments, updateCheckedAttachments] = useState([]);
|
||||
const [status, updateStatus] = useState('');
|
||||
const [loading, updateLoading] = useState<boolean>(undefined);
|
||||
|
||||
const successMessage = 'Attachments saved successfully';
|
||||
|
||||
useEffect(() => {
|
||||
props.graphHelper.getOneDriveFolders().then((_folders) => {
|
||||
setFolders(_folders);
|
||||
});
|
||||
}, []);
|
||||
|
||||
const updateAttachments = (ev: React.FormEvent<HTMLElement>, checked: boolean, attachment: any) => {
|
||||
let attachments = [...checkedAttachments];
|
||||
if (checked) {
|
||||
attachments.push(attachment);
|
||||
} else {
|
||||
attachments.splice(attachments.indexOf(attachment));
|
||||
}
|
||||
updateCheckedAttachments(attachments);
|
||||
};
|
||||
|
||||
const copyToOneDrive = async () => {
|
||||
updateLoading(true);
|
||||
try {
|
||||
await Promise.all(checkedAttachments.map(async (attachment) => {
|
||||
const attachmentContent = await props.graphHelper.getAttachmentContent(props.mail.id, attachment.id.replace(/\//g, '-').replace(/\+/g, '_'));
|
||||
if (attachmentContent.size > 4 * 1024 * 1024) {
|
||||
await props.graphHelper.saveLargeAttachment(attachmentContent, attachment.name, selectedFolder.id);
|
||||
} else {
|
||||
await props.graphHelper.saveAttachment(attachmentContent, attachment.name, selectedFolder.id);
|
||||
}
|
||||
}));
|
||||
updateStatus(successMessage);
|
||||
} catch (error) {
|
||||
updateStatus('Some error occurred');
|
||||
}
|
||||
updateLoading(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={styles.saveAttachments}>
|
||||
<div className={styles.container}>
|
||||
<div className={styles.row}>
|
||||
{props.mail && props.mail.attachments.length > 0 &&
|
||||
<div className={styles.column}>
|
||||
<div>
|
||||
<div className={styles.subTitle}>Select the folder:</div>
|
||||
{selectedFolder &&
|
||||
<div className={styles.folderBreadcrumb}>
|
||||
<div className={styles.folderTitle}
|
||||
onClick={async () => {
|
||||
updateLoading(undefined);
|
||||
updateSelectedFolder(selectedFolder.parentFolder);
|
||||
selectedFolder.parentFolder ?
|
||||
setFolders(await props.graphHelper.getSubFolder(selectedFolder.parentFolder)) :
|
||||
setFolders(await props.graphHelper.getOneDriveFolders());
|
||||
}}
|
||||
>
|
||||
<b>{selectedFolder !== null && selectedFolder.parentFolder ? selectedFolder.parentFolder.name : 'OneDrive'}</b>
|
||||
</div>
|
||||
<div className={styles.folderTitle}>
|
||||
<b>{selectedFolder ? `> ${selectedFolder.name}` : ''}</b>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
{folders.map((folder, i) => {
|
||||
return (
|
||||
<div key={i} >
|
||||
<ActionButton iconProps={{ iconName: 'FabricFolder' }}
|
||||
allowDisabledFocus
|
||||
styles={{ root: { height: '20px' } }}
|
||||
onClick={async () => { updateLoading(undefined); updateSelectedFolder(folder); setFolders(await props.graphHelper.getSubFolder(folder)); }}
|
||||
>
|
||||
{folder.name}
|
||||
</ActionButton>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<div className={styles.subTitle}>Select the attachments:</div>
|
||||
<div className={styles.checkboxGroup}>
|
||||
{props.mail.attachments.map((attachment) => {
|
||||
return (
|
||||
<div className={styles.checkboxRow}>
|
||||
<Checkbox label={attachment.name}
|
||||
onChange={(ev, checked) => { updateLoading(undefined); updateAttachments(ev, checked, attachment); }}
|
||||
styles={{ checkbox: { width: '15px', height: '15px', marginTop: '3px' } }}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<br />
|
||||
{loading === false &&
|
||||
<div className={styles.status}>
|
||||
{status === successMessage &&
|
||||
<div className={styles.checkIcon}>
|
||||
<Icon iconName='SkypeCircleCheck' />
|
||||
</div>
|
||||
}
|
||||
<div className={styles.statusText}>
|
||||
{status}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
{loading === true &&
|
||||
<div>
|
||||
<Spinner />
|
||||
<div className={styles.loaderText}>Uploading...</div>
|
||||
</div>
|
||||
}
|
||||
<br />
|
||||
<PrimaryButton text='Save'
|
||||
onClick={copyToOneDrive}
|
||||
disabled={selectedFolder === null || checkedAttachments.length === 0 ? true : false}
|
||||
/>
|
||||
</div>
|
||||
}
|
||||
{props.mail && props.mail.attachments.length === 0 &&
|
||||
<div className={styles.column}>
|
||||
<div className={styles.subTitle}>This email does not contain any attachments</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
|
@ -0,0 +1,7 @@
|
|||
define([], function() {
|
||||
return {
|
||||
"PropertyPaneDescription": "Description",
|
||||
"BasicGroupName": "Group Name",
|
||||
"DescriptionFieldLabel": "Description Field"
|
||||
}
|
||||
});
|
10
samples/react-save-attachments/src/webparts/saveAttachments/loc/mystrings.d.ts
vendored
Executable file
10
samples/react-save-attachments/src/webparts/saveAttachments/loc/mystrings.d.ts
vendored
Executable file
|
@ -0,0 +1,10 @@
|
|||
declare interface ISaveAttachmentsWebPartStrings {
|
||||
PropertyPaneDescription: string;
|
||||
BasicGroupName: string;
|
||||
DescriptionFieldLabel: string;
|
||||
}
|
||||
|
||||
declare module 'SaveAttachmentsWebPartStrings' {
|
||||
const strings: ISaveAttachmentsWebPartStrings;
|
||||
export = strings;
|
||||
}
|
Binary file not shown.
After Width: | Height: | Size: 3.0 KiB |
Binary file not shown.
After Width: | Height: | Size: 1.4 KiB |
|
@ -0,0 +1,38 @@
|
|||
{
|
||||
"extends": "./node_modules/@microsoft/rush-stack-compiler-3.3/includes/tsconfig-web.json",
|
||||
"compilerOptions": {
|
||||
"target": "es5",
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"module": "esnext",
|
||||
"moduleResolution": "node",
|
||||
"jsx": "react",
|
||||
"declaration": true,
|
||||
"sourceMap": true,
|
||||
"experimentalDecorators": true,
|
||||
"skipLibCheck": true,
|
||||
"outDir": "lib",
|
||||
"inlineSources": false,
|
||||
"strictNullChecks": false,
|
||||
"noUnusedLocals": false,
|
||||
"typeRoots": [
|
||||
"./node_modules/@types",
|
||||
"./node_modules/@microsoft"
|
||||
],
|
||||
"types": [
|
||||
"es6-promise",
|
||||
"webpack-env"
|
||||
],
|
||||
"lib": [
|
||||
"es5",
|
||||
"dom",
|
||||
"es2015.collection"
|
||||
]
|
||||
},
|
||||
"include": [
|
||||
"src/**/*.ts"
|
||||
],
|
||||
"exclude": [
|
||||
"node_modules",
|
||||
"lib"
|
||||
]
|
||||
}
|
|
@ -0,0 +1,30 @@
|
|||
{
|
||||
"extends": "@microsoft/sp-tslint-rules/base-tslint.json",
|
||||
"rules": {
|
||||
"class-name": false,
|
||||
"export-name": false,
|
||||
"forin": false,
|
||||
"label-position": false,
|
||||
"member-access": true,
|
||||
"no-arg": false,
|
||||
"no-console": false,
|
||||
"no-construct": false,
|
||||
"no-duplicate-variable": true,
|
||||
"no-eval": false,
|
||||
"no-function-expression": true,
|
||||
"no-internal-module": true,
|
||||
"no-shadowed-variable": true,
|
||||
"no-switch-case-fall-through": true,
|
||||
"no-unnecessary-semicolons": true,
|
||||
"no-unused-expression": true,
|
||||
"no-use-before-declare": true,
|
||||
"no-with-statement": true,
|
||||
"semicolon": true,
|
||||
"trailing-comma": false,
|
||||
"typedef": false,
|
||||
"typedef-whitespace": false,
|
||||
"use-named-parameter": true,
|
||||
"variable-name": false,
|
||||
"whitespace": false
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue