feat: added react-openai-summarise-page-content web part

This commit is contained in:
Anoop T 2023-03-06 14:18:53 +00:00 committed by GitHub
parent 5dd0a074a0
commit 8a09943cda
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
59 changed files with 66219 additions and 0 deletions

View File

@ -0,0 +1,165 @@
# Multilingual SharePoint Page Summarization with Open AI API and Microsoft Graph Pages API
## Summary
This sample conatins a SharePoint Framework web part and an Azure function that uses the Open AI API to summarize a SharePoint page in multiple languages. The web part uses the Microsoft Graph Pages API to get the page content and the Azure function uses the Open AI API to summarize the page content. The web part then displays the summary in the selected language.
![screenshot](./assets/page_summary.png)
## Used SharePoint Framework Version
| :warning: Important |
|:---------------------------|
| Every SPFx version is optimally compatible with specific versions of Node.js. In order to be able to build this sample, you need to ensure that the version of Node on your workstation matches one of the versions listed in this section. This sample will not work on a different version of Node.|
|Refer to <https://aka.ms/spfx-matrix> for more information on SPFx compatibility. |
This sample is optimally compatible with the following environment configuration:
![SPFx 1.16.1](https://img.shields.io/badge/SPFx-1.16.1-green.svg)
![Node.js v16 | v14 | v12](https://img.shields.io/badge/Node.js-v16%20%7C%20v14%20%7C%20v12-green.svg)
![Compatible with SharePoint Online](https://img.shields.io/badge/SharePoint%20Online-Compatible-green.svg)
![Does not work with SharePoint 2019](https://img.shields.io/badge/SharePoint%20Server%202019-Incompatible-red.svg "SharePoint Server 2019 requires SPFx 1.4.1 or lower")
![Does not work with SharePoint 2016 (Feature Pack 2)](https://img.shields.io/badge/SharePoint%20Server%202016%20(Feature%20Pack%202)-Incompatible-red.svg "SharePoint Server 2016 Feature Pack 2 requires SPFx 1.1")
![Local Workbench Unsupported](https://img.shields.io/badge/Local%20Workbench-Unsupported-red.svg "Local workbench is no longer available as of SPFx 1.13 and above")
![Hosted Workbench Compatible](https://img.shields.io/badge/Hosted%20Workbench-Compatible-green.svg)
![Compatible with Remote Containers](https://img.shields.io/badge/Remote%20Containers-Compatible-green.svg)
## Applies to
- [SharePoint Framework](https://aka.ms/spfx)
- [Microsoft 365 tenant](https://docs.microsoft.com/en-us/sharepoint/dev/spfx/set-up-your-developer-tenant)
> Get your own free development tenant by subscribing to [Microsoft 365 developer program](http://aka.ms/o365devprogram)
## Prerequisites
> Open AI API key. You can get a key from <https://platform.openai.com/account/api-keys>
## Solution
| Solution | Author(s) |
| ----------- | ------------------------------------------------------- |
| react-openai-summarise-page-content | Anoop Tatti ( [anoopt](https://github.com/anoopt), [https://linktr.ee/anoopt](https://linktr.ee/anoopt) )|
## Version history
| Version | Date | Comments |
| ------- | ---------------- | --------------- |
| 1.0 | March 06, 2023 | Initial release |
## 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.**
---
## Minimal Path to Awesome
- Clone this repository
### App registration
- Register an Azure AD application in your tenant
- Get the client ID
- Replace the `APP_ID` in the `/webpart/src/constants/constants.ts` file with the client ID
### Azure Function
- Create an Azure Function App in your tenant with `PowerShell Core` as the runtime stack and version as `7.2`
- Copy the name of the Azure Function App
- Publish the code in `/azure-function` to the Azure Function App by following the steps in <https://learn.microsoft.com/en-us/azure/azure-functions/functions-run-local?tabs=v4%2Clinux%2Ccsharp%2Cportal%2Cbash#publish>
- Secure the Azure Function App with the app registration created above
- Go to the Azure Function in the portal and navigate to the "Authentication" configuration blade. Enable authentication and choose "Microsoft" as the "Identity provider". Then, select the app registration created above as the "App registration". Save the configuration.
- Add the following application settings to the Azure Function App
| Name | Value |
| ------- | ---------------- |
| API_Endpoint | https://api.openai.com/v1/chat/completions |
| API_Key | Your Open AI API key |
- Get the function URL of the functions in the Azure Function App
- Go to the Azure Function in the portal and navigate to the "Functions" blade.
- Click on the function name - Summarise. Copy the "Function URL" from the "Overview" blade.
- Replace the `AZURE_FUNCTION_SUMMARISE` in the `/webpart/src/constants/constants.ts` file with the function URL
- Click on the function name - UpdatePage. Copy the "Function URL" from the "Overview" blade.
- Replace the `AZURE_FUNCTION_UPDATE_PAGE` in the `/webpart/src/constants/constants.ts` file with the function URL
- Enable managed identity for the Azure Function App
- Go to the Azure Function in the portal and navigate to the "Identity" configuration blade. Enable the "System assigned" managed identity. Save the configuration.
- Grant the Azure Function App access to the SharePoint site
- Open the Azure Cloud Shell by clicking on the ">_" icon in the Azure portal toolbar in the top right corner.
- Run the command `m365 login --authType identity` to login to Microsoft 365.
- Run the command `m365 aad approleassignment add --displayName "<Azure Function App name>" --resource "SharePoint" --scope "Sites.ReadWrite.All"` to grant the Azure Function App access to SharePoint sites. Replace the `<Azure Function App name>` with the name of the Azure Function App.
- This permission is required to update the page column and will be used by the `UpdatePage` function.
- Note: `Sites.Selected` permission cab be used to if needed to restrict the access to the SharePoint site.
### Column in the Site Pages library
- Create a column in the Site Pages library
- Go to the SharePoint site in the browser where you want to add the web part
- Navigate to the Site Pages library
- Create a new column called "Summary" of type "Multiple lines of text"
### SPFx web part
- Open command prompt in the `webpart` folder
- in the command line run:
* `npm install`
* `gulp build`
* `gulp bundle --ship`
* `gulp package-solution --ship`
* Add and Deploy Package to AppCatalog
- Add the "Summarise" web part to a page in the SharePoint site
### Running the Azure function and web part locally
#### App registration (if not done already)
- Register an Azure AD application in your tenant
- Get the client ID and client secret
- Use [ACS approach](https://learn.microsoft.com/en-us/sharepoint/dev/solution-guidance/security-apponly-azureacs) to provide the write permissions to the SharePoint site where the web part needs to be added
- Replace the `APP_ID` in the `/webpart/src/constants/constants.ts` file with the client ID
#### Azure Function
- Make sure you have Azure functions core tools installed on your machine. You can install it from <https://learn.microsoft.com/en-us/azure/azure-functions/functions-run-local?tabs=v4%2Clinux%2Ccsharp%2Cportal%2Cbash>
- In the file `./azure-functions/UpdatePage/run.ps1` Comment line number 20 and uncomment line number 23
- Update the `./azure-functions/local.settings.json` file with the Open AI API key, client ID and client secret
- Open command prompt in the `azure-function` folder
- in the command line run:
* `func start`
#### SPFx web part
- Open command prompt in the `webpart` folder
- in the command line run:
* `npm install`
* `gulp serve`
- Open a page in the SharePoint site which has some text content
- Append `?loadSPFX=true&debugManifestsFile=https://localhost:4321/temp/manifests.js` to the URL
- Add the "Summarise" web part to the page
## Features
The code illustrates the following concepts:
* using React for building SharePoint Framework client-side web parts
* using OpenAI API in Azure Function
* using Microsoft Graph API to get only the text content of the page
* using custom React Hooks
* using Fluent UI FrameWork
## References
* [Getting started with SharePoint Framework](https://learn.microsoft.com/sharepoint/dev/spfx/set-up-your-developer-tenant)
* [Building for Microsoft teams](https://learn.microsoft.com/sharepoint/dev/spfx/build-for-teams-overview)
* [Use Microsoft Graph in your solution](https://learn.microsoft.com/sharepoint/dev/spfx/web-parts/get-started/using-microsoft-graph-apis)
* [Publish SharePoint Framework applications to the Marketplace](https://learn.microsoft.com/sharepoint/dev/spfx/publish-to-marketplace-overview)
* [Microsoft 365 Patterns and Practices](https://aka.ms/m365pnp) - Guidance, tooling, samples and open-source controls for your Microsoft 365 development
* [Fluent UI version 9](https://github.com/microsoft/fluentui/tree/master/packages/react-components) - Converged Fluent UI components
## Help
We do not support samples, but we this community is always willing to help, and we want to improve these samples. We use GitHub to track issues, which makes it easy for community members to volunteer their time and help resolve issues.
If you're having issues building the solution, please run [spfx doctor](https://pnp.github.io/cli-microsoft365/cmd/spfx/spfx-doctor/) from within the solution folder to diagnose incompatibility issues with your environment.
If you encounter any issues while using this sample, [create a new issue](https://github.com/pnp/sp-dev-fx-webparts/issues/new?assignees=&labels=Needs%3A+Triage+%3Amag%3A%2Ctype%3Abug-suspected%2Csample%3A%20react-openai-summarise-page-content&template=bug-report.yml&sample=react-openai-summarise-page-content&authors=@anoopt&title=react-openai-summarise-page-content%20-%20).
For questions regarding this sample, [create a new question](https://github.com/pnp/sp-dev-fx-webparts/issues/new?assignees=&labels=Needs%3A+Triage+%3Amag%3A%2Ctype%3Aquestion%2Csample%3A%20react-openai-summarise-page-content&template=question.yml&sample=react-openai-summarise-page-content&authors=@anoopt&title=react-openai-summarise-page-content%20-%20).
Finally, if you have an idea for improvement, [make a suggestion](https://github.com/pnp/sp-dev-fx-webparts/issues/new?assignees=&labels=Needs%3A+Triage+%3Amag%3A%2Ctype%3Aenhancement%2Csample%3A%20react-openai-summarise-page-content&template=question.yml&sample=react-openai-summarise-page-content&authors=@anoopt&title=react-openai-summarise-page-content%20-%20).
<img src="https://pnptelemetry.azurewebsites.net/sp-dev-fx-webparts/samples/react-openai-summarise-page-content" />

Binary file not shown.

After

Width:  |  Height:  |  Size: 240 KiB

View File

@ -0,0 +1,6 @@
# Find the Dockerfile for mcr.microsoft.com/azure-functions/powershell:3.0-powershell${VARIANT}-core-tools at this URL
# https://github.com/Azure/azure-functions-docker/blob/dev/host/3.0/buster/amd64/powershell
# Update the VARIANT arg in devcontainer.json to pick a supported PowerShell version: 7, 6
ARG VARIANT=${templateOption:imageVariant}
FROM mcr.microsoft.com/azure-functions/powershell:3.0-powershell${VARIANT}-core-tools

View File

@ -0,0 +1,30 @@
{
"name": "Azure Functions & PowerShell",
"build": {
"dockerfile": "Dockerfile"
},
"forwardPorts": [ 7071 ],
// Configure tool-specific properties.
"customizations": {
// Configure properties specific to VS Code.
"vscode": {
// Set *default* container specific settings.json values on container create.
"settings": {
"terminal.integrated.defaultProfile.linux": "pwsh"
},
// Add the IDs of extensions you want installed when the container is created.
"extensions": [
"ms-azuretools.vscode-azurefunctions",
"ms-vscode.powershell"
]
}
},
// Use 'postCreateCommand' to run commands after the container is created.
// "postCreateCommand": "dotnet restore",
// Set `remoteUser` to `root` to connect as root instead. More info: https://aka.ms/vscode-remote/containers/non-root.
"remoteUser": "vscode"
}

View File

@ -0,0 +1,7 @@
.git*
.vscode
__azurite_db*__.json
__blobstorage__
__queuestorage__
local.settings.json
test

View File

@ -0,0 +1,48 @@
bin
obj
csx
.vs
edge
Publish
*.user
*.suo
*.cscfg
*.Cache
project.lock.json
/packages
/TestResults
/tools/NuGet.exe
/App_Data
/secrets
/data
.secrets
appsettings.json
# local.settings.json
node_modules
dist
# Local python packages
.python_packages/
# Python Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# Azurite artifacts
__blobstorage__
__queuestorage__
__azurite_db*__.json

View File

@ -0,0 +1,5 @@
{
"recommendations": [
"ms-azuretools.vscode-azurefunctions"
]
}

View File

@ -0,0 +1 @@
# See the main README.md in the top level folder for more information.

View File

@ -0,0 +1,14 @@
{
"model": "gpt-3.5-turbo",
"messages": [
{
"role": "user",
"content": "1 short sentence summary in English, French and Spanish of this: {{content}}. Output format: 'English: 'xxx' \n French: 'xxx' \n Spanish: 'xxx'"
}
],
"temperature": 0.7,
"max_tokens": 256,
"top_p": 1.0,
"frequency_penalty": 0.0,
"presence_penalty": 0.0
}

View File

@ -0,0 +1,18 @@
{
"bindings": [
{
"authLevel": "function",
"type": "httpTrigger",
"direction": "in",
"name": "Request",
"methods": [
"post"
]
},
{
"type": "http",
"direction": "out",
"name": "Response"
}
]
}

View File

@ -0,0 +1,47 @@
using namespace System.Net
# Input bindings are passed in via param block.
param($Request, $TriggerMetadata)
function Get-Summary {
$content = $Request.Body.content;
$json = Get-Content -Path "$($PSScriptRoot)\data.json" -Raw
$json = $json -replace "{{content}}", $content
$uri = $env:API_Endpoint
$api_key = $env:API_Key
$headers = @{
"Content-Type" = "application/json"
"Authorization" = "Bearer " + $api_key
}
$response = Invoke-WebRequest -Uri $uri -Method Post -Headers $headers -Body $json
if ($response -and $response.StatusCode -eq 200) {
$text = $response.Content | ConvertFrom-Json | Select-Object -ExpandProperty choices | Select-Object -ExpandProperty message | Select-Object -ExpandProperty content | ForEach-Object { $_ -replace "\n", "" };
Write-Host $text;
return $text;
}
else {
Write-Host "Error calling API";
return $null;
}
}
function main {
# Write to the Azure Functions log stream.
Write-Host "PowerShell HTTP trigger function summarise, processed a request."
$summary = Get-Summary;
# Associate values to output bindings by calling 'Push-OutputBinding'.
Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
StatusCode = [HttpStatusCode]::OK
Body = $summary
});
}
main;

View File

@ -0,0 +1,19 @@
{
"bindings": [
{
"authLevel": "function",
"type": "httpTrigger",
"direction": "in",
"name": "Request",
"methods": [
"get",
"post"
]
},
{
"type": "http",
"direction": "out",
"name": "Response"
}
]
}

View File

@ -0,0 +1,58 @@
using namespace System.Net
# Input bindings are passed in via param block.
param($Request, $TriggerMetadata)
function Update-Page {
param(
[Parameter(Mandatory = $true)]
[string]$siteUrl,
[Parameter(Mandatory = $true)]
[string]$pageItemId,
[Parameter(Mandatory = $true)]
[string]$columnName,
[Parameter(Mandatory = $true)]
[string]$columnValue
)
# If in Azure, use Managed Identity to connect to SharePoint
Connect-PnPOnline $siteUrl -ManagedIdentity
# If debugging locally, use ClientId and ClientSecret to connect to SharePoint
# Connect-PnPOnline $siteUrl -ClientId $env:ClientId -ClientSecret $env:ClientSecret
$item = Get-PnPListItem -List "Site Pages" -Id $pageItemId
Set-PnPListItem -List "Site Pages" -Identity $pageItemId -Values @{$columnName = $columnValue }
# publish the page
$page = Get-PnPPage -Identity $item.FieldValues["FileLeafRef"]
$page.Publish("Published by Azure Function");
# Why is this not working?
# $item.File.Publish("Published by Azure Function");
}
function main {
# Write to the Azure Functions log stream.
Write-Host "PowerShell HTTP trigger function updatepage, processed a request."
$result = "Please pass a pageItemId, siteUrl, columnName and columnValue in the request body";
$pageItemId = $Request.Body.pageItemId;
$siteUrl = $Request.Body.siteUrl;
$columnName = $Request.Body.columnName;
$columnValue = $Request.Body.columnValue;
if ($null -ne $pageItemId -and $null -ne $siteUrl -and $null -ne $columnName -and $null -ne $columnValue) {
Update-Page -siteUrl $siteUrl -pageItemId $pageItemId -columnName $columnName -columnValue $columnValue;
$result = "Page updated";
}
# Associate values to output bindings by calling 'Push-OutputBinding'.
Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
StatusCode = [HttpStatusCode]::OK
Body = $result
});
}
main;

View File

@ -0,0 +1,18 @@
{
"version": "2.0",
"logging": {
"applicationInsights": {
"samplingSettings": {
"isEnabled": true,
"excludedTypes": "Request"
}
}
},
"managedDependency": {
"enabled": true
},
"extensionBundle": {
"id": "Microsoft.Azure.Functions.ExtensionBundle",
"version": "[3.*, 4.0.0)"
}
}

View File

@ -0,0 +1,15 @@
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "",
"FUNCTIONS_WORKER_RUNTIME_VERSION": "7.2",
"FUNCTIONS_WORKER_RUNTIME": "powershell",
"API_Endpoint": "https://api.openai.com/v1/chat/completions",
"API_Key": "sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"ClientId": "APP_ID",
"ClientSecret": "APP_SECRET"
},
"Host": {
"CORS": "*"
}
}

View File

@ -0,0 +1,22 @@
# Azure Functions profile.ps1
#
# This profile.ps1 will get executed every "cold start" of your Function App.
# "cold start" occurs when:
#
# * A Function App starts up for the very first time
# * A Function App starts up after being de-allocated due to inactivity
#
# You can define helper functions, run commands, or specify environment variables
# NOTE: any variables defined that are not environment variables will get reset after the first execution
# Authenticate with Azure PowerShell using MSI.
# Remove this if you are not planning on using MSI or Azure PowerShell.
<# if ($env:MSI_SECRET) {
Disable-AzContextAutosave -Scope Process | Out-Null
Connect-AzAccount -Identity
} #>
# Uncomment the next line to enable legacy AzureRm alias in Azure PowerShell.
# Enable-AzureRmAlias
# You can also define functions or aliases that can be referenced in any of your PowerShell functions.

View File

@ -0,0 +1,9 @@
# This file enables modules to be automatically managed by the Functions service.
# See https://aka.ms/functionsmanageddependency for additional information.
#
@{
# For latest supported version, go to 'https://www.powershellgallery.com/packages/Az'.
# To use the Az module in your function app, please uncomment the line below.
# 'Az' = '9.*'
'PnP.PowerShell' = '2.0.30-nightly'
}

View File

@ -0,0 +1,39 @@
// For more information on how to run this SPFx project in a VS Code Remote Container, please visit https://aka.ms/spfx-devcontainer
{
"name": "SPFx 1.16.1",
"image": "docker.io/m365pnp/spfx:1.16.1",
// Set *default* container specific settings.json values on container create.
"settings": {},
// Add the IDs of extensions you want installed when the container is created.
"extensions": [
"editorconfig.editorconfig",
"dbaeumer.vscode-eslint"
],
// Use 'forwardPorts' to make a list of ports inside the container available locally.
"forwardPorts": [
4321,
35729
],
"portsAttributes": {
"4321": {
"protocol": "https",
"label": "Manifest",
"onAutoForward": "silent",
"requireLocalPort": true
},
// Not needed for SPFx>= 1.12.1
// "5432": {
// "protocol": "https",
// "label": "Workbench",
// "onAutoForward": "silent"
// },
"35729": {
"protocol": "https",
"label": "LiveReload",
"onAutoForward": "silent",
"requireLocalPort": true
}
},
"postCreateCommand": "bash .devcontainer/spfx-startup.sh",
"remoteUser": "node"
}

View File

@ -0,0 +1,33 @@
echo
echo -e "\e[1;94mInstalling Node dependencies\e[0m"
npm install
## commands to create dev certificate and copy it to the root folder of the project
echo
echo -e "\e[1;94mGenerating dev certificate\e[0m"
gulp trust-dev-cert
# Convert the generated PEM certificate to a CER certificate
openssl x509 -inform PEM -in ~/.rushstack/rushstack-serve.pem -outform DER -out ./spfx-dev-cert.cer
# Copy the PEM ecrtificate for non-Windows hosts
cp ~/.rushstack/rushstack-serve.pem ./spfx-dev-cert.pem
## add *.cer to .gitignore to prevent certificates from being saved in repo
if ! grep -Fxq '*.cer' ./.gitignore
then
echo "# .CER Certificates" >> .gitignore
echo "*.cer" >> .gitignore
fi
## add *.pem to .gitignore to prevent certificates from being saved in repo
if ! grep -Fxq '*.pem' ./.gitignore
then
echo "# .PEM Certificates" >> .gitignore
echo "*.pem" >> .gitignore
fi
echo
echo -e "\e[1;92mReady!\e[0m"
echo -e "\n\e[1;94m**********\nOptional: if you plan on using gulp serve, don't forget to add the container certificate to your local machine. Please visit https://aka.ms/spfx-devcontainer for more information\n**********"

View File

@ -0,0 +1,352 @@
require('@rushstack/eslint-config/patch/modern-module-resolution');
module.exports = {
extends: ['@microsoft/eslint-config-spfx/lib/profiles/react'],
parserOptions: { tsconfigRootDir: __dirname },
overrides: [
{
files: ['*.ts', '*.tsx'],
parser: '@typescript-eslint/parser',
'parserOptions': {
'project': './tsconfig.json',
'ecmaVersion': 2018,
'sourceType': 'module'
},
rules: {
// Prevent usage of the JavaScript null value, while allowing code to access existing APIs that may require null. https://www.npmjs.com/package/@rushstack/eslint-plugin
'@rushstack/no-new-null': 1,
// Require Jest module mocking APIs to be called before any other statements in their code block. https://www.npmjs.com/package/@rushstack/eslint-plugin
'@rushstack/hoist-jest-mock': 1,
// Require regular expressions to be constructed from string constants rather than dynamically building strings at runtime. https://www.npmjs.com/package/@rushstack/eslint-plugin-security
'@rushstack/security/no-unsafe-regexp': 1,
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/adjacent-overload-signatures': 1,
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
//
// CONFIGURATION: By default, these are banned: String, Boolean, Number, Object, Symbol
'@typescript-eslint/ban-types': [
1,
{
'extendDefaults': false,
'types': {
'String': {
'message': 'Use \'string\' instead',
'fixWith': 'string'
},
'Boolean': {
'message': 'Use \'boolean\' instead',
'fixWith': 'boolean'
},
'Number': {
'message': 'Use \'number\' instead',
'fixWith': 'number'
},
'Object': {
'message': 'Use \'object\' instead, or else define a proper TypeScript type:'
},
'Symbol': {
'message': 'Use \'symbol\' instead',
'fixWith': 'symbol'
},
'Function': {
'message': 'The \'Function\' type accepts any function-like value.\nIt provides no type safety when calling the function, which can be a common source of bugs.\nIt also accepts things like class declarations, which will throw at runtime as they will not be called with \'new\'.\nIf you are expecting the function to accept certain arguments, you should explicitly define the function shape.'
}
}
}
],
// RATIONALE: Code is more readable when the type of every variable is immediately obvious.
// Even if the compiler may be able to infer a type, this inference will be unavailable
// to a person who is reviewing a GitHub diff. This rule makes writing code harder,
// but writing code is a much less important activity than reading it.
//
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/explicit-function-return-type': [
1,
{
'allowExpressions': true,
'allowTypedFunctionExpressions': true,
'allowHigherOrderFunctions': false
}
],
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
// Rationale to disable: although this is a recommended rule, it is up to dev to select coding style.
// Set to 1 (warning) or 2 (error) to enable.
'@typescript-eslint/explicit-member-accessibility': 0,
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/no-array-constructor': 1,
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
//
// RATIONALE: The "any" keyword disables static type checking, the main benefit of using TypeScript.
// This rule should be suppressed only in very special cases such as JSON.stringify()
// where the type really can be anything. Even if the type is flexible, another type
// may be more appropriate such as "unknown", "{}", or "Record<k,V>".
'@typescript-eslint/no-explicit-any': 1,
// RATIONALE: The #1 rule of promises is that every promise chain must be terminated by a catch()
// handler. Thus wherever a Promise arises, the code must either append a catch handler,
// or else return the object to a caller (who assumes this responsibility). Unterminated
// promise chains are a serious issue. Besides causing errors to be silently ignored,
// they can also cause a NodeJS process to terminate unexpectedly.
// '@typescript-eslint/no-floating-promises': 2,
// RATIONALE: Catches a common coding mistake.
'@typescript-eslint/no-for-in-array': 2,
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/no-misused-new': 2,
// RATIONALE: The "namespace" keyword is not recommended for organizing code because JavaScript lacks
// a "using" statement to traverse namespaces. Nested namespaces prevent certain bundler
// optimizations. If you are declaring loose functions/variables, it's better to make them
// static members of a class, since classes support property getters and their private
// members are accessible by unit tests. Also, the exercise of choosing a meaningful
// class name tends to produce more discoverable APIs: for example, search+replacing
// the function "reverse()" is likely to return many false matches, whereas if we always
// write "Text.reverse()" is more unique. For large scale organization, it's recommended
// to decompose your code into separate NPM packages, which ensures that component
// dependencies are tracked more conscientiously.
//
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/no-namespace': [
1,
{
'allowDeclarations': false,
'allowDefinitionFiles': false
}
],
// RATIONALE: Parameter properties provide a shorthand such as "constructor(public title: string)"
// that avoids the effort of declaring "title" as a field. This TypeScript feature makes
// code easier to write, but arguably sacrifices readability: In the notes for
// "@typescript-eslint/member-ordering" we pointed out that fields are central to
// a class's design, so we wouldn't want to bury them in a constructor signature
// just to save some typing.
//
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
// Set to 1 (warning) or 2 (error) to enable the rule
'@typescript-eslint/no-parameter-properties': 0,
// RATIONALE: When left in shipping code, unused variables often indicate a mistake. Dead code
// may impact performance.
//
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/no-unused-vars': [
1,
{
'vars': 'all',
// Unused function arguments often indicate a mistake in JavaScript code. However in TypeScript code,
// the compiler catches most of those mistakes, and unused arguments are fairly common for type signatures
// that are overriding a base class method or implementing an interface.
'args': 'none'
}
],
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/no-use-before-define': [
2,
{
'functions': false,
'classes': true,
'variables': true,
'enums': true,
'typedefs': true
}
],
// Disallows require statements except in import statements.
// In other words, the use of forms such as var foo = require("foo") are banned. Instead use ES6 style imports or import foo = require("foo") imports.
'@typescript-eslint/no-var-requires': 'error',
// RATIONALE: The "module" keyword is deprecated except when describing legacy libraries.
//
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/prefer-namespace-keyword': 1,
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
// Rationale to disable: it's up to developer to decide if he wants to add type annotations
// Set to 1 (warning) or 2 (error) to enable the rule
'@typescript-eslint/no-inferrable-types': 0,
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
// Rationale to disable: declaration of empty interfaces may be helpful for generic types scenarios
'@typescript-eslint/no-empty-interface': 0,
// RATIONALE: This rule warns if setters are defined without getters, which is probably a mistake.
'accessor-pairs': 1,
// RATIONALE: In TypeScript, if you write x["y"] instead of x.y, it disables type checking.
'dot-notation': [
1,
{
'allowPattern': '^_'
}
],
// RATIONALE: Catches code that is likely to be incorrect
'eqeqeq': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'for-direction': 1,
// RATIONALE: Catches a common coding mistake.
'guard-for-in': 2,
// RATIONALE: If you have more than 2,000 lines in a single source file, it's probably time
// to split up your code.
'max-lines': ['warn', { max: 2000 }],
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
// 'no-async-promise-executor': 2,
// RATIONALE: Deprecated language feature.
'no-caller': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-compare-neg-zero': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-cond-assign': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-constant-condition': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-control-regex': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-debugger': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-delete-var': 2,
// RATIONALE: Catches code that is likely to be incorrect
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-duplicate-case': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-empty': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-empty-character-class': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-empty-pattern': 1,
// RATIONALE: Eval is a security concern and a performance concern.
'no-eval': 1,
// RATIONALE: Catches code that is likely to be incorrect
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-ex-assign': 2,
// RATIONALE: System types are global and should not be tampered with in a scalable code base.
// If two different libraries (or two versions of the same library) both try to modify
// a type, only one of them can win. Polyfills are acceptable because they implement
// a standardized interoperable contract, but polyfills are generally coded in plain
// JavaScript.
'no-extend-native': 1,
// Disallow unnecessary labels
'no-extra-label': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-fallthrough': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-func-assign': 1,
// RATIONALE: Catches a common coding mistake.
'no-implied-eval': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-invalid-regexp': 2,
// RATIONALE: Catches a common coding mistake.
'no-label-var': 2,
// RATIONALE: Eliminates redundant code.
'no-lone-blocks': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-misleading-character-class': 2,
// RATIONALE: Catches a common coding mistake.
'no-multi-str': 2,
// RATIONALE: It's generally a bad practice to call "new Thing()" without assigning the result to
// a variable. Either it's part of an awkward expression like "(new Thing()).doSomething()",
// or else implies that the constructor is doing nontrivial computations, which is often
// a poor class design.
'no-new': 1,
// RATIONALE: Obsolete language feature that is deprecated.
'no-new-func': 2,
// RATIONALE: Obsolete language feature that is deprecated.
'no-new-object': 2,
// RATIONALE: Obsolete notation.
'no-new-wrappers': 1,
// RATIONALE: Catches code that is likely to be incorrect
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-octal': 2,
// RATIONALE: Catches code that is likely to be incorrect
'no-octal-escape': 2,
// RATIONALE: Catches code that is likely to be incorrect
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-regex-spaces': 2,
// RATIONALE: Catches a common coding mistake.
'no-return-assign': 2,
// RATIONALE: Security risk.
'no-script-url': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-self-assign': 2,
// RATIONALE: Catches a common coding mistake.
'no-self-compare': 2,
// RATIONALE: This avoids statements such as "while (a = next(), a && a.length);" that use
// commas to create compound expressions. In general code is more readable if each
// step is split onto a separate line. This also makes it easier to set breakpoints
// in the debugger.
'no-sequences': 1,
// RATIONALE: Catches code that is likely to be incorrect
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-shadow-restricted-names': 2,
// RATIONALE: Obsolete language feature that is deprecated.
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-sparse-arrays': 2,
// RATIONALE: Although in theory JavaScript allows any possible data type to be thrown as an exception,
// such flexibility adds pointless complexity, by requiring every catch block to test
// the type of the object that it receives. Whereas if catch blocks can always assume
// that their object implements the "Error" contract, then the code is simpler, and
// we generally get useful additional information like a call stack.
'no-throw-literal': 2,
// RATIONALE: Catches a common coding mistake.
'no-unmodified-loop-condition': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-unsafe-finally': 2,
// RATIONALE: Catches a common coding mistake.
'no-unused-expressions': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-unused-labels': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-useless-catch': 1,
// RATIONALE: Avoids a potential performance problem.
'no-useless-concat': 1,
// RATIONALE: The "var" keyword is deprecated because of its confusing "hoisting" behavior.
// Always use "let" or "const" instead.
//
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'no-var': 2,
// RATIONALE: Generally not needed in modern code.
'no-void': 1,
// RATIONALE: Obsolete language feature that is deprecated.
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-with': 2,
// RATIONALE: Makes logic easier to understand, since constants always have a known value
// @typescript-eslint\eslint-plugin\dist\configs\eslint-recommended.js
'prefer-const': 1,
// RATIONALE: Catches a common coding mistake where "resolve" and "reject" are confused.
'promise/param-names': 2,
// RATIONALE: Catches code that is likely to be incorrect
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'require-atomic-updates': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'require-yield': 1,
// "Use strict" is redundant when using the TypeScript compiler.
'strict': [
2,
'never'
],
// RATIONALE: Catches code that is likely to be incorrect
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'use-isnan': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
// Set to 1 (warning) or 2 (error) to enable.
// Rationale to disable: !!{}
'no-extra-boolean-cast': 0,
// ====================================================================
// @microsoft/eslint-plugin-spfx
// ====================================================================
'@microsoft/spfx/import-requires-chunk-name': 1,
'@microsoft/spfx/no-require-ensure': 2,
'@microsoft/spfx/pair-react-dom-render-unmount': 1
}
},
{
// For unit tests, we can be a little bit less strict. The settings below revise the
// defaults specified in the extended configurations, as well as above.
files: [
// Test files
'*.test.ts',
'*.test.tsx',
'*.spec.ts',
'*.spec.tsx',
// Facebook convention
'**/__mocks__/*.ts',
'**/__mocks__/*.tsx',
'**/__tests__/*.ts',
'**/__tests__/*.tsx',
// Microsoft convention
'**/test/*.ts',
'**/test/*.tsx'
],
rules: {}
}
]
};

View File

@ -0,0 +1,35 @@
# Logs
logs
*.log
npm-debug.log*
# Dependency directories
node_modules
# Build generated files
dist
lib
release
solution
temp
*.sppkg
.heft
# Coverage directory used by tools like istanbul
coverage
# OSX
.DS_Store
# Visual Studio files
.ntvs_analysis.dat
.vs
bin
obj
# Resx Generated Code
*.resx.ts
# Styles Generated Code
*.scss.ts
*.scss.d.ts

View File

@ -0,0 +1,16 @@
!dist
config
gulpfile.js
release
src
temp
tsconfig.json
tslint.json
*.log
.yo-rc.json
.vscode

View File

@ -0,0 +1,23 @@
{
"version": "0.2.0",
"configurations": [
{
"name": "Hosted workbench",
"type": "pwa-chrome",
"request": "launch",
"url": "https://enter-your-SharePoint-site/_layouts/workbench.aspx",
"webRoot": "${workspaceRoot}",
"sourceMaps": true,
"sourceMapPathOverrides": {
"webpack:///.././src/*": "${webRoot}/src/*",
"webpack:///../../../src/*": "${webRoot}/src/*",
"webpack:///../../../../src/*": "${webRoot}/src/*",
"webpack:///../../../../../src/*": "${webRoot}/src/*"
},
"runtimeArgs": [
"--remote-debugging-port=9222",
"-incognito"
]
}
]
}

View File

@ -0,0 +1,13 @@
// Place your settings in this file to overwrite default and user settings.
{
// Configure glob patterns for excluding files and folders in the file explorer.
"files.exclude": {
"**/.git": true,
"**/.DS_Store": true,
"**/bower_components": true,
"**/coverage": true,
"**/lib-amd": true,
"src/**/*.scss.ts": true
},
"typescript.tsdk": ".\\node_modules\\typescript\\lib"
}

View File

@ -0,0 +1,21 @@
{
"@microsoft/generator-sharepoint": {
"plusBeta": false,
"isCreatingSolution": true,
"nodeVersion": "16.19.1",
"sdksVersions": {
"@microsoft/microsoft-graph-client": "3.0.2",
"@microsoft/teams-js": "2.4.1"
},
"version": "1.16.1",
"libraryName": "open-ai-summarise",
"libraryId": "f15c9e3f-fcfe-4059-bf17-a2bfa7f49020",
"environment": "spo",
"packageManager": "npm",
"solutionName": "open-ai-summarise",
"solutionShortDescription": "open-ai-summarise description",
"skipFeatureDeployment": true,
"isDomainIsolated": false,
"componentType": "webpart"
}
}

View File

@ -0,0 +1 @@
# See the main README.md in the top level folder for more information.

View File

@ -0,0 +1,18 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/config.2.0.schema.json",
"version": "2.0",
"bundles": {
"summarise-web-part": {
"components": [
{
"entrypoint": "./lib/webparts/summarise/SummariseWebPart.js",
"manifest": "./src/webparts/summarise/SummariseWebPart.manifest.json"
}
]
}
},
"externals": {},
"localizedResources": {
"SummariseWebPartStrings": "lib/webparts/summarise/loc/{locale}.js"
}
}

View File

@ -0,0 +1,7 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/deploy-azure-storage.schema.json",
"workingDir": "./release/assets/",
"account": "<!-- STORAGE ACCOUNT NAME -->",
"container": "open-ai-summarise",
"accessKey": "<!-- ACCESS KEY -->"
}

View File

@ -0,0 +1,50 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/package-solution.schema.json",
"solution": {
"name": "open-ai-summarise-client-side-solution",
"id": "f15c9e3f-fcfe-4059-bf17-a2bfa7f49020",
"version": "1.0.0.0",
"includeClientSideAssets": true,
"skipFeatureDeployment": true,
"isDomainIsolated": false,
"developer": {
"name": "",
"websiteUrl": "",
"privacyUrl": "",
"termsOfUseUrl": "",
"mpnId": "Undefined-1.16.1"
},
"webApiPermissionRequests": [
{
"resource": "APP_REG_NAME",
"scope": "user_impersonation"
},
{
"resource": "Microsoft Graph",
"scope": "Sites.Read.All"
}
],
"metadata": {
"shortDescription": {
"default": "A webpart that uses Open AI to summarise text."
},
"longDescription": {
"default": "A webpart that uses Open AI to summarise text on a SharePoint page using the Open AI API and Microsoft graph pages API."
},
"screenshotPaths": [],
"videoUrl": "",
"categories": []
},
"features": [
{
"title": "open-ai-summarise Feature",
"description": "The feature that activates elements of the open-ai-summarise solution.",
"id": "92c9f7fc-92e7-435a-81f7-9d483adc99ff",
"version": "1.0.0.0"
}
]
},
"paths": {
"zippedPackage": "solution/open-ai-summarise.sppkg"
}
}

View File

@ -0,0 +1,3 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/core-build/sass.schema.json"
}

View File

@ -0,0 +1,6 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/spfx-serve.schema.json",
"port": 4321,
"https": true,
"initialPage": "https://enter-your-SharePoint-site/_layouts/workbench.aspx"
}

View File

@ -0,0 +1,4 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/write-manifests.schema.json",
"cdnBasePath": "<!-- PATH TO CDN -->"
}

View File

@ -0,0 +1,6 @@
{
"$schema": "https://raw.githubusercontent.com/s-KaiNet/spfx-fast-serve/master/schema/config.latest.schema.json",
"cli": {
"isLibraryComponent": false
}
}

View File

@ -0,0 +1,24 @@
/*
* User webpack settings file. You can add your own settings here.
* Changes from this file will be merged into the base webpack configuration file.
* This file will not be overwritten by the subsequent spfx-fast-serve calls.
*/
// you can add your project related webpack configuration here, it will be merged using webpack-merge module
// i.e. plugins: [new webpack.Plugin()]
const webpackConfig = {
}
// for even more fine-grained control, you can apply custom webpack settings using below function
const transformConfig = function (initialWebpackConfig) {
// transform the initial webpack config here, i.e.
// initialWebpackConfig.plugins.push(new webpack.Plugin()); etc.
return initialWebpackConfig;
}
module.exports = {
webpackConfig,
transformConfig
}

View File

@ -0,0 +1,22 @@
'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.`);
var getTasks = build.rig.getTasks;
build.rig.getTasks = function () {
var result = getTasks.call(build.rig);
result.set('serve', result.get('serve-deprecated'));
return result;
};
/* fast-serve */
const { addFastServe } = require("spfx-fast-serve-helpers");
addFastServe(build);
/* end of fast-serve */
build.initialize(require('gulp'));

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,43 @@
{
"name": "open-ai-summarise",
"version": "0.0.1",
"private": true,
"engines": {
"node": ">=16.13.0 <17.0.0"
},
"main": "lib/index.js",
"scripts": {
"build": "gulp bundle",
"clean": "gulp clean",
"test": "gulp test",
"serve": "gulp bundle --custom-serve --max_old_space_size=4096 && fast-serve"
},
"dependencies": {
"@fluentui/merge-styles": "^8.5.6",
"@microsoft/sp-core-library": "1.16.1",
"@microsoft/sp-lodash-subset": "1.16.1",
"@microsoft/sp-office-ui-fabric-core": "1.16.1",
"@microsoft/sp-property-pane": "1.16.1",
"@microsoft/sp-webpart-base": "1.16.1",
"office-ui-fabric-react": "^7.199.1",
"react": "17.0.1",
"react-dom": "17.0.1",
"tslib": "2.3.1"
},
"devDependencies": {
"@microsoft/eslint-config-spfx": "1.16.1",
"@microsoft/eslint-plugin-spfx": "1.16.1",
"@microsoft/rush-stack-compiler-4.5": "0.2.2",
"@microsoft/sp-build-web": "1.16.1",
"@microsoft/sp-module-interfaces": "1.16.1",
"@rushstack/eslint-config": "2.5.1",
"@types/react": "17.0.45",
"@types/react-dom": "17.0.17",
"@types/webpack-env": "~1.15.2",
"ajv": "^6.12.5",
"eslint-plugin-react-hooks": "4.3.0",
"gulp": "4.0.2",
"spfx-fast-serve-helpers": "~1.16.0",
"typescript": "4.5.5"
}
}

View File

@ -0,0 +1,5 @@
export const SITE_PAGES_LIBRARY_NAME = "Site Pages";
export const SUMMARY_COLUMN_NAME = "Summary";
export const APP_ID = "APP_ID";
export const AZURE_FUNCTION_SUMMARISE = "http://localhost:7071/api/Summarise";
export const AZURE_FUNCTION_UPDATE_PAGE = "http://localhost:7071/api/UpdatePage";

View File

@ -0,0 +1,3 @@
export * from './useAzureFunctions';
export * from './useSharePointRest';
export * from './useMicrosoftGraph';

View File

@ -0,0 +1,73 @@
import * as React from 'react';
import { AadHttpClient, AadHttpClientFactory } from "@microsoft/sp-http";
import { APP_ID, AZURE_FUNCTION_SUMMARISE, AZURE_FUNCTION_UPDATE_PAGE } from '../constants/constants';
export const useAzureFunctions = (aadHttpClientFactory: AadHttpClientFactory) => {
const clientRef = React.useRef<AadHttpClient>();
const getClient = React.useCallback(async () => {
if (!aadHttpClientFactory) {
return undefined;
}
const client = await aadHttpClientFactory.getClient(APP_ID);
clientRef.current = client;
}, [aadHttpClientFactory]);
const callAzureFunction = React.useCallback(
async (functionName: string, request: any, method: 'get' | 'post' = 'post') => {
try {
if (!clientRef.current) {
await getClient();
}
let requestHeaders: any = {};
requestHeaders['Content-Type'] = 'application/json';
let requestParams = '';
if (method === 'get' && request) {
// Add request params to URL query string
const params = new URLSearchParams(request).toString();
functionName += `?${params}`;
} else if (method === 'post') {
requestParams = JSON.stringify(request);
}
const response = await (await clientRef.current)[method](
functionName,
AadHttpClient.configurations.v1,
{
headers: requestHeaders,
body: requestParams
}
);
console.log('response', response);
const result = await response.text();
console.log('Azure function result - ', result);
return result;
} catch (error) {
if (!DEBUG) {
console.error('Error:', error);
}
return undefined;
}
},
[getClient]
);
const getSummaryUsingOpenAI = React.useCallback(
async (content: string) => {
return await callAzureFunction(AZURE_FUNCTION_SUMMARISE, { content });
},
[callAzureFunction]
);
const updatePagePnPPowerShell = React.useCallback(
async (siteUrl: string, pageItemId: number, columnName: string, columnValue: string) => {
return await callAzureFunction(AZURE_FUNCTION_UPDATE_PAGE, { siteUrl, pageItemId, columnName, columnValue });
},
[callAzureFunction]
);
return { getSummaryUsingOpenAI, updatePagePnPPowerShell };
};

View File

@ -0,0 +1,64 @@
import * as React from 'react';
import { MSGraphClientV3, MSGraphClientFactory } from '@microsoft/sp-http';
export const useMicrosoftGraph = (msGraphClientFactory: MSGraphClientFactory) => {
const clientRef = React.useRef<MSGraphClientV3>();
const getClient = React.useCallback(async (): Promise<any> => {
if (!msGraphClientFactory) {
return undefined;
}
const client = await msGraphClientFactory.getClient('3');
clientRef.current = client;
}, [msGraphClientFactory]);
const callMicrosoftGraphAPI = React.useCallback(
async (
method: "get" | "post" | "patch" | "delete",
apiUrl: string,
version: "v1.0" | "beta",
content?: any,
selectProperties?: string[],
expandProperties?: string[],
filter?: string,
count?: boolean
): Promise<any> => {
if (!clientRef.current) {
await getClient();
}
const query = clientRef.current.api(apiUrl).version(version);
typeof content === 'object' && (content = JSON.stringify(content));
selectProperties && selectProperties.length > 0 && (query.select(selectProperties));
filter && filter.length > 0 && (query.filter(filter));
expandProperties && expandProperties.length > 0 && (query.expand(expandProperties));
count && (query.count(count));
try {
return await new Promise((resolve, reject) => {
let callback = (error: any, response: any, rawResponse?: any) => {
if (error) {
reject(error);
} else {
resolve(response);
}
};
if (method === 'post' || method === 'patch') {
query[method](content, callback);
} else {
query[method](callback);
}
});
} catch (error) {
console.error(`Error calling Microsoft Graph API: ${error.message}`);
throw error;
}
},
[getClient]
);
return { callMicrosoftGraphAPI };
};

View File

@ -0,0 +1,99 @@
import { useCallback } from 'react';
import { SPHttpClient, SPHttpClientResponse } from '@microsoft/sp-http';
export const useSharePointRest = (spHttpClient: SPHttpClient, siteUrl: string) => {
const getItem = useCallback(async (listName: string, itemId: number, selectColumns?: string[]) => {
const selectString = selectColumns ? selectColumns.join(',') : '';
const url = `${siteUrl}/_api/web/lists/getByTitle('${listName}')/items?$filter=Id eq ${itemId}&$select=${selectString}`;
try {
const response: SPHttpClientResponse = await spHttpClient.get(url, SPHttpClient.configurations.v1, {
headers: {
'Accept': 'application/json;odata.metadata=none'
}
});
const responseJson = await response.json();
if (responseJson.error) {
console.error('Error in get SharePoint data', responseJson.error);
return undefined;
}
return responseJson.value[0];
} catch (error) {
console.error('Error in get SharePoint data', error);
return undefined;
}
}, [spHttpClient, siteUrl]);
const postItem = useCallback(async (listName: string, itemData: any) => {
const url = `${siteUrl}/_api/web/lists/getByTitle('${listName}')/items`;
try {
const response: SPHttpClientResponse = await spHttpClient.post(url, SPHttpClient.configurations.v1, {
headers: {
'Accept': 'application/json;odata.metadata=none',
'Content-type': 'application/json;odata=verbose',
'odata-version': ''
},
body: JSON.stringify(itemData)
});
const responseJson = await response.json();
if (responseJson.error) {
console.error('Error in post SharePoint data', responseJson.error);
return undefined;
}
return responseJson.value;
} catch (error) {
console.error('Error in post SharePoint data', error);
return undefined;
}
}, [spHttpClient, siteUrl]);
const updateItem = useCallback(async (listName: string, itemId: number, itemData: any) => {
const url = `${siteUrl}/_api/web/lists/getByTitle('${listName}')/items(${itemId})`;
try {
const response: SPHttpClientResponse = await spHttpClient.post(url, SPHttpClient.configurations.v1, {
headers: {
'Accept': 'application/json;odata.metadata=none',
'Content-type': 'application/json;odata=verbose',
'odata-version': '',
'X-HTTP-Method': 'MERGE',
'IF-MATCH': '*'
},
body: JSON.stringify(itemData)
});
const responseJson = await response.json();
if (responseJson.error) {
console.error('Error in update SharePoint item', responseJson.error);
return undefined;
}
return responseJson.value;
} catch (error) {
console.error('Error in update SharePoint item', error);
return undefined;
}
}, [spHttpClient, siteUrl]);
const deleteItem = useCallback(async (listName: string, itemId: number) => {
const url = `${siteUrl}/_api/web/lists/getByTitle('${listName}')/items(${itemId})`;
try {
const response: SPHttpClientResponse = await spHttpClient.post(url, SPHttpClient.configurations.v1, {
headers: {
'Accept': 'application/json;odata.metadata=none',
'X-HTTP-Method': 'DELETE',
'IF-MATCH': '*'
}
});
const responseJson = await response.json();
if (responseJson.error) {
console.error('Error in delete SharePoint item', responseJson.error);
return undefined;
}
return responseJson;
} catch (error) {
console.error('Error in delete SharePoint item', error);
return undefined;
}
}, [spHttpClient, siteUrl]);
return { getItem, postItem, updateItem, deleteItem };
};

View File

@ -0,0 +1 @@
// A file is required to be in the root of the /src directory by the TypeScript compiler

View File

@ -0,0 +1,45 @@
import { AadHttpClient, AadHttpClientFactory } from "@microsoft/sp-http";
export class AzureFunctions {
private static _aadHttpClient: AadHttpClient;
public static async Init(aadHttpClientFactory: AadHttpClientFactory, appId: string) {
this._aadHttpClient = await aadHttpClientFactory.getClient(appId);
}
public static async CallAzureFunction(functionName: string, request: any, method: 'get' | 'post' = 'post') {
try {
if (!this._aadHttpClient) return;
let requestHeaders: any = {};
requestHeaders['Content-Type'] = 'application/json';
let requestParams = '';
if (method === 'get' && request) {
// Add request params to URL query string
const params = new URLSearchParams(request).toString();
functionName += `?${params}`;
} else if (method === 'post') {
requestParams = JSON.stringify(request);
}
const response = await this._aadHttpClient[method](
functionName,
AadHttpClient.configurations.v1,
{
headers: requestHeaders,
body: requestParams
});
console.log("response", response);
const result = await response.text();
console.log("Azure function result - ", result);
return result;
} catch (error) {
if (!DEBUG) {
console.error("Error:", error);
}
return undefined;
}
}
}

View File

@ -0,0 +1,33 @@
import { MSGraphClientV3, MSGraphClientFactory } from '@microsoft/sp-http';
export class MicrosoftGraph {
private static _graphClient: MSGraphClientV3;
public static async Init(msGraphClientFactory: MSGraphClientFactory): Promise<void> {
this._graphClient = await msGraphClientFactory.getClient('3');
}
public static async CallMicrosoftGraph (
method: "get" | "post" | "patch" | "delete",
apiUrl: string,
version: "v1.0" | "beta",
content?: any,
selectProperties?: string[],
expandProperties?: string[],
filter?: string,
count?: boolean
): Promise<any> {
const p = new Promise<string>(async (resolve, reject) => {
let query = this._graphClient.api(apiUrl).version(version);
typeof(content) === "object" && (content = JSON.stringify(content));
selectProperties && selectProperties.length > 0 && (query = query.select(selectProperties));
filter && filter.length > 0 && (query = query.filter(filter));
expandProperties && expandProperties.length > 0 && (query = query.expand(expandProperties));
count && (query = query.count(count));
let callback = (error: any, response: any, rawResponse?: any) => error ? reject(error) : resolve(response);
//* ES2016
["post", "patch"].includes(method) ? await query[method](content, callback) : await query[method](callback);
});
return p;
}
}

View File

@ -0,0 +1,48 @@
import { SPHttpClient, SPHttpClientResponse } from '@microsoft/sp-http';
export default class SharePointRest {
private static async makeRequest(url: string, spHttpClient: SPHttpClient, requestType: string, itemData?: any): Promise<any> {
try {
const response: SPHttpClientResponse = await spHttpClient.fetch(url, SPHttpClient.configurations.v1, {
method: requestType,
headers: {
'Accept': 'application/json;odata.metadata=none',
'Content-type': 'application/json;odata=verbose',
'odata-version': '',
...(requestType === 'DELETE' ? {'X-HTTP-Method': 'DELETE', 'IF-MATCH': '*'} : {})
},
body: requestType === 'POST' || requestType === 'MERGE' ? JSON.stringify(itemData) : undefined
});
const responseJson = await response.json();
if (responseJson.error) {
console.error(`Error in ${requestType} SharePoint data`, responseJson.error);
return undefined;
}
return requestType === 'GET' ? responseJson.value[0] : responseJson.value;
} catch (error) {
console.error(`Error in ${requestType} SharePoint data`, error);
return undefined;
}
}
public static async getItem(spHttpClient: SPHttpClient, siteUrl: string, listName: string, itemId: number, selectColumns?: string[]): Promise<any> {
const selectString = selectColumns ? selectColumns.join(',') : '';
const url = `${siteUrl}/_api/web/lists/getByTitle('${listName}')/items?$filter=Id eq ${itemId}&$select=${selectString}`;
return await this.makeRequest(url, spHttpClient, 'GET');
}
public static async postItem(spHttpClient: SPHttpClient, siteUrl: string, listName: string, itemData: any): Promise<any> {
const url = `${siteUrl}/_api/web/lists/getByTitle('${listName}')/items`;
return await this.makeRequest(url, spHttpClient, 'POST', itemData);
}
public static async updateItem(spHttpClient: SPHttpClient, siteUrl: string, listName: string, itemId: number, itemData: any): Promise<any> {
const url = `${siteUrl}/_api/web/lists/getByTitle('${listName}')/items(${itemId})`;
return await this.makeRequest(url, spHttpClient, 'MERGE', itemData);
}
public static async deleteItem(spHttpClient: SPHttpClient, siteUrl: string, listName: string, itemId: number): Promise<any> {
const url = `${siteUrl}/_api/web/lists/getByTitle('${listName}')/items(${itemId})`;
return await this.makeRequest(url, spHttpClient, 'DELETE');
}
}

View File

@ -0,0 +1,3 @@
export * from './AzureFunctions';
export * from './MicrosoftGraph';
export * from './SharePointRest';

View File

@ -0,0 +1,26 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx/client-side-web-part-manifest.schema.json",
"id": "2111d6f4-2ccc-4400-be27-58b1a795bcac",
"alias": "SummariseWebPart",
"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", "SharePointFullPage"],
"supportsThemeVariants": true,
"preconfiguredEntries": [{
"groupId": "5c03119e-3074-46fd-976b-c60198311f70", // Advanced
"group": { "default": "Advanced" },
"title": { "default": "Summarise" },
"description": { "default": "A webpart that uses Open AI to summarise current page's text." },
"officeFabricIconFontName": "AlignLeft",
"properties": {}
}]
}

View File

@ -0,0 +1,59 @@
import * as React from 'react';
import * as ReactDom from 'react-dom';
import { Version } from '@microsoft/sp-core-library';
import {
IPropertyPaneConfiguration
} from '@microsoft/sp-property-pane';
import { BaseClientSideWebPart } from '@microsoft/sp-webpart-base';
import Summarise from './components/Summarise';
import { ISummariseProps } from './components/ISummariseProps';
export interface ISummariseWebPartProps {
}
export default class SummariseWebPart extends BaseClientSideWebPart<ISummariseWebPartProps> {
public render(): void {
const listItem: any = this.context.pageContext.listItem;
const element: React.ReactElement<ISummariseProps> = React.createElement(
Summarise,
{
spHttpClient: this.context.spHttpClient,
aadHttpClientFactory: this.context.aadHttpClientFactory,
msGraphClientFactory: this.context.msGraphClientFactory,
pageItemId: listItem.id,
pageId: listItem.uniqueId,
siteId: this.context.pageContext.site.id.toString(),
siteUrl: this.context.pageContext.site.absoluteUrl
}
);
ReactDom.render(element, this.domElement);
}
protected async onInit(): Promise<void> {
// If you want to use the services instead of hooks, you can use the following:
// await azurefunctions.Init(this.context.aadHttpClientFactory, APP_ID);
// await MicrosoftGraph.Init(this.context.msGraphClientFactory);
return super.onInit();
}
protected onDispose(): void {
ReactDom.unmountComponentAtNode(this.domElement);
}
protected get dataVersion(): Version {
return Version.parse('1.0');
}
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
return {
pages: []
};
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

View File

@ -0,0 +1,10 @@
import { SPHttpClient, AadHttpClientFactory, MSGraphClientFactory } from "@microsoft/sp-http";
export interface ISummariseProps {
spHttpClient: SPHttpClient;
aadHttpClientFactory: AadHttpClientFactory;
msGraphClientFactory: MSGraphClientFactory;
pageItemId: number;
pageId: string;
siteId: string;
siteUrl: string;
}

View File

@ -0,0 +1,160 @@
import * as React from 'react';
import { ISummariseProps } from './ISummariseProps';
import { Spinner, SpinnerSize } from '@fluentui/react/lib/Spinner';
import { FontIcon } from '@fluentui/react/lib/Icon';
import { summariseStyles, loadingSpinnerStyles } from './styles';
import { isEmpty } from '@microsoft/sp-lodash-subset';
import { useAzureFunctions, useSharePointRest, useMicrosoftGraph } from '../../../hooks';
import { SUMMARY_COLUMN_NAME, SITE_PAGES_LIBRARY_NAME } from '../../../constants/constants';
const Summarise: React.FC<ISummariseProps> = (props) => {
const [loading, setLoading] = React.useState<boolean>(true);
const [sentences, setSentences] = React.useState<{ language: string, content: string }[]>([]);
const { aadHttpClientFactory, msGraphClientFactory, spHttpClient, siteId, pageId, siteUrl, pageItemId } = props;
const { getSummaryUsingOpenAI, updatePagePnPPowerShell } = useAzureFunctions(aadHttpClientFactory);
const { callMicrosoftGraphAPI } = useMicrosoftGraph(msGraphClientFactory);
const { getItem } = useSharePointRest(spHttpClient, siteUrl);
const formatSummary = (summary: string[]): void => {
// if summary is empty, return
if (isEmpty(summary)) return;
// if summary is not empty, return the summary by splitting it into sentences
const sentences: { language: string, content: string }[] = [];
summary.forEach((sentence: string) => {
// if the sentence does not contain a language, then the language is empty
if (sentence.indexOf(':') === -1) {
sentences.push({
language: '',
content: `${sentence}.`
});
return;
}
// split the sentence into language and content
// each sentence is in the format language: content
const splitSentence = sentence.split(':');
sentences.push({
language: `${splitSentence[0]}: `,
content: `${splitSentence[1]}.`
});
});
setSentences(sentences);
};
const getPageContent = async (): Promise<string> => {
// get the page content from the Microsoft Graph API
const response = await callMicrosoftGraphAPI(
"get",
`/sites/${siteId}/pages/${pageId}`,
"beta",
null,
["id", "title"],
["webparts($filter=(isof('microsoft.graph.textWebPart')))"],
null
);
return response.webParts.map((webPart: any) => webPart.innerHtml).join(' ');
};
const getSummaryFromAPI = async (): Promise<string[]> => {
let pageContent = await getPageContent();
//remove html tags from the content
pageContent = pageContent.replace(/<[^>]*>?/gm, '');
//replace " with '
pageContent = pageContent.replace(/"/g, "'");
// remove all unicode characters
pageContent = pageContent.replace(/[^\x00-\x7F]/g, "");
// get summary from OpenAI
const summary = await getSummaryUsingOpenAI(pageContent);
// if summary is empty, return
if (summary === undefined || summary === null) {
return [];
}
// update the page with the summary
updatePagePnPPowerShell(siteUrl, pageItemId, SUMMARY_COLUMN_NAME, summary);
// return the summary by splitting it into sentences
return summary.split('.')?.filter((sentence: string) => sentence !== '') || [];
};
const getSummaryFromPage = async (): Promise<string[]> => {
// get the summary from the page
const page = await getItem(SITE_PAGES_LIBRARY_NAME, pageItemId, [SUMMARY_COLUMN_NAME]);
// if page is empty, return
if (page === undefined) {
return [];
}
let summary: string[] = null;
// if summary is not empty, return the summary by splitting it into sentences
if (!isEmpty(page) && !isEmpty(page[SUMMARY_COLUMN_NAME])) {
summary = page[SUMMARY_COLUMN_NAME]?.split('.')?.filter((sentence: string) => sentence !== '') || [];
}
// wait for 1 second before returning the summary to show the loading spinner
await new Promise((resolve) => setTimeout(resolve, 1000));
return summary;
};
const getSummary = async (): Promise<void> => {
let summary: string[] = await getSummaryFromPage();
if (summary === null) {
summary = await getSummaryFromAPI();
}
formatSummary(summary);
};
React.useEffect(() => {
// setTimeout(async () => {
getSummary().then(
() => setLoading(false)
).catch(
(error) => {
console.log("error", error);
setSentences([]);
setLoading(false);
}
);
// }, 200);
}, []);
return (
<div className={summariseStyles.mainContainer}>
<div className={summariseStyles.titleContainer}>
<FontIcon className={summariseStyles.icon} iconName="AlignLeft" />
<span className={summariseStyles.title}>Summary</span>
</div>
{loading ? (
<Spinner size={SpinnerSize.large} label="Loading summary..." styles={loadingSpinnerStyles} />
) : isEmpty(sentences) ? (
<p className={summariseStyles.description}>No summary available</p>
) : (
sentences.map((sentence, index) => (
<p className={summariseStyles.descriptionContainer} key={index}>
<span className={`${summariseStyles.description}`}><span className={summariseStyles.language}>{sentence.language}</span>{sentence.content}</span>
</p>
))
)}
</div>
);
}
export default Summarise;

View File

@ -0,0 +1,77 @@
import { getTheme, FontWeights, AnimationStyles, FontSizes } from '@fluentui/react/lib/Styling';
import { mergeStyleSets } from '@fluentui/merge-styles';
import { NeutralColors, MotionDurations, Depths } from '@fluentui/theme';
import { ISpinnerStyles } from '@fluentui/react/lib/Spinner';
const theme = getTheme();
const ThemeState = (<any>window).__themeState__;
function getThemeColor(slot: string) {
if (ThemeState && ThemeState.theme && ThemeState.theme[slot]) {
return ThemeState.theme[slot];
}
return theme[slot as keyof typeof theme];
}
export const loadingSpinnerStyles: Partial<ISpinnerStyles> = {
root: {
...AnimationStyles.fadeIn200,
animationDuration: MotionDurations.duration4
},
label: {
fontSize: "14px",
fontWeight: 400,
color: NeutralColors.white
}
}
export interface ISummariseStyles {
mainContainer: string;
titleContainer: string;
icon: string;
title: string;
description: string;
descriptionContainer: string;
language: string;
}
export const summariseStyles: ISummariseStyles = mergeStyleSets({
mainContainer: {
...AnimationStyles.slideRightIn400,
animationDuration: MotionDurations.duration4,
backgroundColor: getThemeColor('themePrimary'),
borderLeft: '5px solid ' + getThemeColor('themeDarker'),
color: NeutralColors.white,
padding: '10px',
borderRadius: '5px',
boxShadow: Depths.depth16,
minHeight: '100px'
},
titleContainer: {
display: 'flex',
alignItems: 'center'
},
icon: {
...AnimationStyles.slideRightIn400,
fontSize: FontSizes.xLarge,
fontWeight: FontWeights.regular,
marginRight: '10px'
},
title: {
...AnimationStyles.slideRightIn400,
fontSize: FontSizes.xLarge,
fontWeight: FontWeights.semibold,
marginBottom: '6px'
},
descriptionContainer: {
display: 'flex'
},
description: {
...AnimationStyles.fadeIn500,
fontSize: FontSizes.mediumPlus,
fontWeight: FontWeights.regular,
marginBottom: '10px'
},
language: {
fontWeight: FontWeights.semibold
}
});

View File

@ -0,0 +1,15 @@
define([], function() {
return {
"PropertyPaneDescription": "Description",
"BasicGroupName": "Group Name",
"DescriptionFieldLabel": "Description Field",
"AppLocalEnvironmentSharePoint": "The app is running on your local environment as SharePoint web part",
"AppLocalEnvironmentTeams": "The app is running on your local environment as Microsoft Teams app",
"AppLocalEnvironmentOffice": "The app is running on your local environment in office.com",
"AppLocalEnvironmentOutlook": "The app is running on your local environment in Outlook",
"AppSharePointEnvironment": "The app is running on SharePoint page",
"AppTeamsTabEnvironment": "The app is running in Microsoft Teams",
"AppOfficeEnvironment": "The app is running in office.com",
"AppOutlookEnvironment": "The app is running in Outlook"
}
});

View File

@ -0,0 +1,18 @@
declare interface ISummariseWebPartStrings {
PropertyPaneDescription: string;
BasicGroupName: string;
DescriptionFieldLabel: string;
AppLocalEnvironmentSharePoint: string;
AppLocalEnvironmentTeams: string;
AppLocalEnvironmentOffice: string;
AppLocalEnvironmentOutlook: string;
AppSharePointEnvironment: string;
AppTeamsTabEnvironment: string;
AppOfficeEnvironment: string;
AppOutlookEnvironment: string;
}
declare module 'SummariseWebPartStrings' {
const strings: ISummariseWebPartStrings;
export = strings;
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 542 B

View File

@ -0,0 +1,37 @@
{
"extends": "./node_modules/@microsoft/rush-stack-compiler-4.5/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,
"noImplicitAny": true,
"typeRoots": [
"./node_modules/@types",
"./node_modules/@microsoft"
],
"types": [
"webpack-env"
],
"lib": [
"es5",
"dom",
"es2015.collection",
"es2015.promise",
"ES2016.Array.Include"
]
},
"include": [
"src/**/*.ts",
"src/**/*.tsx"
]
}