@the-vcsi/msgraph 0.0.2 → 0.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,13 +1,21 @@
1
1
  {
2
2
  "name": "@the-vcsi/msgraph",
3
- "version": "0.0.2",
3
+ "version": "0.0.4",
4
4
  "description": "sv CLI add-on for Microsoft Graph / SharePoint integration",
5
5
  "type": "module",
6
6
  "exports": {
7
7
  ".": "./src/index.js"
8
8
  },
9
- "files": ["src"],
10
- "keywords": ["sv-add", "svelte", "sveltekit", "microsoft-graph", "sharepoint"],
9
+ "files": [
10
+ "src"
11
+ ],
12
+ "keywords": [
13
+ "sv-add",
14
+ "svelte",
15
+ "sveltekit",
16
+ "microsoft-graph",
17
+ "sharepoint"
18
+ ],
11
19
  "dependencies": {},
12
20
  "peerDependencies": {
13
21
  "sv": "^0.13.0"
@@ -16,5 +24,8 @@
16
24
  "type": "git",
17
25
  "url": "https://github.com/Vermont-Complex-Systems/vcsi-starter"
18
26
  },
19
- "license": "MIT"
27
+ "license": "MIT",
28
+ "scripts": {
29
+ "test": "node --test test/"
30
+ }
20
31
  }
package/src/index.js CHANGED
@@ -8,6 +8,7 @@ const __dirname = dirname(fileURLToPath(import.meta.url));
8
8
  // Read templates from files (testable, lintable)
9
9
  const FETCH_SCRIPT = readFileSync(join(__dirname, 'templates/fetch-msgraph.js'), 'utf8');
10
10
  const APP_SETTINGS = readFileSync(join(__dirname, 'templates/appSettings.js'), 'utf8');
11
+ const ASSETS_SCRIPT = readFileSync(join(__dirname, 'templates/fetch-assets.js'), 'utf8');
11
12
  const ENV_EXAMPLE = readFileSync(join(__dirname, 'templates/.env.example'), 'utf8');
12
13
 
13
14
  const options = defineAddonOptions()
@@ -17,6 +18,17 @@ const options = defineAddonOptions()
17
18
  })
18
19
  .build();
19
20
 
21
+ // sv.file hands us the file's current contents, or nothing when it does not
22
+ // exist yet. Everything this add-on writes is edited afterwards: appSettings.js
23
+ // carries the siteId, fetch-assets.js carries ASSET_FOLDERS, and either fetch
24
+ // script may be tuned per site. So a re-run must leave an existing file alone.
25
+ //
26
+ // `sv add` scaffolds a project; it does not update one. To adopt a newer
27
+ // version of these scripts, diff this package's templates against your copy and
28
+ // port the change deliberately.
29
+ const keepExisting = (generated) => (content) =>
30
+ content && content.trim() ? content : generated;
31
+
20
32
  export default defineAddon({
21
33
  id: '@the-vcsi/msgraph',
22
34
  shortDescription: 'Microsoft Graph / SharePoint integration for fetching story content',
@@ -24,11 +36,14 @@ export default defineAddon({
24
36
 
25
37
  run: ({ sv, options: opts }) => {
26
38
  // Create the fetch script
27
- sv.file('scripts/fetch-msgraph.js', () => FETCH_SCRIPT);
39
+ sv.file('scripts/fetch-msgraph.js', keepExisting(FETCH_SCRIPT));
40
+
41
+ // Pull binary assets (headshots, logos) out of the same SharePoint site
42
+ sv.file('scripts/fetch-assets.js', keepExisting(ASSETS_SCRIPT));
28
43
 
29
44
  // Create app settings config with user-provided siteId
30
45
  const appSettings = APP_SETTINGS.replace(/__SITE_ID__/g, opts.siteId || 'YOUR_SITE_ID');
31
- sv.file('src/appSettings.js', () => appSettings);
46
+ sv.file('src/appSettings.js', keepExisting(appSettings));
32
47
 
33
48
  // Append to .env.example (or create if doesn't exist)
34
49
  sv.file('.env.example', (content) => {
@@ -43,12 +58,15 @@ export default defineAddon({
43
58
  const pkg = JSON.parse(content);
44
59
  pkg.scripts = pkg.scripts || {};
45
60
  pkg.scripts['fetch:sharepoint'] = 'node scripts/fetch-msgraph.js';
61
+ pkg.scripts['fetch:headshots'] = 'node scripts/fetch-assets.js';
46
62
 
47
63
  // Add required dependencies
48
64
  pkg.dependencies = pkg.dependencies || {};
49
65
  pkg.dependencies['@azure/identity'] = '^4.0.0';
50
66
  pkg.dependencies['@microsoft/microsoft-graph-client'] = '^3.0.0';
51
67
  pkg.dependencies['dotenv'] = '^16.0.0';
68
+ // fetch-assets.js converts SharePoint's .webp to the .jpg the templates request
69
+ pkg.dependencies['sharp'] = '^0.34.5';
52
70
 
53
71
  return JSON.stringify(pkg, null, 2);
54
72
  });
@@ -59,6 +77,8 @@ export default defineAddon({
59
77
  'Copy .env.example to .env',
60
78
  'Get credentials from Azure Portal > App registrations',
61
79
  'Run npm install',
62
- 'Run npm run fetch:sharepoint'
80
+ 'Run npm run fetch:sharepoint to pull story copy',
81
+ 'Run npm run fetch:headshots to pull images (edit ASSET_FOLDERS first)',
82
+ 'Re-running this add-on keeps any of these files you already have'
63
83
  ]
64
84
  });
@@ -0,0 +1,116 @@
1
+ #!/usr/bin/env node
2
+
3
+ import 'dotenv/config';
4
+ import { mkdirSync } from 'fs';
5
+ import { writeFile } from 'fs/promises';
6
+ import { join, dirname, extname, basename } from 'path';
7
+ import { fileURLToPath } from 'url';
8
+ import { ClientSecretCredential } from '@azure/identity';
9
+ import { Client } from '@microsoft/microsoft-graph-client';
10
+ import { TokenCredentialAuthenticationProvider } from '@microsoft/microsoft-graph-client/authProviders/azureTokenCredentials/index.js';
11
+ import sharp from 'sharp';
12
+ import settings from '../src/appSettings.js';
13
+
14
+ const __dirname = dirname(fileURLToPath(import.meta.url));
15
+ const STATIC_DIR = join(__dirname, '..', 'static');
16
+
17
+ // Which SharePoint folders to pull, as { remotePath: localPathUnderStatic }.
18
+ // Edit this for your site: remotePath is relative to the document library root,
19
+ // localPath is relative to static/.
20
+ //
21
+ // Filenames become the local filenames, and .webp is converted to .jpg (the
22
+ // templates' member components request `<member id>.jpg`). So a headshot is
23
+ // only picked up if its filename matches the person's id in members.csv;
24
+ // rename it in SharePoint rather than guessing here.
25
+ const ASSET_FOLDERS = {
26
+ 'assets/headshots': 'common/assets/members',
27
+ };
28
+
29
+ function createClient() {
30
+ const credential = new ClientSecretCredential(
31
+ settings.tenantId || process.env.tenantId,
32
+ settings.clientId || process.env.clientId,
33
+ settings.clientSecret || process.env.clientSecret
34
+ );
35
+
36
+ const authProvider = new TokenCredentialAuthenticationProvider(credential, {
37
+ scopes: settings.scopes,
38
+ });
39
+
40
+ return Client.initWithMiddleware({ authProvider });
41
+ }
42
+
43
+ async function downloadFile(client, driveId, itemId) {
44
+ // Get the download URL and fetch content
45
+ const response = await client
46
+ .api(`/drives/${driveId}/items/${itemId}/content`)
47
+ .responseType('arraybuffer')
48
+ .get();
49
+
50
+ return Buffer.from(response);
51
+ }
52
+
53
+ async function main() {
54
+ const client = createClient();
55
+
56
+ // Get site info
57
+ let site;
58
+ try {
59
+ site = await client.api(`/sites/${settings.siteId}`).get();
60
+ } catch (error) {
61
+ console.error(`Error: ${error.code} - ${error.message}`);
62
+ throw error;
63
+ }
64
+
65
+ console.log(`Site: ${site.webUrl}`);
66
+
67
+ // Get drives
68
+ const drives = await client.api(`/sites/${site.id}/drives`).get();
69
+ const driveId = drives.value[0].id;
70
+
71
+ for (const [remotePath, localPath] of Object.entries(ASSET_FOLDERS)) {
72
+ console.log(`\nSyncing: ${remotePath} -> ${localPath}`);
73
+
74
+ const outputDir = join(STATIC_DIR, localPath);
75
+ mkdirSync(outputDir, { recursive: true });
76
+
77
+ try {
78
+ // Get items in the folder
79
+ const items = await client
80
+ .api(`/drives/${driveId}/root:/${remotePath}:/children`)
81
+ .get();
82
+
83
+ const files = items.value.filter((item) => item.file);
84
+ console.log(`Found ${files.length} file(s)`);
85
+
86
+ for (const file of files) {
87
+ console.log(` Downloading: ${file.name}`);
88
+
89
+ try {
90
+ const content = await downloadFile(client, driveId, file.id);
91
+ const ext = extname(file.name).toLowerCase();
92
+ const name = basename(file.name, ext);
93
+
94
+ // Convert webp to jpg, keep other formats as-is
95
+ if (ext === '.webp') {
96
+ const jpgBuffer = await sharp(content).jpeg({ quality: 90 }).toBuffer();
97
+ const outputName = `${name}.jpg`;
98
+ await writeFile(join(outputDir, outputName), jpgBuffer);
99
+ console.log(` -> ${localPath}/${outputName} (converted from webp)`);
100
+ } else {
101
+ await writeFile(join(outputDir, file.name), content);
102
+ console.log(` -> ${localPath}/${file.name}`);
103
+ }
104
+ } catch (error) {
105
+ console.error(` Error downloading: ${error.message}`);
106
+ }
107
+ }
108
+ } catch (error) {
109
+ console.error(`Error accessing folder: ${error.message}`);
110
+ }
111
+ }
112
+
113
+ console.log('\nDone!');
114
+ }
115
+
116
+ main().catch(console.error);