From 61ec64b4373756f8e14e9902714fc8f12574002b Mon Sep 17 00:00:00 2001 From: oshahid Date: Mon, 16 Nov 2026 19:19:50 +0530 Subject: [PATCH 1/9] feat: add support for linking OneDrive, Teams, and SharePoint folders to topics --- .../collaboration/BrainTopicChangeUtils.java | 10 +- src/prerna/collaboration/BrainTopicLinks.java | 244 ++++++++++++++++++ src/prerna/collaboration/BrainTopicUtils.java | 6 +- .../collaboration/CollaborationDbUtils.java | 4 + .../CollaborationOwlCreator.java | 15 ++ 5 files changed, 276 insertions(+), 3 deletions(-) create mode 100644 src/prerna/collaboration/BrainTopicLinks.java diff --git a/src/prerna/collaboration/BrainTopicChangeUtils.java b/src/prerna/collaboration/BrainTopicChangeUtils.java index c1b11e78ba..a410ffbe1a 100644 --- a/src/prerna/collaboration/BrainTopicChangeUtils.java +++ b/src/prerna/collaboration/BrainTopicChangeUtils.java @@ -77,6 +77,8 @@ public final class BrainTopicChangeUtils { private static final String FOLDER_TOPIC = "BRAIN_TOPIC_FOLDER"; // OneDrive and Teams files linked to the topics; likewise only when there are some private static final String FILE_TOPIC = "BRAIN_TOPIC_FILE"; + // OneDrive, Teams and SharePoint folders linked to the topics + private static final String LINK_TOPIC = "BRAIN_TOPIC_LINK"; // work items linked to the topics; likewise only when there are some private static final String TASK_TOPIC = "WORK_TASK_TOPIC"; // memories linked to the topics, keyed by memory: the rows and every link they have @@ -255,7 +257,7 @@ private static Map undoInReview(User user, String changeId) { + CollaborationDbUtils.placeholders(topicIds.size()) + ")", params(ownerId, ownerType, topicIds)); } - for (String table : List.of(ROOM_TOPIC, FOLDER_TOPIC, TASK_TOPIC, FILE_TOPIC)) { + for (String table : List.of(ROOM_TOPIC, FOLDER_TOPIC, TASK_TOPIC, FILE_TOPIC, LINK_TOPIC)) { CollaborationDbUtils.update(conn, "DELETE FROM " + table + OWNED + " AND TOPIC_ID IN (" + CollaborationDbUtils.placeholders(topicIds.size()) + ")", @@ -355,6 +357,12 @@ private static Map>> scopeRows(Connection conn, if (!files.isEmpty()) { rows.put(FILE_TOPIC, files); } + List> links = readRows(conn, "SELECT * FROM " + LINK_TOPIC + OWNED + + " AND TOPIC_ID IN (" + CollaborationDbUtils.placeholders(topicIds.size()) + + ") ORDER BY TOPIC_ID, LINK_ID", params(ownerId, ownerType, topicIds)); + if (!links.isEmpty()) { + rows.put(LINK_TOPIC, links); + } if (!memoryIds.isEmpty()) { String inMemories = " AND MEMORY_ID IN (" + CollaborationDbUtils.placeholders(memoryIds.size()) + ")"; rows.put(MEMORY, readRows(conn, "SELECT * FROM " + MEMORY + OWNED + inMemories + " ORDER BY MEMORY_ID", diff --git a/src/prerna/collaboration/BrainTopicLinks.java b/src/prerna/collaboration/BrainTopicLinks.java new file mode 100644 index 0000000000..7218793aee --- /dev/null +++ b/src/prerna/collaboration/BrainTopicLinks.java @@ -0,0 +1,244 @@ +/******************************************************************************* + * Copyright 2015 Defense Health Agency (DHA) + * + * If your use of this software does not include any GPLv2 components: + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ---------------------------------------------------------------------------- + * If your use of this software includes any GPLv2 components: + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + *******************************************************************************/ +package prerna.collaboration; + +import java.sql.Connection; +import java.sql.SQLException; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.javatuples.Pair; + +import prerna.auth.User; + +/** Owner-scoped pointers to OneDrive, Teams, or SharePoint folders linked to topics. */ +public final class BrainTopicLinks { + + public static final String DRIVE_FOLDER = "drive_folder"; + public static final String CHANNEL_FILES = "channel_files"; + public static final String SHAREPOINT_FOLDER = "sharepoint_folder"; + public static final String OK = "ok"; + public static final String NO_ACCESS = "no_access"; + + private static final String LOCK = "topic-link"; + private static final String ON_TOPIC = " WHERE OWNER_ID = ? AND OWNER_TYPE = ? AND TOPIC_ID = ?"; + private static final int MAX_DISPLAY_NAME = 255; + + private BrainTopicLinks() { + } + + /** + * Folder identifiers and metadata obtained from Microsoft Graph using the owner's delegated token. + * The caller must validate the folder before saving it. + */ + public record FolderPointer(String kind, String driveId, String itemId, String teamId, String channelId, + String siteId, String displayName, String webUrl) { + + private Identity identity() { + return new Identity(kind, driveId, itemId, teamId, channelId, siteId); + } + } + + private record Identity(String kind, String driveId, String itemId, String teamId, String channelId, + String siteId) { + } + + private record StoredLink(String linkId, FolderPointer folder) { + } + + /** Lists a topic's linked folders, scoped to the signed-in owner. */ + public static List> list(User user, String topicId) { + Pair owner = CollaborationDbUtils.ownerOf(user); + BrainTopicUtils.requireTopic(owner.getValue0(), owner.getValue1(), topicId); + return ofTopic(owner.getValue0(), owner.getValue1(), topicId); + } + + /** Saves a folder pointer after its metadata and access have been verified with Microsoft Graph. */ + public static Map link(User user, String topicId, FolderPointer folder) { + Pair owner = CollaborationDbUtils.ownerOf(user); + String ownerId = owner.getValue0(); + String ownerType = owner.getValue1(); + BrainTopicUtils.requireTopic(ownerId, ownerType, topicId); + folder = validate(topicId, folder); + + String linkId = linkId(ownerId, ownerType, topicId, folder); + synchronized (CollaborationDbUtils.ownerLock(LOCK, ownerId, ownerType)) { + if (!CollaborationDbUtils.exists("SELECT 1 FROM BRAIN_TOPIC_LINK WHERE OWNER_ID = ? AND OWNER_TYPE = ? " + + "AND LINK_ID = ?", ownerId, ownerType, linkId)) { + CollaborationDbUtils.update("INSERT INTO BRAIN_TOPIC_LINK (OWNER_ID, OWNER_TYPE, LINK_ID, TOPIC_ID, " + + "KIND, DRIVE_ID, ITEM_ID, TEAM_ID, CHANNEL_ID, SITE_ID, DISPLAY_NAME, WEB_URL, STATE, " + + "CHECKED_AT) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + ownerId, ownerType, linkId, topicId, folder.kind(), folder.driveId(), folder.itemId(), + folder.teamId(), folder.channelId(), folder.siteId(), clip(folder.displayName(), MAX_DISPLAY_NAME), + folder.webUrl(), OK, CollaborationDbUtils.now()); + } + } + return result(topicId, ofTopic(ownerId, ownerType, topicId)); + } + + /** Removes one of the signed-in owner's links from the specified topic. */ + public static Map unlink(User user, String topicId, String linkId) { + Pair owner = CollaborationDbUtils.ownerOf(user); + String ownerId = owner.getValue0(); + String ownerType = owner.getValue1(); + BrainTopicUtils.requireTopic(ownerId, ownerType, topicId); + requireText(linkId, "A linked folder id is required"); + + CollaborationDbUtils.update("DELETE FROM BRAIN_TOPIC_LINK" + ON_TOPIC + " AND LINK_ID = ?", ownerId, + ownerType, topicId, linkId); + return result(topicId, ofTopic(ownerId, ownerType, topicId)); + } + + /** Records the most recent live access check for a linked folder. */ + public static void updateState(User user, String topicId, String linkId, String state) { + Pair owner = CollaborationDbUtils.ownerOf(user); + String ownerId = owner.getValue0(); + String ownerType = owner.getValue1(); + BrainTopicUtils.requireTopic(ownerId, ownerType, topicId); + requireText(linkId, "A linked folder id is required"); + if (!OK.equals(state) && !NO_ACCESS.equals(state)) { + throw new IllegalArgumentException("Folder state must be ok or no_access"); + } + int updated = CollaborationDbUtils.update("UPDATE BRAIN_TOPIC_LINK SET STATE = ?, CHECKED_AT = ?" + + ON_TOPIC + " AND LINK_ID = ?", state, CollaborationDbUtils.now(), ownerId, ownerType, topicId, + linkId); + if (updated == 0) { + throw new IllegalArgumentException("Linked folder not found"); + } + } + + static List> ofTopic(String ownerId, String ownerType, String topicId) { + return CollaborationDbUtils.query("SELECT LINK_ID, KIND, DRIVE_ID, ITEM_ID, TEAM_ID, CHANNEL_ID, SITE_ID, " + + "DISPLAY_NAME, WEB_URL, STATE, CHECKED_AT FROM BRAIN_TOPIC_LINK" + ON_TOPIC + + " ORDER BY DISPLAY_NAME, LINK_ID", rs -> { + Map link = new LinkedHashMap<>(); + link.put("linkId", rs.getString("LINK_ID")); + link.put("kind", rs.getString("KIND")); + link.put("driveId", rs.getString("DRIVE_ID")); + link.put("itemId", rs.getString("ITEM_ID")); + link.put("teamId", rs.getString("TEAM_ID")); + link.put("channelId", rs.getString("CHANNEL_ID")); + link.put("siteId", rs.getString("SITE_ID")); + link.put("displayName", rs.getString("DISPLAY_NAME")); + link.put("webUrl", CollaborationDbUtils.getString(rs, "WEB_URL")); + link.put("state", rs.getString("STATE")); + link.put("checkedAt", CollaborationDbUtils.getTimestamp(rs, "CHECKED_AT")); + return link; + }, ownerId, ownerType, topicId); + } + + /** Moves source-topic links to the target, retaining the target row for duplicate folder pointers. */ + static void merge(Connection conn, String ownerId, String ownerType, String sourceTopicId, String targetTopicId) + throws SQLException { + List source = links(conn, ownerId, ownerType, sourceTopicId); + Set targetFolders = new HashSet<>(); + for (StoredLink row : links(conn, ownerId, ownerType, targetTopicId)) { + targetFolders.add(row.folder().identity()); + } + + for (StoredLink row : source) { + if (!targetFolders.add(row.folder().identity())) { + CollaborationDbUtils.update(conn, "DELETE FROM BRAIN_TOPIC_LINK WHERE OWNER_ID = ? AND OWNER_TYPE = ? " + + "AND LINK_ID = ?", ownerId, ownerType, row.linkId()); + continue; + } + CollaborationDbUtils.update(conn, "UPDATE BRAIN_TOPIC_LINK SET TOPIC_ID = ?, LINK_ID = ? WHERE OWNER_ID = ? " + + "AND OWNER_TYPE = ? AND LINK_ID = ?", targetTopicId, + linkId(ownerId, ownerType, targetTopicId, row.folder()), ownerId, ownerType, row.linkId()); + } + } + + private static List links(Connection conn, String ownerId, String ownerType, String topicId) + throws SQLException { + return CollaborationDbUtils.query(conn, "SELECT LINK_ID, KIND, DRIVE_ID, ITEM_ID, TEAM_ID, CHANNEL_ID, " + + "SITE_ID, DISPLAY_NAME, WEB_URL FROM BRAIN_TOPIC_LINK" + ON_TOPIC + " ORDER BY LINK_ID", rs -> { + FolderPointer folder = new FolderPointer(rs.getString("KIND"), rs.getString("DRIVE_ID"), + rs.getString("ITEM_ID"), rs.getString("TEAM_ID"), rs.getString("CHANNEL_ID"), + rs.getString("SITE_ID"), rs.getString("DISPLAY_NAME"), + CollaborationDbUtils.getString(rs, "WEB_URL")); + return new StoredLink(rs.getString("LINK_ID"), folder); + }, ownerId, ownerType, topicId); + } + + private static String linkId(String ownerId, String ownerType, String topicId, FolderPointer folder) { + return CollaborationDbUtils.deterministicId(ownerId, ownerType, topicId, folder.kind(), folder.driveId(), + folder.itemId(), folder.teamId(), folder.channelId(), folder.siteId()); + } + + private static FolderPointer validate(String topicId, FolderPointer folder) { + requireText(topicId, "A topic id is required"); + if (folder == null) { + throw new IllegalArgumentException("Folder details are required"); + } + String kind = requireText(folder.kind(), "A folder kind is required"); + String driveId = optionalText(folder.driveId()); + String itemId = optionalText(folder.itemId()); + String teamId = optionalText(folder.teamId()); + String channelId = optionalText(folder.channelId()); + String siteId = optionalText(folder.siteId()); + switch (kind) { + case DRIVE_FOLDER -> { + requireText(driveId, "A drive id is required for a OneDrive folder"); + requireText(itemId, "A folder item id is required"); + } + case CHANNEL_FILES -> { + requireText(teamId, "A team id is required for channel files"); + requireText(channelId, "A channel id is required for channel files"); + } + case SHAREPOINT_FOLDER -> requireText(siteId, "A site id is required for a SharePoint folder"); + default -> throw new IllegalArgumentException("Unsupported folder kind"); + } + return new FolderPointer(kind, driveId, itemId, teamId, channelId, siteId, + requireText(folder.displayName(), "A folder name is required"), optionalText(folder.webUrl())); + } + + private static String optionalText(String value) { + return value == null || value.isBlank() ? null : value.trim(); + } + + private static String requireText(String value, String message) { + if (value == null || value.isBlank()) { + throw new IllegalArgumentException(message); + } + return value.trim(); + } + + private static String clip(String value, int maxLength) { + return value.length() <= maxLength ? value : value.substring(0, maxLength); + } + + private static Map result(String topicId, List> links) { + Map out = new LinkedHashMap<>(); + out.put("topicId", topicId); + out.put("folders", links); + return out; + } +} diff --git a/src/prerna/collaboration/BrainTopicUtils.java b/src/prerna/collaboration/BrainTopicUtils.java index c2e836cd59..2623caa337 100644 --- a/src/prerna/collaboration/BrainTopicUtils.java +++ b/src/prerna/collaboration/BrainTopicUtils.java @@ -451,6 +451,7 @@ private static Map mergeTopicsInReview(User user, String sourceT ownerId, ownerType, sourceTopicId, ownerId, ownerType, targetTopicId); CollaborationDbUtils.update(conn, "UPDATE BRAIN_TOPIC_FILE SET TOPIC_ID = ?" + owned, targetTopicId, ownerId, ownerType, sourceTopicId); + BrainTopicLinks.merge(conn, ownerId, ownerType, sourceTopicId, targetTopicId); // the source's work items are the target's now; one on both keeps the target's link CollaborationDbUtils.update(conn, "DELETE FROM WORK_TASK_TOPIC" + owned + " AND TASK_ID IN (SELECT " + "TASK_ID FROM WORK_TASK_TOPIC WHERE OWNER_ID = ? AND OWNER_TYPE = ? AND TOPIC_ID = ?)", @@ -547,8 +548,9 @@ private static Map deleteTopicInReview(User user, String topicId thread.getValue0()); } } - for (String table : new String[] { "BRAIN_THREAD_TOPIC", "BRAIN_THREAD_TOPIC_REJECTION", "BRAIN_TOPIC_PERSON", "BRAIN_TOPIC_NOTE", - "BRAIN_RULE", "BRAIN_TOPIC_FOLDER", "BRAIN_TOPIC_FILE", "WORK_TASK_TOPIC", "BRAIN_TOPIC" }) { + for (String table : new String[] { "BRAIN_THREAD_TOPIC", "BRAIN_THREAD_TOPIC_REJECTION", + "BRAIN_TOPIC_PERSON", "BRAIN_TOPIC_NOTE", "BRAIN_RULE", "BRAIN_TOPIC_FOLDER", "BRAIN_TOPIC_FILE", + "BRAIN_TOPIC_LINK", "WORK_TASK_TOPIC", "BRAIN_TOPIC" }) { CollaborationDbUtils.update(conn, "DELETE FROM " + table + owned, ownerId, ownerType, topicId); } // memories only about this topic go with it, as its notes did; the others just lose the link diff --git a/src/prerna/collaboration/CollaborationDbUtils.java b/src/prerna/collaboration/CollaborationDbUtils.java index 5a46761bc0..36c0d4bb0d 100644 --- a/src/prerna/collaboration/CollaborationDbUtils.java +++ b/src/prerna/collaboration/CollaborationDbUtils.java @@ -601,6 +601,10 @@ private static void initialize(List>>> db "FOLDER_ID"), OwlIndex.of("BRAIN_TOPIC_FILE_TOPIC_ID_INDEX", "BRAIN_TOPIC_FILE", "OWNER_ID", "OWNER_TYPE", "TOPIC_ID"), + OwlIndex.of("BRAIN_TOPIC_LINK_TOPIC_ID_INDEX", "BRAIN_TOPIC_LINK", "OWNER_ID", "OWNER_TYPE", + "TOPIC_ID"), + OwlIndex.of("BRAIN_TOPIC_LINK_LINK_ID_INDEX", "BRAIN_TOPIC_LINK", "OWNER_ID", "OWNER_TYPE", + "LINK_ID"), OwlIndex.of("BRAIN_MAIL_FOLDER_OWNER_INDEX", "BRAIN_MAIL_FOLDER", "OWNER_ID", "OWNER_TYPE"), // brain: threads diff --git a/src/prerna/collaboration/CollaborationOwlCreator.java b/src/prerna/collaboration/CollaborationOwlCreator.java index 10d352fee8..8a5ab03b73 100644 --- a/src/prerna/collaboration/CollaborationOwlCreator.java +++ b/src/prerna/collaboration/CollaborationOwlCreator.java @@ -296,6 +296,21 @@ public void createColumnsAndTypes(AbstractSqlQueryUtil queryUtil) { // onedrive or teams: the app the owner picked the file in Pair.with("SOURCE", VARCHAR_20), Pair.with("CREATED_AT", TIMESTAMP_DATATYPE_NAME))); + // OneDrive, Teams and SharePoint folders the owner linked to a topic; stores pointers, never contents + addTable("BRAIN_TOPIC_LINK", Arrays.asList( + OWNER_ID, OWNER_TYPE, + Pair.with("LINK_ID", VARCHAR_50), + Pair.with("TOPIC_ID", VARCHAR_50), + Pair.with("KIND", VARCHAR_50), + Pair.with("DRIVE_ID", VARCHAR_255), + Pair.with("ITEM_ID", VARCHAR_255), + Pair.with("TEAM_ID", VARCHAR_255), + Pair.with("CHANNEL_ID", VARCHAR_255), + Pair.with("SITE_ID", VARCHAR_255), + Pair.with("DISPLAY_NAME", VARCHAR_255), + Pair.with("WEB_URL", CLOB_DATATYPE_NAME), + Pair.with("STATE", VARCHAR_20), + Pair.with("CHECKED_AT", TIMESTAMP_DATATYPE_NAME))); // mail Collaboration sent the owner (routine results, notices), by the key import gives it, so import skips it addTable("BRAIN_OWN_MAIL", Arrays.asList( OWNER_ID, OWNER_TYPE, From e8464b58acb917b61719a30cf661790d57efe987 Mon Sep 17 00:00:00 2001 From: oshahid Date: Tue, 17 Nov 2026 11:35:26 +0530 Subject: [PATCH 2/9] feat: implement linking and listing of OneDrive and Teams folders for topics --- src/prerna/collaboration/BrainTopicLinks.java | 217 ++++++++++++++++-- .../collaboration/CollaborationDbUtils.java | 14 ++ .../BrainLinkTopicM365FolderReactor.java | 148 ++++++++++++ .../BrainListTopicM365FoldersReactor.java | 61 +++++ 4 files changed, 427 insertions(+), 13 deletions(-) create mode 100644 src/prerna/reactor/collaboration/BrainLinkTopicM365FolderReactor.java create mode 100644 src/prerna/reactor/collaboration/BrainListTopicM365FoldersReactor.java diff --git a/src/prerna/collaboration/BrainTopicLinks.java b/src/prerna/collaboration/BrainTopicLinks.java index 7218793aee..9e0ccd98bc 100644 --- a/src/prerna/collaboration/BrainTopicLinks.java +++ b/src/prerna/collaboration/BrainTopicLinks.java @@ -29,19 +29,28 @@ import java.sql.Connection; import java.sql.SQLException; +import java.sql.Timestamp; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.javatuples.Pair; import prerna.auth.User; +import prerna.io.connector.ms.MicrosoftLoginUtils; +import prerna.io.connector.ms.onedrive.MicrosoftOneDriveHelper; +import prerna.io.connector.ms.teams.MicrosoftTeamsHelper; +import prerna.sablecc2.om.execptions.SemossPixelException; /** Owner-scoped pointers to OneDrive, Teams, or SharePoint folders linked to topics. */ public final class BrainTopicLinks { + private static final Logger classLogger = LogManager.getLogger(BrainTopicLinks.class); + public static final String DRIVE_FOLDER = "drive_folder"; public static final String CHANNEL_FILES = "channel_files"; public static final String SHAREPOINT_FOLDER = "sharepoint_folder"; @@ -51,6 +60,9 @@ public final class BrainTopicLinks { private static final String LOCK = "topic-link"; private static final String ON_TOPIC = " WHERE OWNER_ID = ? AND OWNER_TYPE = ? AND TOPIC_ID = ?"; private static final int MAX_DISPLAY_NAME = 255; + private static final String INSERT_LINK = "INSERT INTO BRAIN_TOPIC_LINK (OWNER_ID, OWNER_TYPE, LINK_ID, TOPIC_ID, " + + "KIND, DRIVE_ID, ITEM_ID, TEAM_ID, CHANNEL_ID, SITE_ID, DISPLAY_NAME, WEB_URL, STATE, CHECKED_AT) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; private BrainTopicLinks() { } @@ -74,11 +86,43 @@ private record Identity(String kind, String driveId, String itemId, String teamI private record StoredLink(String linkId, FolderPointer folder) { } + private record LinkKey(String ownerId, String ownerType, String linkId) { + } + + private record LinkRow(String topicId, FolderPointer folder, String state, Timestamp checkedAt) { + } + /** Lists a topic's linked folders, scoped to the signed-in owner. */ - public static List> list(User user, String topicId) { + public static Map list(User user, String topicId) { Pair owner = CollaborationDbUtils.ownerOf(user); - BrainTopicUtils.requireTopic(owner.getValue0(), owner.getValue1(), topicId); - return ofTopic(owner.getValue0(), owner.getValue1(), topicId); + String ownerId = owner.getValue0(); + String ownerType = owner.getValue1(); + BrainTopicUtils.requireTopic(ownerId, ownerType, topicId); + List> links = ofTopic(ownerId, ownerType, topicId); + if (links.stream().anyMatch(BrainTopicLinks::isLiveMicrosoftFolder)) { + String accessToken = accessToken(user); + for (Map link : links) { + if (!isLiveMicrosoftFolder(link)) { + continue; + } + String linkId = String.valueOf(link.get("linkId")); + try { + String state = isAccessible(accessToken, link) ? OK : NO_ACCESS; + updateState(user, topicId, linkId, state); + } catch (Exception e) { + if (isUnavailable(e)) { + classLogger.warn("Microsoft folder link {} is no longer available: {}", linkId, + e.getMessage()); + updateState(user, topicId, linkId, NO_ACCESS); + } else { + throw new SemossPixelException("Could not check access to linked Microsoft folder " + + link.get("displayName") + ": " + e.getMessage()); + } + } + } + links = ofTopic(ownerId, ownerType, topicId); + } + return result(topicId, links); } /** Saves a folder pointer after its metadata and access have been verified with Microsoft Graph. */ @@ -91,14 +135,22 @@ public static Map link(User user, String topicId, FolderPointer String linkId = linkId(ownerId, ownerType, topicId, folder); synchronized (CollaborationDbUtils.ownerLock(LOCK, ownerId, ownerType)) { - if (!CollaborationDbUtils.exists("SELECT 1 FROM BRAIN_TOPIC_LINK WHERE OWNER_ID = ? AND OWNER_TYPE = ? " + if (CollaborationDbUtils.exists("SELECT 1 FROM BRAIN_TOPIC_LINK WHERE OWNER_ID = ? AND OWNER_TYPE = ? " + "AND LINK_ID = ?", ownerId, ownerType, linkId)) { - CollaborationDbUtils.update("INSERT INTO BRAIN_TOPIC_LINK (OWNER_ID, OWNER_TYPE, LINK_ID, TOPIC_ID, " - + "KIND, DRIVE_ID, ITEM_ID, TEAM_ID, CHANNEL_ID, SITE_ID, DISPLAY_NAME, WEB_URL, STATE, " - + "CHECKED_AT) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", - ownerId, ownerType, linkId, topicId, folder.kind(), folder.driveId(), folder.itemId(), - folder.teamId(), folder.channelId(), folder.siteId(), clip(folder.displayName(), MAX_DISPLAY_NAME), - folder.webUrl(), OK, CollaborationDbUtils.now()); + if (refreshLink(ownerId, ownerType, topicId, linkId, folder) == 0) { + insertLink(ownerId, ownerType, topicId, linkId, folder); + } + } else { + try { + insertLink(ownerId, ownerType, topicId, linkId, folder); + } catch (IllegalStateException e) { + if (!isUniqueConstraintViolation(e) + || !CollaborationDbUtils.exists("SELECT 1 FROM BRAIN_TOPIC_LINK WHERE OWNER_ID = ? " + + "AND OWNER_TYPE = ? AND LINK_ID = ?", ownerId, ownerType, linkId) + || refreshLink(ownerId, ownerType, topicId, linkId, folder) == 0) { + throw e; + } + } } } return result(topicId, ofTopic(ownerId, ownerType, topicId)); @@ -127,14 +179,153 @@ public static void updateState(User user, String topicId, String linkId, String if (!OK.equals(state) && !NO_ACCESS.equals(state)) { throw new IllegalArgumentException("Folder state must be ok or no_access"); } - int updated = CollaborationDbUtils.update("UPDATE BRAIN_TOPIC_LINK SET STATE = ?, CHECKED_AT = ?" - + ON_TOPIC + " AND LINK_ID = ?", state, CollaborationDbUtils.now(), ownerId, ownerType, topicId, - linkId); + int updated = updateState(ownerId, ownerType, topicId, linkId, state); if (updated == 0) { throw new IllegalArgumentException("Linked folder not found"); } } + private static int updateState(String ownerId, String ownerType, String topicId, String linkId, String state) { + return CollaborationDbUtils.update("UPDATE BRAIN_TOPIC_LINK SET STATE = ?, CHECKED_AT = ?" + ON_TOPIC + + " AND LINK_ID = ?", state, CollaborationDbUtils.now(), ownerId, ownerType, topicId, linkId); + } + + private static boolean isLiveMicrosoftFolder(Map link) { + Object kind = link.get("kind"); + return DRIVE_FOLDER.equals(kind) || CHANNEL_FILES.equals(kind); + } + + private static String accessToken(User user) { + try { + return MicrosoftLoginUtils.getValidAccessToken(user); + } catch (SemossPixelException e) { + throw e; + } catch (Exception e) { + throw new SemossPixelException("Could not retrieve a Microsoft access token: " + e.getMessage()); + } + } + + private static boolean isAccessible(String accessToken, Map link) throws Exception { + String kind = String.valueOf(link.get("kind")); + if (DRIVE_FOLDER.equals(kind)) { + Map item = MicrosoftOneDriveHelper.getItem(accessToken, + String.valueOf(link.get("driveId")), String.valueOf(link.get("itemId")), null); + return Boolean.TRUE.equals(item.get("isFolder")); + } + if (CHANNEL_FILES.equals(kind)) { + MicrosoftTeamsHelper.getChannelFilesFolder(accessToken, String.valueOf(link.get("teamId")), + String.valueOf(link.get("channelId"))); + return true; + } + return false; + } + + private static boolean isUnavailable(Throwable error) { + for (Throwable cause = error; cause != null; cause = cause.getCause()) { + String message = cause.getMessage(); + if (message != null + && (message.contains(" returned HTTP 403") || message.contains(" returned HTTP 404"))) { + return true; + } + } + return false; + } + + private static void insertLink(String ownerId, String ownerType, String topicId, String linkId, + FolderPointer folder) { + insertLink(ownerId, ownerType, linkId, topicId, folder, OK, CollaborationDbUtils.now()); + } + + private static void insertLink(String ownerId, String ownerType, String linkId, String topicId, + FolderPointer folder, String state, Timestamp checkedAt) { + CollaborationDbUtils.update(INSERT_LINK, + ownerId, ownerType, linkId, topicId, folder.kind(), folder.driveId(), folder.itemId(), folder.teamId(), + folder.channelId(), folder.siteId(), clip(folder.displayName(), MAX_DISPLAY_NAME), folder.webUrl(), + state, checkedAt); + } + + private static void insertLink(Connection conn, String ownerId, String ownerType, String linkId, String topicId, + FolderPointer folder, String state, Timestamp checkedAt) throws SQLException { + CollaborationDbUtils.update(conn, INSERT_LINK, ownerId, ownerType, linkId, topicId, folder.kind(), + folder.driveId(), folder.itemId(), folder.teamId(), folder.channelId(), folder.siteId(), + clip(folder.displayName(), MAX_DISPLAY_NAME), folder.webUrl(), state, checkedAt); + } + + private static int refreshLink(String ownerId, String ownerType, String topicId, String linkId, + FolderPointer folder) { + return CollaborationDbUtils.update("UPDATE BRAIN_TOPIC_LINK SET TOPIC_ID = ?, KIND = ?, DRIVE_ID = ?, " + + "ITEM_ID = ?, TEAM_ID = ?, CHANNEL_ID = ?, SITE_ID = ?, DISPLAY_NAME = ?, WEB_URL = ?, STATE = ?, " + + "CHECKED_AT = ?" + ON_TOPIC + " AND LINK_ID = ?", topicId, folder.kind(), folder.driveId(), + folder.itemId(), folder.teamId(), folder.channelId(), folder.siteId(), + clip(folder.displayName(), MAX_DISPLAY_NAME), folder.webUrl(), OK, CollaborationDbUtils.now(), + ownerId, ownerType, topicId, linkId); + } + + private static boolean isUniqueConstraintViolation(Throwable error) { + for (Throwable cause = error; cause != null; cause = cause.getCause()) { + if (cause instanceof SQLException sqlException && sqlException.getSQLState() != null + && sqlException.getSQLState().startsWith("23")) { + return true; + } + } + return false; + } + + /** Consolidates duplicate link ids created before the unique database index is installed. */ + static void deduplicate(Connection conn) throws SQLException { + List duplicates = CollaborationDbUtils.query(conn, "SELECT OWNER_ID, OWNER_TYPE, LINK_ID " + + "FROM BRAIN_TOPIC_LINK GROUP BY OWNER_ID, OWNER_TYPE, LINK_ID HAVING COUNT(*) > 1", + rs -> new LinkKey(rs.getString("OWNER_ID"), rs.getString("OWNER_TYPE"), rs.getString("LINK_ID"))); + if (duplicates.isEmpty()) { + return; + } + + boolean autoCommit = conn.getAutoCommit(); + if (autoCommit) { + conn.setAutoCommit(false); + } + try { + for (LinkKey key : duplicates) { + List rows = CollaborationDbUtils.query(conn, "SELECT TOPIC_ID, KIND, DRIVE_ID, ITEM_ID, " + + "TEAM_ID, CHANNEL_ID, SITE_ID, DISPLAY_NAME, WEB_URL, STATE, CHECKED_AT " + + "FROM BRAIN_TOPIC_LINK WHERE OWNER_ID = ? AND OWNER_TYPE = ? AND LINK_ID = ?", + rs -> new LinkRow(rs.getString("TOPIC_ID"), + new FolderPointer(rs.getString("KIND"), rs.getString("DRIVE_ID"), + rs.getString("ITEM_ID"), rs.getString("TEAM_ID"), rs.getString("CHANNEL_ID"), + rs.getString("SITE_ID"), rs.getString("DISPLAY_NAME"), + CollaborationDbUtils.getString(rs, "WEB_URL")), + rs.getString("STATE"), rs.getTimestamp("CHECKED_AT")), + key.ownerId(), key.ownerType(), key.linkId()); + if (rows.size() < 2) { + continue; + } + LinkRow latest = rows.get(0); + for (LinkRow row : rows) { + if (row.checkedAt() != null + && (latest.checkedAt() == null || row.checkedAt().after(latest.checkedAt()))) { + latest = row; + } + } + CollaborationDbUtils.update(conn, "DELETE FROM BRAIN_TOPIC_LINK WHERE OWNER_ID = ? AND OWNER_TYPE = ? " + + "AND LINK_ID = ?", key.ownerId(), key.ownerType(), key.linkId()); + insertLink(conn, key.ownerId(), key.ownerType(), key.linkId(), latest.topicId(), latest.folder(), + latest.state(), latest.checkedAt()); + } + if (autoCommit) { + conn.commit(); + } + } catch (SQLException | RuntimeException e) { + if (autoCommit) { + conn.rollback(); + } + throw e; + } finally { + if (autoCommit) { + conn.setAutoCommit(true); + } + } + } + static List> ofTopic(String ownerId, String ownerType, String topicId) { return CollaborationDbUtils.query("SELECT LINK_ID, KIND, DRIVE_ID, ITEM_ID, TEAM_ID, CHANNEL_ID, SITE_ID, " + "DISPLAY_NAME, WEB_URL, STATE, CHECKED_AT FROM BRAIN_TOPIC_LINK" + ON_TOPIC diff --git a/src/prerna/collaboration/CollaborationDbUtils.java b/src/prerna/collaboration/CollaborationDbUtils.java index 36c0d4bb0d..f3757cbb9f 100644 --- a/src/prerna/collaboration/CollaborationDbUtils.java +++ b/src/prerna/collaboration/CollaborationDbUtils.java @@ -546,6 +546,20 @@ private static void initialize(List>>> db } } } + // Link ids are deterministic, and the database constraint closes the race between server instances. + BrainTopicLinks.deduplicate(conn); + String topicLinkIndex = "BRAIN_TOPIC_LINK_LINK_UNIQUE"; + if (queryUtil.allowIfExistsIndexSyntax() || !queryUtil.indexExists(collaborationDb, topicLinkIndex, + "BRAIN_TOPIC_LINK", collaborationDb.getDatabase(), collaborationDb.getSchema())) { + String sql = queryUtil.allowIfExistsIndexSyntax() + ? queryUtil.createIndexIfNotExists(topicLinkIndex, "BRAIN_TOPIC_LINK", + List.of("OWNER_ID", "OWNER_TYPE", "LINK_ID")) + : queryUtil.createIndex(topicLinkIndex, "BRAIN_TOPIC_LINK", + List.of("OWNER_ID", "OWNER_TYPE", "LINK_ID")); + try (Statement statement = conn.createStatement()) { + statement.execute(sql.replaceFirst("(?i)CREATE INDEX", "CREATE UNIQUE INDEX")); + } + } // syncSchema only adds columns; a role defaults to the job title (VARCHAR 255) widenColumn(collaborationDb, conn, "BRAIN_TOPIC_PERSON", "ROLE_LABEL", 255); // a topic's short name defaults to its name (VARCHAR 255) diff --git a/src/prerna/reactor/collaboration/BrainLinkTopicM365FolderReactor.java b/src/prerna/reactor/collaboration/BrainLinkTopicM365FolderReactor.java new file mode 100644 index 0000000000..0e936d1161 --- /dev/null +++ b/src/prerna/reactor/collaboration/BrainLinkTopicM365FolderReactor.java @@ -0,0 +1,148 @@ +/******************************************************************************* + * Copyright 2015 Defense Health Agency (DHA) + * + * If your use of this software does not include any GPLv2 components: + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ---------------------------------------------------------------------------- + * If your use of this software includes any GPLv2 components: + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + *******************************************************************************/ +package prerna.reactor.collaboration; + +import java.util.Map; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import prerna.auth.User; +import prerna.collaboration.BrainTopicLinks; +import prerna.collaboration.BrainTopicLinks.FolderPointer; +import prerna.io.connector.ms.MicrosoftLoginUtils; +import prerna.io.connector.ms.onedrive.MicrosoftOneDriveHelper; +import prerna.io.connector.ms.onedrive.MicrosoftOneDriveItemMapper; +import prerna.io.connector.ms.teams.MicrosoftTeamsHelper; +import prerna.reactor.ReactorDefinition; +import prerna.sablecc2.om.execptions.SemossPixelException; +import prerna.sablecc2.om.nounmeta.NounMetadata; +import prerna.util.ValueUtils; + +// BrainLinkTopicM365Folder(topicId=["..."], kind=["drive_folder"], driveId=["..."], itemId=["..."]); +public class BrainLinkTopicM365FolderReactor extends AbstractCollaborationReactor { + + private static final Logger classLogger = LogManager.getLogger(BrainLinkTopicM365FolderReactor.class); + + private static final String TOPIC_ID = "topicId"; + private static final String KIND = "kind"; + private static final String DRIVE_ID = "driveId"; + private static final String ITEM_ID = "itemId"; + private static final String TEAM_ID = "teamId"; + private static final String CHANNEL_ID = "channelId"; + private static final String LINK_ID = "linkId"; + private static final String REMOVE = "remove"; + + public BrainLinkTopicM365FolderReactor() { + this.keysToGet = new String[] { TOPIC_ID, KIND, DRIVE_ID, ITEM_ID, TEAM_ID, CHANNEL_ID, LINK_ID, REMOVE }; + this.keyRequired = new int[] { 1, 0, 0, 0, 0, 0, 0, 0 }; + } + + @Override + public NounMetadata execute() { + User user = getUser(); + String topicId = getStringFromKeyOrCurRow(TOPIC_ID); + if (Boolean.TRUE.equals(getBoolean(REMOVE))) { + return mapResult(BrainTopicLinks.unlink(user, topicId, getString(LINK_ID))); + } + + String kind = ValueUtils.trimToNull(getString(KIND)); + if (kind == null) { + throw new IllegalArgumentException("A folder kind is required"); + } + try { + String accessToken = MicrosoftLoginUtils.getValidAccessToken(user); + FolderPointer folder = resolveFolder(accessToken, kind); + return mapResult(BrainTopicLinks.link(user, topicId, folder)); + } catch (SemossPixelException e) { + classLogger.error("Could not get a Microsoft token to link a topic folder", e); + throw e; + } catch (IllegalArgumentException e) { + classLogger.error("Invalid input while linking a Microsoft folder to a topic", e); + throw e; + } catch (Exception e) { + classLogger.error("Could not verify a Microsoft folder for a topic link", e); + throw new SemossPixelException("Could not verify folder access in Microsoft 365: " + e.getMessage()); + } + } + + private FolderPointer resolveFolder(String accessToken, String kind) throws Exception { + if (BrainTopicLinks.DRIVE_FOLDER.equals(kind)) { + String driveId = ValueUtils.trimToNull(getString(DRIVE_ID)); + String itemId = ValueUtils.trimToNull(getString(ITEM_ID)); + if (driveId == null || itemId == null) { + throw new IllegalArgumentException("A drive id and item id are required for a OneDrive folder"); + } + Map item = MicrosoftOneDriveHelper.getItem(accessToken, driveId, itemId, null); + if (!Boolean.TRUE.equals(item.get("isFolder"))) { + throw new IllegalArgumentException("The selected OneDrive item is not a folder"); + } + String resolvedDriveId = ValueUtils.toNonBlankString(item.get("driveId")); + if (resolvedDriveId == null) { + resolvedDriveId = driveId; + } + String resolvedItemId = MicrosoftOneDriveItemMapper.itemIdOf(item); + return new FolderPointer(kind, resolvedDriveId, resolvedItemId, null, null, null, + MicrosoftOneDriveItemMapper.nameOf(item), string(item, "webUrl")); + } + if (BrainTopicLinks.CHANNEL_FILES.equals(kind)) { + String teamId = ValueUtils.trimToNull(getString(TEAM_ID)); + String channelId = ValueUtils.trimToNull(getString(CHANNEL_ID)); + if (teamId == null || channelId == null) { + throw new IllegalArgumentException("A team id and channel id are required for Teams channel files"); + } + Map folder = MicrosoftTeamsHelper.getChannelFilesFolder(accessToken, teamId, channelId); + return new FolderPointer(kind, string(folder, "driveId"), string(folder, "folderId"), teamId, channelId, + null, string(folder, "name"), string(folder, "webUrl")); + } + if (BrainTopicLinks.SHAREPOINT_FOLDER.equals(kind)) { + throw new IllegalArgumentException("SharePoint folder linking is not available in this operation"); + } + throw new IllegalArgumentException("Unsupported folder kind"); + } + + private static String string(Map values, String key) { + return ValueUtils.toNonBlankString(values.get(key)); + } + + @Override + public ReactorDefinition getReactorDefinition() { + return super.getReactorDefinition() + .description("Links a OneDrive folder or Teams channel's Files folder to a topic after checking it " + + "with the owner's Microsoft account; set remove to true with linkId to unlink it.") + .key(TOPIC_ID, "Topic id") + .key(KIND, "Folder kind: drive_folder for OneDrive or channel_files for Teams") + .key(DRIVE_ID, "Microsoft drive id of a OneDrive folder") + .key(ITEM_ID, "Microsoft item id of a OneDrive folder") + .key(TEAM_ID, "Microsoft Teams team id that owns the channel") + .key(CHANNEL_ID, "Microsoft Teams channel id whose Files folder should be linked") + .key(LINK_ID, "Linked folder id, required when removing a link") + .key(REMOVE, "true removes the existing link instead of creating one") + .output(Map.class, "The topic id and its linked OneDrive and Teams folders"); + } +} diff --git a/src/prerna/reactor/collaboration/BrainListTopicM365FoldersReactor.java b/src/prerna/reactor/collaboration/BrainListTopicM365FoldersReactor.java new file mode 100644 index 0000000000..f1c81fa91b --- /dev/null +++ b/src/prerna/reactor/collaboration/BrainListTopicM365FoldersReactor.java @@ -0,0 +1,61 @@ +/******************************************************************************* + * Copyright 2015 Defense Health Agency (DHA) + * + * If your use of this software does not include any GPLv2 components: + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ---------------------------------------------------------------------------- + * If your use of this software includes any GPLv2 components: + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + *******************************************************************************/ +package prerna.reactor.collaboration; + +import java.util.Map; + +import prerna.auth.User; +import prerna.collaboration.BrainTopicLinks; +import prerna.reactor.ReactorDefinition; +import prerna.sablecc2.om.nounmeta.NounMetadata; + +// BrainListTopicM365Folders(topicId=["..."]); +public class BrainListTopicM365FoldersReactor extends AbstractCollaborationReactor { + + private static final String TOPIC_ID = "topicId"; + + public BrainListTopicM365FoldersReactor() { + this.keysToGet = new String[] { TOPIC_ID }; + this.keyRequired = new int[] { 1 }; + } + + @Override + public NounMetadata execute() { + User user = getUser(); + String topicId = getStringFromKeyOrCurRow(TOPIC_ID); + return mapResult(BrainTopicLinks.list(user, topicId)); + } + + @Override + public ReactorDefinition getReactorDefinition() { + return super.getReactorDefinition() + .description("Lists the OneDrive and Teams folders linked to a topic, including their access state.") + .key(TOPIC_ID, "Topic id") + .output(Map.class, "The topic id and its linked folders"); + } +} From f769f092df10102c247923ef7611b753204e5775 Mon Sep 17 00:00:00 2001 From: oshahid Date: Tue, 17 Nov 2026 14:18:37 +0530 Subject: [PATCH 3/9] feat: add functionality to link and apply Microsoft 365 folder defaults for topics --- src/prerna/collaboration/BrainTopicBrief.java | 33 ++++++++ .../CollaborationAgentTools.java | 81 +++++++++++++++++++ 2 files changed, 114 insertions(+) diff --git a/src/prerna/collaboration/BrainTopicBrief.java b/src/prerna/collaboration/BrainTopicBrief.java index 29d3fbcfb2..3b7706f739 100644 --- a/src/prerna/collaboration/BrainTopicBrief.java +++ b/src/prerna/collaboration/BrainTopicBrief.java @@ -179,6 +179,7 @@ private static String topic(User user, String ownerId, String ownerType, String classLogger.warn("Could not count the threads of topic {} for the brief", topicId, e); } out.append(BrainTopicFiles.brief(ownerId, ownerType, topicId)); + out.append(linkedFoldersBrief(ownerId, ownerType, topicId)); // the topic's work items, each with the owner's next step or who they wait on List> items = new ArrayList<>(); for (Object o : (List) WorkTaskUtils.listMyWork(user, Map.of("topicId", topicId)).get("workItems")) { @@ -245,4 +246,36 @@ static List> openItems(String ownerId, String ownerType, Str private static String clip(String text, int max) { return text.length() <= max ? text : text.substring(0, max - 3) + "..."; } + + private static String linkedFoldersBrief(String ownerId, String ownerType, String topicId) { + List> links = BrainTopicLinks.ofTopic(ownerId, ownerType, topicId); + if (links.isEmpty()) { + return ""; + } + StringBuilder out = new StringBuilder( + "\nLinked Microsoft 365 folders: the agent lists and reads files from these by default. " + + "To list files, call ListDriveFiles for a OneDrive link, or ListChannelFiles for Teams. " + + "Availability is marked 'ok' or 'unavailable' (access lost):"); + for (Map link : links.subList(0, Math.min(links.size(), MAX_ITEMS))) { + out.append("\n- ").append(BrainThreadBrief.neutral(String.valueOf(link.get("displayName")))) + .append(" ("); + String state = String.valueOf(link.get("state")); + out.append(state); + if ("ok".equals(state)) { + String kind = String.valueOf(link.get("kind")); + if ("drive_folder".equals(kind)) { + out.append(", driveId ").append(link.get("driveId")).append(", itemId ") + .append(link.get("itemId")); + } else if ("channel_files".equals(kind)) { + out.append(", teamId ").append(link.get("teamId")).append(", channelId ") + .append(link.get("channelId")); + } + } + out.append(")"); + } + if (links.size() > MAX_ITEMS) { + out.append("\nAnd ").append(links.size() - MAX_ITEMS).append(" more, listed on the topic's page."); + } + return out.toString(); + } } diff --git a/src/prerna/collaboration/CollaborationAgentTools.java b/src/prerna/collaboration/CollaborationAgentTools.java index b932a06cda..845838fdb8 100644 --- a/src/prerna/collaboration/CollaborationAgentTools.java +++ b/src/prerna/collaboration/CollaborationAgentTools.java @@ -410,6 +410,7 @@ public static ToolExecutionResult execute(String toolName, Map p params = params == null ? new LinkedHashMap<>() : new LinkedHashMap<>(params); params.put("timeZone", BrainProfileUtils.timeZone(insight.getUser()).getId()); } + applyTopicFolderDefaults(toolName, params, insight.getUser(), insight); String output = MCPUtility.runPixelTool(null, insight, meta.getString(MCPUtility.SMSS_FUNCTION_NAME), properties, params); return ToolExecutionResult.success(CollaborationToolResults.forModel(toolName, output, insight.getUser(), @@ -420,6 +421,86 @@ public static ToolExecutionResult execute(String toolName, Map p } } + private static void applyTopicFolderDefaults(String toolName, Map params, User user, + Insight insight) { + if (params == null || user == null || insight == null) { + return; + } + if (!("ListDriveFiles".equals(toolName) || "SearchFiles".equals(toolName) + || "ListChannelFiles".equals(toolName))) { + return; + } + + try { + String roomId = insight.getRoomId(); + if (roomId == null || roomId.isBlank()) { + return; + } + + List topicIds = BrainTopicBrief.chatTopics(user, roomId); + if (topicIds.isEmpty()) { + return; + } + + if ("ListDriveFiles".equals(toolName) || "SearchFiles".equals(toolName)) { + applyOneDriveFolderDefaults(params, user, topicIds); + } else if ("ListChannelFiles".equals(toolName)) { + applyTeamsFolderDefaults(params, user, topicIds); + } + } catch (RuntimeException e) { + classLogger.debug("Could not apply topic folder defaults for tool {}: {}", toolName, e.getMessage()); + } + } + + private static void applyOneDriveFolderDefaults(Map params, User user, List topicIds) { + if (params.containsKey("driveId") && !String.valueOf(params.get("driveId")).isBlank()) { + return; + } + + for (String topicId : topicIds) { + List> links = BrainTopicLinks.ofTopic(CollaborationDbUtils.ownerOf(user).getValue0(), + CollaborationDbUtils.ownerOf(user).getValue1(), topicId); + for (Map link : links) { + String kind = String.valueOf(link.get("kind")); + String state = String.valueOf(link.get("state")); + if ("drive_folder".equals(kind) && "ok".equals(state)) { + String driveId = String.valueOf(link.get("driveId")); + String itemId = String.valueOf(link.get("itemId")); + if (driveId != null && !driveId.isBlank() && itemId != null && !itemId.isBlank()) { + params.putIfAbsent("driveId", driveId); + params.putIfAbsent("itemId", itemId); + return; + } + } + } + } + } + + private static void applyTeamsFolderDefaults(Map params, User user, List topicIds) { + if ((params.containsKey("teamId") && !String.valueOf(params.get("teamId")).isBlank()) + && (params.containsKey("channelId") && !String.valueOf(params.get("channelId")).isBlank())) { + return; + } + + for (String topicId : topicIds) { + List> links = BrainTopicLinks.ofTopic(CollaborationDbUtils.ownerOf(user).getValue0(), + CollaborationDbUtils.ownerOf(user).getValue1(), topicId); + for (Map link : links) { + String kind = String.valueOf(link.get("kind")); + String state = String.valueOf(link.get("state")); + if ("channel_files".equals(kind) && "ok".equals(state)) { + String teamId = String.valueOf(link.get("teamId")); + String channelId = String.valueOf(link.get("channelId")); + if (teamId != null && !teamId.isBlank() && channelId != null && !channelId.isBlank()) { + params.putIfAbsent("teamId", teamId); + params.putIfAbsent("channelId", channelId); + return; + } + } + } + } + } + private static String selectedEmailId(String input) { String header = "[SEMOSS_WORK_CONTEXT_V1]\n"; String error = "No selected email is available in the current request. Select an included email or pass its exact id. " From 17cafe778d1ab2a7546aca66be703e7db4063608 Mon Sep 17 00:00:00 2001 From: oshahid Date: Tue, 17 Nov 2026 19:12:13 +0530 Subject: [PATCH 4/9] feat: add reactors for linking and listing M365 folders to topics --- src/prerna/collaboration/CollaborationAgentTools.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/prerna/collaboration/CollaborationAgentTools.java b/src/prerna/collaboration/CollaborationAgentTools.java index 845838fdb8..4870cb1dc9 100644 --- a/src/prerna/collaboration/CollaborationAgentTools.java +++ b/src/prerna/collaboration/CollaborationAgentTools.java @@ -82,6 +82,8 @@ import prerna.reactor.collaboration.BrainGetThreadMessagesReactor; import prerna.reactor.collaboration.BrainGetWritingStyleReactor; import prerna.reactor.collaboration.BrainListTopicsReactor; +import prerna.reactor.collaboration.BrainListTopicM365FoldersReactor; +import prerna.reactor.collaboration.BrainLinkTopicM365FolderReactor; import prerna.reactor.collaboration.BrainRememberReactor; import prerna.reactor.collaboration.BrainSearchMemoriesReactor; import prerna.reactor.collaboration.BrainSearchThreadsReactor; @@ -154,6 +156,9 @@ public final class CollaborationAgentTools { // tags the chat it runs in with a topic; no approval, the owner can undo or // dismiss it REACTORS.put("TagTopic", BrainTagTopicReactor.class); + // link and list M365 folders to topics + REACTORS.put("ListTopicM365Folders", BrainListTopicM365FoldersReactor.class); + REACTORS.put("LinkTopicM365Folder", BrainLinkTopicM365FolderReactor.class); // then Outlook directly, for what Brain does not hold; Brain's rules do not // apply to it REACTORS.put("ListM365Mail", MicrosoftOutlookListMailReactor.class); From d291ed694c78a1aa6a8b813b4923bd4904f70416 Mon Sep 17 00:00:00 2001 From: oshahid Date: Wed, 18 Nov 2026 18:21:29 +0530 Subject: [PATCH 5/9] feat: implement fixture mode for Microsoft Teams and OneDrive integration --- .../ms/AbstractMicrosoftReactor.java | 14 +- .../ms/onedrive/MicrosoftOneDriveHelper.java | 120 ++++++++++++++ .../onedrive/MicrosoftOneDriveItemMapper.java | 9 +- .../MicrosoftOneDriveListFilesReactor.java | 10 ++ .../ms/teams/MicrosoftTeamsHelper.java | 152 ++++++++++++++++++ .../MicrosoftTeamsListChannelsReactor.java | 17 +- .../teams/MicrosoftTeamsListFilesReactor.java | 18 ++- .../teams/MicrosoftTeamsListTeamsReactor.java | 17 +- .../BrainLinkTopicM365FolderReactor.java | 22 ++- 9 files changed, 368 insertions(+), 11 deletions(-) diff --git a/src/prerna/io/connector/ms/AbstractMicrosoftReactor.java b/src/prerna/io/connector/ms/AbstractMicrosoftReactor.java index fe7f8a9d1a..82e58feef4 100644 --- a/src/prerna/io/connector/ms/AbstractMicrosoftReactor.java +++ b/src/prerna/io/connector/ms/AbstractMicrosoftReactor.java @@ -28,11 +28,13 @@ package prerna.io.connector.ms; import prerna.auth.AuthProvider; +import prerna.auth.AccessToken; import prerna.io.connector.AbstractConnectorReactor; +import prerna.io.connector.ms.onedrive.MicrosoftOneDriveHelper; /** * Checks the user's Microsoft login before validating inputs or calling the - * provider. + * provider. In fixture mode, skips login requirement. */ public abstract class AbstractMicrosoftReactor extends AbstractConnectorReactor { @@ -40,4 +42,14 @@ public abstract class AbstractMicrosoftReactor extends AbstractConnectorReactor protected final AuthProvider getAuthProvider() { return AuthProvider.MICROSOFT; } + + @Override + protected AccessToken requireLogin(AuthProvider provider) { + // In fixture mode, skip login requirement and return a dummy token + if (MicrosoftOneDriveHelper.fixturePath() != null) { + return new AccessToken(); + } + // Otherwise, proceed with normal login check + return super.requireLogin(provider); + } } diff --git a/src/prerna/io/connector/ms/onedrive/MicrosoftOneDriveHelper.java b/src/prerna/io/connector/ms/onedrive/MicrosoftOneDriveHelper.java index 3be2ff8e03..76c272171f 100644 --- a/src/prerna/io/connector/ms/onedrive/MicrosoftOneDriveHelper.java +++ b/src/prerna/io/connector/ms/onedrive/MicrosoftOneDriveHelper.java @@ -31,6 +31,7 @@ import java.io.File; import java.io.FileInputStream; import java.io.InputStream; +import java.io.Reader; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.nio.file.Files; @@ -51,6 +52,7 @@ import java.util.Locale; import java.util.Map; import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; import org.apache.hc.core5.http.ContentType; import org.apache.hc.core5.util.Timeout; @@ -65,6 +67,7 @@ import prerna.io.connector.ms.MicrosoftLoginUtils; import prerna.io.connector.ms.MicrosoftTokenFiller; import prerna.security.HttpHelperUtility; +import prerna.util.Utility; import prerna.util.ValueUtils; /** @@ -192,6 +195,8 @@ public class MicrosoftOneDriveHelper { */ private static final String MATCH_EVERYTHING = "*"; + private static final String FIXTURE_SETTING = "COLLABORATION_FIXTURE_MAIL"; + /** * Utility class constructor intentionally hidden. */ @@ -199,6 +204,91 @@ private MicrosoftOneDriveHelper() { } + public static String fixturePath() { + try { + String fixture = Utility.getDIHelperProperty(FIXTURE_SETTING); + if (fixture == null || fixture.isBlank()) { + fixture = System.getenv(FIXTURE_SETTING); + } + if (fixture == null || fixture.isBlank()) { + classLogger.debug("No fixture setting found for COLLABORATION_FIXTURE_MAIL"); + return null; + } + fixture = fixture.trim(); + classLogger.debug("Found fixture mail path: {}", fixture); + Path mailPath = Path.of(fixture); + Path onedriveM365Path = mailPath.resolveSibling("onedrive-m365.json"); + classLogger.debug("Looking for OneDrive M365 fixture at: {}", onedriveM365Path); + if (Files.exists(onedriveM365Path)) { + classLogger.debug("OneDrive M365 fixture found, using fixture mode"); + return onedriveM365Path.toString(); + } else { + classLogger.debug("OneDrive M365 fixture not found at: {}", onedriveM365Path); + return null; + } + } catch (Exception e) { + classLogger.error("Error checking for OneDrive fixture", e); + return null; + } + } + + static class OneDriveFixtureSource { + private static final Map LOADED = new ConcurrentHashMap<>(); + private final List> drives = new ArrayList<>(); + private final List> items = new ArrayList<>(); + + @SuppressWarnings("unchecked") + private OneDriveFixtureSource(String path) { + try (Reader reader = Files.newBufferedReader(Path.of(path), StandardCharsets.UTF_8)) { + Map fixture = new Gson().fromJson(reader, Map.class); + if (fixture.get("drives") instanceof List drivesList) { + for (Object item : drivesList) { + drives.add((Map) item); + } + } + if (fixture.get("items") instanceof List itemsList) { + for (Object item : itemsList) { + items.add((Map) item); + } + } + } catch (Exception e) { + throw new IllegalStateException("Cannot read the " + FIXTURE_SETTING + " file at " + path, e); + } + } + + static OneDriveFixtureSource of(String path) { + return (OneDriveFixtureSource) LOADED.computeIfAbsent(path, p -> new OneDriveFixtureSource(p)); + } + + List> listFiles(String driveId, String itemId, String path, int limit) { + List> result = new ArrayList<>(); + for (Map item : items) { + Object itemDriveId = item.get("driveId"); + Object itemParentId = item.get("parentId"); + boolean matchesDrive = driveId == null || (itemDriveId != null && itemDriveId.equals(driveId)); + boolean matchesParent = itemId == null || (itemParentId != null && itemParentId.equals(itemId)); + if (matchesDrive && matchesParent) { + result.add(item); + if (limit > 0 && result.size() >= limit) { + break; + } + } + } + return result; + } + + Map getItem(String driveId, String itemId) { + for (Map item : items) { + Object itemDriveId = item.get("driveId"); + Object itemItemId = item.get("id"); + if (itemItemId != null && itemItemId.equals(itemId) && (driveId == null || (itemDriveId != null && itemDriveId.equals(driveId)))) { + return item; + } + } + return null; + } + } + /** * Reads the signed in user's own OneDrive. * @@ -1874,4 +1964,34 @@ private static void requireNoPathSeparator(String fileName) { } } + public static List> listFilesFixture(String driveId, String itemId, String path, int limit) + throws Exception { + String fixturePath = fixturePath(); + if (fixturePath == null) { + throw new IllegalStateException("Fixture mode is not enabled. Set " + FIXTURE_SETTING + + " environment variable or DI property and ensure onedrive-m365.json exists next to mail.json."); + } + OneDriveFixtureSource source = OneDriveFixtureSource.of(fixturePath); + List> items = new ArrayList<>(); + for (Map item : source.listFiles(driveId, itemId, path, limit)) { + items.add(MicrosoftOneDriveItemMapper.toDriveItem(item, driveId)); + } + return items; + } + + public static Map getItemFixture(String driveId, String itemId) throws Exception { + String fixturePath = fixturePath(); + if (fixturePath == null) { + throw new IllegalStateException("Fixture mode is not enabled. Set " + FIXTURE_SETTING + + " environment variable or DI property and ensure onedrive-m365.json exists next to mail.json."); + } + OneDriveFixtureSource source = OneDriveFixtureSource.of(fixturePath); + Map item = source.getItem(driveId, itemId); + if (item == null) { + throw new IllegalStateException("Microsoft Graph returned no OneDrive item for drive = " + driveId + + ", item = " + itemId + " in fixture data"); + } + return MicrosoftOneDriveItemMapper.toDriveItem(item, driveId); + } + } diff --git a/src/prerna/io/connector/ms/onedrive/MicrosoftOneDriveItemMapper.java b/src/prerna/io/connector/ms/onedrive/MicrosoftOneDriveItemMapper.java index e951c19e00..a4e6b7f2bf 100644 --- a/src/prerna/io/connector/ms/onedrive/MicrosoftOneDriveItemMapper.java +++ b/src/prerna/io/connector/ms/onedrive/MicrosoftOneDriveItemMapper.java @@ -101,7 +101,9 @@ public static Map toDriveItem(Map item, String f Map described = effectiveItem(item); Map output = new LinkedHashMap<>(); - output.put(ID, described.get(ID)); + Object itemId = described.get(ID); + output.put("id", itemId); + output.put("itemId", itemId); putIfPresent(output, NAME, described.get(NAME)); putIfPresent(output, DRIVE_ID, driveIdOf(item, fallbackDriveId)); output.put("isFolder", described.get(FOLDER) != null); @@ -221,6 +223,11 @@ public static String driveIdOf(Map item, String fallback) { if (driveId == null) { driveId = ValueUtils.toNonBlankString(parentField(item, DRIVE_ID)); } + // For fixture data, check if driveId is at the root level + if (driveId == null) { + Object rootDriveId = item.get(DRIVE_ID); + driveId = ValueUtils.toNonBlankString(rootDriveId == null ? null : rootDriveId.toString()); + } return driveId == null ? fallback : driveId; } diff --git a/src/prerna/io/connector/ms/onedrive/MicrosoftOneDriveListFilesReactor.java b/src/prerna/io/connector/ms/onedrive/MicrosoftOneDriveListFilesReactor.java index e70bac6291..035ce93bb2 100644 --- a/src/prerna/io/connector/ms/onedrive/MicrosoftOneDriveListFilesReactor.java +++ b/src/prerna/io/connector/ms/onedrive/MicrosoftOneDriveListFilesReactor.java @@ -88,6 +88,16 @@ protected NounMetadata executeAuthenticated() { int limit = positiveInt(ReactorKeysEnum.LIMIT.getKey(), DEFAULT_LIMIT, MAX_LIMIT); try { + String fixturePath = MicrosoftOneDriveHelper.fixturePath(); + if (fixturePath != null) { + List> files = MicrosoftOneDriveHelper.listFilesFixture(driveId, itemId, path, + limit); + Map output = new LinkedHashMap<>(); + output.put("count", files.size()); + output.put("files", files); + return new NounMetadata(output, PixelDataType.CUSTOM_DATA_STRUCTURE); + } + User user = this.insight.getUser(); String accessToken = MicrosoftLoginUtils.getValidAccessToken(user); List> files = MicrosoftOneDriveHelper.listFiles(accessToken, driveId, itemId, path, diff --git a/src/prerna/io/connector/ms/teams/MicrosoftTeamsHelper.java b/src/prerna/io/connector/ms/teams/MicrosoftTeamsHelper.java index 60d32b50f8..b0e0f46fa6 100644 --- a/src/prerna/io/connector/ms/teams/MicrosoftTeamsHelper.java +++ b/src/prerna/io/connector/ms/teams/MicrosoftTeamsHelper.java @@ -28,6 +28,7 @@ package prerna.io.connector.ms.teams; import java.io.File; +import java.io.Reader; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.nio.file.Files; @@ -39,6 +40,7 @@ import java.util.List; import java.util.Locale; import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; import org.apache.hc.core5.http.ContentType; import org.apache.logging.log4j.LogManager; @@ -53,6 +55,7 @@ import prerna.io.connector.ms.MicrosoftTokenFiller; import prerna.io.connector.ms.onedrive.MicrosoftOneDriveHelper; import prerna.security.HttpHelperUtility; +import prerna.util.Utility; /** * Helper utility for Microsoft Teams connector operations. @@ -101,6 +104,8 @@ public class MicrosoftTeamsHelper { private static final List CONFLICT_BEHAVIORS = Arrays.asList(CONFLICT_FAIL, CONFLICT_RENAME, CONFLICT_REPLACE); + private static final String FIXTURE_SETTING = "COLLABORATION_FIXTURE_MAIL"; + /** * Graph recommends a resumable upload session for anything larger than 4MB. */ @@ -113,6 +118,101 @@ private MicrosoftTeamsHelper() { } + static String fixturePath() { + try { + String fixture = Utility.getDIHelperProperty(FIXTURE_SETTING); + if (fixture == null || fixture.isBlank()) { + fixture = System.getenv(FIXTURE_SETTING); + } + if (fixture == null || fixture.isBlank()) { + classLogger.debug("No fixture setting found for COLLABORATION_FIXTURE_MAIL"); + return null; + } + fixture = fixture.trim(); + classLogger.debug("Found fixture mail path: {}", fixture); + Path mailPath = Path.of(fixture); + Path teamsM365Path = mailPath.resolveSibling("teams-m365.json"); + classLogger.debug("Looking for Teams M365 fixture at: {}", teamsM365Path); + if (Files.exists(teamsM365Path)) { + classLogger.debug("Teams M365 fixture found, using fixture mode"); + return teamsM365Path.toString(); + } else { + classLogger.debug("Teams M365 fixture not found at: {}", teamsM365Path); + return null; + } + } catch (Exception e) { + classLogger.error("Error checking for Teams fixture", e); + return null; + } + } + + static class TeamsFixtureSource { + private static final Map LOADED = new ConcurrentHashMap<>(); + private final List> teams = new ArrayList<>(); + private final List> channels = new ArrayList<>(); + + @SuppressWarnings("unchecked") + private TeamsFixtureSource(String path) { + try (Reader reader = Files.newBufferedReader(Path.of(path), StandardCharsets.UTF_8)) { + Map fixture = new Gson().fromJson(reader, Map.class); + if (fixture.get("teams") instanceof List teamsList) { + for (Object item : teamsList) { + teams.add((Map) item); + } + } + if (fixture.get("channels") instanceof List channelsList) { + for (Object item : channelsList) { + channels.add((Map) item); + } + } + } catch (Exception e) { + throw new IllegalStateException("Cannot read the " + FIXTURE_SETTING + " file at " + path, e); + } + } + + static TeamsFixtureSource of(String path) { + return (TeamsFixtureSource) LOADED.computeIfAbsent(path, p -> new TeamsFixtureSource(p)); + } + + List> listTeams(int limit) { + List> result = new ArrayList<>(); + for (Map team : teams) { + result.add(team); + if (limit > 0 && result.size() >= limit) { + break; + } + } + return result; + } + + List> listChannels(String teamId, int limit) { + List> result = new ArrayList<>(); + for (Map channel : channels) { + if (teamId.equals(channel.get("teamId"))) { + result.add(channel); + if (limit > 0 && result.size() >= limit) { + break; + } + } + } + return result; + } + + Map getChannelFilesFolder(String teamId, String channelId) { + for (Map channel : channels) { + if (teamId.equals(channel.get("teamId")) && channelId.equals(channel.get("id"))) { + Map folder = new HashMap<>(); + folder.put(DRIVE_ID, "drive-" + teamId); + folder.put(FOLDER_ID, "folder-" + channelId); + folder.put(NAME, channel.get(DISPLAY_NAME)); + folder.put(WEB_URL, channel.get(WEB_URL)); + return folder; + } + } + return null; + } + } + /** * Lists the Microsoft Teams the current user has joined. * @@ -611,4 +711,56 @@ private static void requireValue(String value, String message) { } } + static List> listTeamsFixture(int limit) throws Exception { + String fixturePath = fixturePath(); + if (fixturePath == null) { + throw new IllegalStateException("Fixture mode is not enabled. Set " + FIXTURE_SETTING + " environment variable or DI property and ensure teams-m365.json exists next to mail.json."); + } + TeamsFixtureSource source = TeamsFixtureSource.of(fixturePath); + return source.listTeams(limit); + } + + static List> listChannelsFixture(String teamId, int limit) throws Exception { + String fixturePath = fixturePath(); + if (fixturePath == null) { + throw new IllegalStateException("Fixture mode is not enabled. Set " + FIXTURE_SETTING + " environment variable or DI property and ensure teams-m365.json exists next to mail.json."); + } + TeamsFixtureSource source = TeamsFixtureSource.of(fixturePath); + return source.listChannels(teamId, limit); + } + + public static Map getChannelFilesFolderFixture(String teamId, String channelId) throws Exception { + String fixturePath = fixturePath(); + if (fixturePath == null) { + throw new IllegalStateException("Fixture mode is not enabled. Set " + FIXTURE_SETTING + " environment variable or DI property and ensure teams-m365.json exists next to mail.json."); + } + TeamsFixtureSource source = TeamsFixtureSource.of(fixturePath); + Map folder = source.getChannelFilesFolder(teamId, channelId); + if (folder == null) { + throw new IllegalStateException( + "Microsoft Graph returned no folder for channel id = " + channelId + " in team " + teamId + " in fixture data"); + } + return folder; + } + + public static List> listChannelFilesFixture(String teamId, String channelId, + String folderPath, int limit) throws Exception { + String fixturePath = fixturePath(); + if (fixturePath == null) { + throw new IllegalStateException("Fixture mode is not enabled. Set " + FIXTURE_SETTING + " environment variable or DI property and ensure teams-m365.json exists next to mail.json."); + } + Map folder = getChannelFilesFolderFixture(teamId, channelId); + String driveId = folder.get(DRIVE_ID).toString(); + List> items = new ArrayList<>(); + try { + List> files = MicrosoftOneDriveHelper.listFilesFixture(driveId, folder.get(FOLDER_ID).toString(), folderPath, limit); + for (Map file : files) { + items.add(toDriveItemMap(file, driveId)); + } + } catch (Exception e) { + classLogger.debug("Channel files not found in OneDrive fixture, returning empty list", e); + } + return items; + } + } diff --git a/src/prerna/io/connector/ms/teams/MicrosoftTeamsListChannelsReactor.java b/src/prerna/io/connector/ms/teams/MicrosoftTeamsListChannelsReactor.java index bcdcd03c07..015ef24f50 100644 --- a/src/prerna/io/connector/ms/teams/MicrosoftTeamsListChannelsReactor.java +++ b/src/prerna/io/connector/ms/teams/MicrosoftTeamsListChannelsReactor.java @@ -27,6 +27,7 @@ *******************************************************************************/ package prerna.io.connector.ms.teams; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -90,10 +91,22 @@ protected NounMetadata executeAuthenticated() { } try { + String fixturePath = MicrosoftTeamsHelper.fixturePath(); + if (fixturePath != null) { + List> channels = MicrosoftTeamsHelper.listChannelsFixture(teamId, limit); + Map output = new LinkedHashMap<>(); + output.put("count", channels.size()); + output.put("channels", channels); + return new NounMetadata(output, PixelDataType.CUSTOM_DATA_STRUCTURE); + } + User user = this.insight.getUser(); String accessToken = MicrosoftLoginUtils.getValidAccessToken(user); - List> result = MicrosoftTeamsHelper.listChannels(accessToken, teamId, limit); - return new NounMetadata(result, PixelDataType.CUSTOM_DATA_STRUCTURE); + List> channels = MicrosoftTeamsHelper.listChannels(accessToken, teamId, limit); + Map output = new LinkedHashMap<>(); + output.put("count", channels.size()); + output.put("channels", channels); + return new NounMetadata(output, PixelDataType.CUSTOM_DATA_STRUCTURE); } catch (SemossPixelException e) { classLogger.error("Error while listing Microsoft Teams channels", e); throw e; diff --git a/src/prerna/io/connector/ms/teams/MicrosoftTeamsListFilesReactor.java b/src/prerna/io/connector/ms/teams/MicrosoftTeamsListFilesReactor.java index 647e484c39..51c465cae4 100644 --- a/src/prerna/io/connector/ms/teams/MicrosoftTeamsListFilesReactor.java +++ b/src/prerna/io/connector/ms/teams/MicrosoftTeamsListFilesReactor.java @@ -27,6 +27,7 @@ *******************************************************************************/ package prerna.io.connector.ms.teams; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -96,11 +97,24 @@ protected NounMetadata executeAuthenticated() { } try { + String fixturePath = MicrosoftTeamsHelper.fixturePath(); + if (fixturePath != null) { + List> files = MicrosoftTeamsHelper.listChannelFilesFixture(teamId, channelId, + folderPath, limit); + Map output = new LinkedHashMap<>(); + output.put("count", files.size()); + output.put("files", files); + return new NounMetadata(output, PixelDataType.CUSTOM_DATA_STRUCTURE); + } + User user = this.insight.getUser(); String accessToken = MicrosoftLoginUtils.getValidAccessToken(user); - List> result = MicrosoftTeamsHelper.listChannelFiles(accessToken, teamId, channelId, + List> files = MicrosoftTeamsHelper.listChannelFiles(accessToken, teamId, channelId, folderPath, limit); - return new NounMetadata(result, PixelDataType.CUSTOM_DATA_STRUCTURE); + Map output = new LinkedHashMap<>(); + output.put("count", files.size()); + output.put("files", files); + return new NounMetadata(output, PixelDataType.CUSTOM_DATA_STRUCTURE); } catch (SemossPixelException e) { classLogger.error("Error while listing Microsoft Teams channel files", e); throw e; diff --git a/src/prerna/io/connector/ms/teams/MicrosoftTeamsListTeamsReactor.java b/src/prerna/io/connector/ms/teams/MicrosoftTeamsListTeamsReactor.java index 76c9c467f5..048ba613e1 100644 --- a/src/prerna/io/connector/ms/teams/MicrosoftTeamsListTeamsReactor.java +++ b/src/prerna/io/connector/ms/teams/MicrosoftTeamsListTeamsReactor.java @@ -27,6 +27,7 @@ *******************************************************************************/ package prerna.io.connector.ms.teams; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -83,10 +84,22 @@ protected NounMetadata executeAuthenticated() { } try { + String fixturePath = MicrosoftTeamsHelper.fixturePath(); + if (fixturePath != null) { + List> teams = MicrosoftTeamsHelper.listTeamsFixture(limit); + Map output = new LinkedHashMap<>(); + output.put("count", teams.size()); + output.put("teams", teams); + return new NounMetadata(output, PixelDataType.CUSTOM_DATA_STRUCTURE); + } + User user = this.insight.getUser(); String accessToken = MicrosoftLoginUtils.getValidAccessToken(user); - List> result = MicrosoftTeamsHelper.listTeams(accessToken, limit); - return new NounMetadata(result, PixelDataType.CUSTOM_DATA_STRUCTURE); + List> teams = MicrosoftTeamsHelper.listTeams(accessToken, limit); + Map output = new LinkedHashMap<>(); + output.put("count", teams.size()); + output.put("teams", teams); + return new NounMetadata(output, PixelDataType.CUSTOM_DATA_STRUCTURE); } catch (SemossPixelException e) { classLogger.error("Error while listing Microsoft Teams", e); throw e; diff --git a/src/prerna/reactor/collaboration/BrainLinkTopicM365FolderReactor.java b/src/prerna/reactor/collaboration/BrainLinkTopicM365FolderReactor.java index 0e936d1161..43e9dc664a 100644 --- a/src/prerna/reactor/collaboration/BrainLinkTopicM365FolderReactor.java +++ b/src/prerna/reactor/collaboration/BrainLinkTopicM365FolderReactor.java @@ -76,7 +76,11 @@ public NounMetadata execute() { throw new IllegalArgumentException("A folder kind is required"); } try { - String accessToken = MicrosoftLoginUtils.getValidAccessToken(user); + String accessToken = null; + String fixturePath = MicrosoftOneDriveHelper.fixturePath(); + if (fixturePath == null) { + accessToken = MicrosoftLoginUtils.getValidAccessToken(user); + } FolderPointer folder = resolveFolder(accessToken, kind); return mapResult(BrainTopicLinks.link(user, topicId, folder)); } catch (SemossPixelException e) { @@ -98,7 +102,13 @@ private FolderPointer resolveFolder(String accessToken, String kind) throws Exce if (driveId == null || itemId == null) { throw new IllegalArgumentException("A drive id and item id are required for a OneDrive folder"); } - Map item = MicrosoftOneDriveHelper.getItem(accessToken, driveId, itemId, null); + Map item; + String fixturePath = MicrosoftOneDriveHelper.fixturePath(); + if (fixturePath != null) { + item = MicrosoftOneDriveHelper.getItemFixture(driveId, itemId); + } else { + item = MicrosoftOneDriveHelper.getItem(accessToken, driveId, itemId, null); + } if (!Boolean.TRUE.equals(item.get("isFolder"))) { throw new IllegalArgumentException("The selected OneDrive item is not a folder"); } @@ -116,7 +126,13 @@ private FolderPointer resolveFolder(String accessToken, String kind) throws Exce if (teamId == null || channelId == null) { throw new IllegalArgumentException("A team id and channel id are required for Teams channel files"); } - Map folder = MicrosoftTeamsHelper.getChannelFilesFolder(accessToken, teamId, channelId); + Map folder; + String fixturePath = MicrosoftOneDriveHelper.fixturePath(); + if (fixturePath != null) { + folder = MicrosoftTeamsHelper.getChannelFilesFolderFixture(teamId, channelId); + } else { + folder = MicrosoftTeamsHelper.getChannelFilesFolder(accessToken, teamId, channelId); + } return new FolderPointer(kind, string(folder, "driveId"), string(folder, "folderId"), teamId, channelId, null, string(folder, "name"), string(folder, "webUrl")); } From 5f41348b0a62f894e365039040523a45cd0cef59 Mon Sep 17 00:00:00 2001 From: oshahid Date: Thu, 19 Nov 2026 14:45:44 +0530 Subject: [PATCH 6/9] feat: add support for retrieving M365 folders in topic details --- src/prerna/collaboration/BrainTopicUtils.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/prerna/collaboration/BrainTopicUtils.java b/src/prerna/collaboration/BrainTopicUtils.java index 2623caa337..ea10a00530 100644 --- a/src/prerna/collaboration/BrainTopicUtils.java +++ b/src/prerna/collaboration/BrainTopicUtils.java @@ -155,6 +155,7 @@ public static Map getTopic(String ownerId, String ownerType, Str topic.put("people", getPeople(ownerId, ownerType, topicId)); topic.put("folders", BrainMailFolders.ofTopic(ownerId, ownerType, topicId)); topic.put("files", BrainTopicFiles.ofTopic(ownerId, ownerType, topicId)); + topic.put("m365Folders", BrainTopicLinks.ofTopic(ownerId, ownerType, topicId)); return topic; } From 82b7c3aaaa88c3026da0b24e8b6d9e4ede71da38 Mon Sep 17 00:00:00 2001 From: oshahid Date: Thu, 19 Nov 2026 17:54:40 +0530 Subject: [PATCH 7/9] feat: add fixture mode support for downloading files from OneDrive --- .../MicrosoftOneDriveDownloadFileReactor.java | 44 +++++++++ .../ms/onedrive/MicrosoftOneDriveHelper.java | 94 ++++++++++++------- 2 files changed, 106 insertions(+), 32 deletions(-) diff --git a/src/prerna/io/connector/ms/onedrive/MicrosoftOneDriveDownloadFileReactor.java b/src/prerna/io/connector/ms/onedrive/MicrosoftOneDriveDownloadFileReactor.java index e091c37961..00d4d348ba 100644 --- a/src/prerna/io/connector/ms/onedrive/MicrosoftOneDriveDownloadFileReactor.java +++ b/src/prerna/io/connector/ms/onedrive/MicrosoftOneDriveDownloadFileReactor.java @@ -90,6 +90,50 @@ protected NounMetadata executeAuthenticated() { try { User user = this.insight.getUser(); + + // Check for fixture mode first + String fixturePath = MicrosoftOneDriveHelper.fixturePath(); + if (fixturePath != null && driveId != null && itemId != null) { + try { + String content = MicrosoftOneDriveHelper.getFileContentFixture(driveId, itemId); + Map item = MicrosoftOneDriveHelper.getItemFixture(driveId, itemId); + + // Create insight folder + String insightFolder = this.insight.getInsightFolder(); + File insightFolderFile = new File(insightFolder); + if (!insightFolderFile.exists() && !insightFolderFile.mkdirs()) { + throw new SemossPixelException("Unable to create the insight folder at: " + insightFolder); + } + + // Use provided file name or extract from item + String resolvedFileName = fileName; + if (resolvedFileName == null && item.get("name") != null) { + resolvedFileName = toBaseName(item.get("name").toString()); + } + if (resolvedFileName == null) { + resolvedFileName = "downloaded_file.txt"; + } + + // Write fixture content to file + File targetFile = new File(insightFolder, resolvedFileName); + java.nio.file.Files.write(targetFile.toPath(), content.getBytes(java.nio.charset.StandardCharsets.UTF_8)); + + // Return result similar to real download + Map result = new java.util.HashMap<>(); + result.put("filePath", targetFile.getAbsolutePath()); + result.put("name", resolvedFileName); + result.put("size", content.getBytes(java.nio.charset.StandardCharsets.UTF_8).length); + result.put("lastModifiedDateTime", item.get("lastModifiedDateTime")); + result.put("lastModifiedBy", item.get("lastModifiedBy")); + result.put("source", "fixture"); + + return new NounMetadata(result, PixelDataType.CUSTOM_DATA_STRUCTURE); + } catch (Exception e) { + classLogger.debug("Fixture mode download failed, trying real download", e); + // Fall through to real download + } + } + String accessToken = MicrosoftLoginUtils.getValidAccessToken(user); // create it up front: for an unsaved insight the folder may not exist yet, and diff --git a/src/prerna/io/connector/ms/onedrive/MicrosoftOneDriveHelper.java b/src/prerna/io/connector/ms/onedrive/MicrosoftOneDriveHelper.java index 76c272171f..cb6c78dc7a 100644 --- a/src/prerna/io/connector/ms/onedrive/MicrosoftOneDriveHelper.java +++ b/src/prerna/io/connector/ms/onedrive/MicrosoftOneDriveHelper.java @@ -281,12 +281,25 @@ Map getItem(String driveId, String itemId) { for (Map item : items) { Object itemDriveId = item.get("driveId"); Object itemItemId = item.get("id"); - if (itemItemId != null && itemItemId.equals(itemId) && (driveId == null || (itemDriveId != null && itemDriveId.equals(driveId)))) { + if (itemItemId != null && itemItemId.equals(itemId) + && (driveId == null || (itemDriveId != null && itemDriveId.equals(driveId)))) { return item; } } return null; } + + String getFileContent(String driveId, String itemId) { + Map item = getItem(driveId, itemId); + if (item == null) { + return null; + } + Object content = item.get("content"); + if (content instanceof String) { + return (String) content; + } + return null; + } } /** @@ -548,8 +561,8 @@ public static List> listRecentFiles(String accessToken, Inst } List> recent = new ArrayList<>(files.values()); - recent.sort(Comparator.comparing((Map file) -> instantOf(file.get(LAST_MODIFIED))) - .reversed()); + recent.sort( + Comparator.comparing((Map file) -> instantOf(file.get(LAST_MODIFIED))).reversed()); if (limit > 0 && recent.size() > limit) { return new ArrayList<>(recent.subList(0, limit)); } @@ -731,8 +744,8 @@ public static Map resolveSharingLink(String accessToken, String * *

* Where the copy came from is recorded beside it (see - * {@link MicrosoftOneDriveSources}). A copy of the same file that is already - * in the destination, and that nobody changed there, is the one brought up to + * {@link MicrosoftOneDriveSources}). A copy of the same file that is already in + * the destination, and that nobody changed there, is the one brought up to * date: it is fetched again only when OneDrive holds a newer version, and no * second copy is written under another name. A copy that was changed there is * never written over unless the caller names it: a download that names no file @@ -850,12 +863,12 @@ public static Map downloadFile(String accessToken, String driveI *

* *

- * An upload that replaces is the one that can lose somebody's work, so when - * the local file is a copy a download recorded, and the upload is aimed at the - * file it was copied from, it goes through {@link #saveBack} instead, as a save - * the owner asked for. Aimed nowhere in particular (no drive, folder or other - * name) it goes back to that file too, wherever it lives, rather than to the - * drive root. + * An upload that replaces is the one that can lose somebody's work, so when the + * local file is a copy a download recorded, and the upload is aimed at the file + * it was copied from, it goes through {@link #saveBack} instead, as a save the + * owner asked for. Aimed nowhere in particular (no drive, folder or other name) + * it goes back to that file too, wherever it lives, rather than to the drive + * root. *

* * @param accessToken Microsoft Graph access token for the user @@ -956,9 +969,9 @@ public boolean alreadyTold() { * {@link MicrosoftOneDriveSources}), and the original has to still hold the * version the copy was taken from. When somebody changed the original in the * meantime nothing is uploaded, since writing the copy over it would discard - * their change without anybody having seen it. That refusal is recorded, and - * an owner who was told of the change and asks again gets their way: the - * second informed save writes the copy over it. + * their change without anybody having seen it. That refusal is recorded, and an + * owner who was told of the change and asks again gets their way: the second + * informed save writes the copy over it. *

* *

@@ -968,9 +981,9 @@ public boolean alreadyTold() { * * @param accessToken Microsoft Graph access token for the user * @param copy the local copy to upload - * @param informed whether the owner asked for this save themselves, which - * is what lets it write over a change they were already - * told about; a save nobody asked for never does + * @param informed whether the owner asked for this save themselves, which is + * what lets it write over a change they were already told + * about; a save nobody asked for never does * @return the file as OneDrive now holds it * @throws SaveBackRefused if the file is not a recorded copy, or its original * is gone or has changed @@ -1325,8 +1338,8 @@ private static long downloadBytes(String accessToken, Map item, *

* * @param url what to fetch - * @param headers the request headers, or null for a url that is pre-authenticated, - * which a failure then does not quote + * @param headers the request headers, or null for a url that is + * pre-authenticated, which a failure then does not quote * @param file where the bytes go, in a folder that exists * @param name what a refusal calls the file * @return how many bytes were written; the file is left as it was when there @@ -1446,11 +1459,11 @@ private static String sessionUpload(String accessToken, String driveId, String i /** * Sends a file to an upload session in pieces, for whichever helper opened the - * session. A session whose upload fails is cancelled: while one is open OneDrive - * answers every other upload of the same file with a 409, "currently being - * uploaded", for a quarter of an hour or so, which is how one refusal of a file - * open in Office became many. The failure does not quote the session's url, - * which is what signs its requests. + * session. A session whose upload fails is cancelled: while one is open + * OneDrive answers every other upload of the same file with a 409, "currently + * being uploaded", for a quarter of an hour or so, which is how one refusal of + * a file open in Office became many. The failure does not quote the session's + * url, which is what signs its requests. * * @param uploadUrl the url the session answered with * @param file the file to send @@ -1488,7 +1501,8 @@ public static String sendToUploadSession(String uploadUrl, File file, String fil try { HttpHelperUtility.deleteRequestStringBody(uploadUrl, null, null, null, null); } catch (Exception notCancelled) { - // the url is what signs the request, so the failure, which quotes it, is not logged + // the url is what signs the request, so the failure, which quotes it, is not + // logged classLogger.warn("Could not cancel the upload session of {}; Graph refuses another upload of that " + "file until the session expires", fileName); } @@ -1507,8 +1521,10 @@ public static String sendToUploadSession(String uploadUrl, File file, String fil * @return the failure itself when it does not quote the url, or one that says * the same without it */ - // shortcut: HttpHelperUtility logs the url itself when the connection drops, before it throws; - // have it leave query strings out of its own lines once that has to be closed too + // shortcut: HttpHelperUtility logs the url itself when the connection drops, + // before it throws; + // have it leave query strings out of its own lines once that has to be closed + // too private static Exception withoutUrl(Exception e, String url, String what) { String why = e.getMessage(); if (why == null || !why.contains(url)) { @@ -1585,11 +1601,11 @@ private static void remember(File copy, String driveId, String itemId, String ve * @param itemId the folder the upload names, or null * @param folderPath the folder path the upload names, or null * @param fileName the name the upload gives the file - * @return true when the local file is a recorded copy and the upload names - * its original, or names nowhere else to go + * @return true when the local file is a recorded copy and the upload names its + * original, or names nowhere else to go */ - private static boolean isOriginal(String accessToken, File copy, String driveId, String itemId, - String folderPath, String fileName) throws Exception { + private static boolean isOriginal(String accessToken, File copy, String driveId, String itemId, String folderPath, + String fileName) throws Exception { MicrosoftOneDriveSources.Source source = MicrosoftOneDriveSources.read(copy); if (source == null) { return false; @@ -1994,4 +2010,18 @@ public static Map getItemFixture(String driveId, String itemId) return MicrosoftOneDriveItemMapper.toDriveItem(item, driveId); } -} + public static String getFileContentFixture(String driveId, String itemId) throws Exception { + String fixturePath = fixturePath(); + if (fixturePath == null) { + throw new IllegalStateException("Fixture mode is not enabled. Set " + FIXTURE_SETTING + + " environment variable or DI property and ensure onedrive-m365.json exists next to mail.json."); + } + OneDriveFixtureSource source = OneDriveFixtureSource.of(fixturePath); + String content = source.getFileContent(driveId, itemId); + if (content == null) { + throw new IllegalStateException( + "No content found for item in fixture data for drive = " + driveId + ", item = " + itemId); + } + return content; + } +} \ No newline at end of file From c9d9756a10873cdf241edd860100cdd494ae16a8 Mon Sep 17 00:00:00 2001 From: oshahid Date: Tue, 24 Nov 2026 16:30:23 +0530 Subject: [PATCH 8/9] feat: enhance description of linked Microsoft 365 folders in BrainTopicBrief --- src/prerna/collaboration/BrainTopicBrief.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/prerna/collaboration/BrainTopicBrief.java b/src/prerna/collaboration/BrainTopicBrief.java index 3b7706f739..84f268732c 100644 --- a/src/prerna/collaboration/BrainTopicBrief.java +++ b/src/prerna/collaboration/BrainTopicBrief.java @@ -253,7 +253,8 @@ private static String linkedFoldersBrief(String ownerId, String ownerType, Strin return ""; } StringBuilder out = new StringBuilder( - "\nLinked Microsoft 365 folders: the agent lists and reads files from these by default. " + "\nLinked Microsoft 365 folders: the owner linked these to this topic because they contain " + + "relevant files for this topic's work. The agent lists and reads files from these by default. " + "To list files, call ListDriveFiles for a OneDrive link, or ListChannelFiles for Teams. " + "Availability is marked 'ok' or 'unavailable' (access lost):"); for (Map link : links.subList(0, Math.min(links.size(), MAX_ITEMS))) { From e26fe97426b0624e908ac4347adbd03cfa05622b Mon Sep 17 00:00:00 2001 From: oshahid Date: Thu, 26 Nov 2026 14:16:05 +0530 Subject: [PATCH 9/9] feat: add import for Path in MicrosoftTeamsHelper --- src/prerna/io/connector/ms/teams/MicrosoftTeamsHelper.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/prerna/io/connector/ms/teams/MicrosoftTeamsHelper.java b/src/prerna/io/connector/ms/teams/MicrosoftTeamsHelper.java index 83a29252ab..df3cb477d4 100644 --- a/src/prerna/io/connector/ms/teams/MicrosoftTeamsHelper.java +++ b/src/prerna/io/connector/ms/teams/MicrosoftTeamsHelper.java @@ -32,6 +32,7 @@ import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.nio.file.Files; +import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays;