Skip to content

Commit

Permalink
476 resolving slack last image upload (#478)
Browse files Browse the repository at this point in the history
* Fetching past the last 15 images for the uploading of last image

* refactoring code of last image uploaded

* fixing lint

* fixing lint
  • Loading branch information
Thibault authored and GitHub committed Aug 6, 2025
1 parent 5d82e58 commit da710c2
Show file tree
Hide file tree
Showing 4 changed files with 55 additions and 117 deletions.
47 changes: 9 additions & 38 deletions backend/src/api/slack/controllers/slack.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ module.exports = {
fetchImages: async (ctx) => {
const CACHE_DURATION = 60 * 1000; // 1 minute
const now = Date.now();

if (
cachedImage &&
cacheTimestamp &&
Expand All @@ -26,15 +25,18 @@ module.exports = {
}
try {
const { satName } = ctx.request.body;

const message = await fetchImagesFromSlack.fetchImagesFromSlack(satName);
const image = message ? message.files[0] : null;
if (!image.public_url_shared) {
await fetchImagesFromSlack.getSharedURL(image?.id);
}
const imageURl = fetchImagesFromSlack.createImageUrl(
image?.permalink_public,
image?.name
);
cachedImage = {
success: true,
message: {
id: message.files[0].id,
name: message.files[0].name,
permalink_public: message.files[0].permalink_public,
},
image: imageURl,
};
cacheTimestamp = now;
if (message) {
Expand All @@ -50,35 +52,4 @@ module.exports = {
ctx.body = { error: error.message };
}
},
getSharedURL: async (ctx) => {
const { fileId } = ctx.request.body;
if (!fileId) {
return ctx.badRequest("File ID is required");
}

try {
const response = await fetch(
"https://slack.com/api/files.sharedPublicURL",
{
method: "POST",
headers: {
Authorization: `Bearer ${process.env.SLACK_USER_TOKEN}`,
"Content-Type": "application/json",
},
body: JSON.stringify({ file: fileId }),
}
);

const data = await response.json();
if (!data.ok && !data.error.includes("already_public")) {
throw new Error(data.error || "Failed to make the image public");
}
ctx.send({
message: "Image has been made public successfully",
});
} catch (error) {
console.error("Error generating public URL:", error);
ctx.internalServerError("Failed to make the image URL " + fileId);
}
},
};
8 changes: 0 additions & 8 deletions backend/src/api/slack/routes/slack.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,5 @@ module.exports = {
auth: false,
},
},
{
method: "POST",
path: "/slack-shared-url",
handler: "slack.getSharedURL",
config: {
auth: false,
},
},
],
};
41 changes: 39 additions & 2 deletions backend/src/api/slack/services/slack.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,49 @@ module.exports = {
cursor = result.response_metadata
? result.response_metadata.next_cursor
: null;
if (image) break;
if (image) return image;
}
return image;
} catch (error) {
console.error("Error fetching images from Slack:", error);
throw error;
}
},
getSharedURL: async (idImage) => {
if (!idImage) {
console.error("No image ID provided for sharing.");
return;
}
try {
const response = await fetch(
"https://slack.com/api/files.sharedPublicURL",
{
method: "POST",
headers: {
Authorization: `Bearer ${process.env.SLACK_USER_TOKEN}`,
"Content-Type": "application/json",
},
body: JSON.stringify({ file: idImage }),
}
);

const data = await response.json();
if (!data.ok && !data.error.includes("already_public")) {
throw new Error(data.error || "Failed to make the image public");
}
} catch (error) {
console.error("Error generating public URL:", error);
}
},
createImageUrl: (originalURL, fileName) => {
if (originalURL !== undefined) {
const lastSegment = originalURL.split("/").pop();
if (!lastSegment) return;
const arrayInfo = lastSegment.split("-");
const userTeam = arrayInfo[0];
const fileId = arrayInfo[1];
const pubSecret = arrayInfo[2];
const fileNameLowered = fileName.toLowerCase();
return `https://files.slack.com/files-pri/${userTeam}-${fileId}/${fileNameLowered}?pub_secret=${pubSecret}`;
}
},
};
76 changes: 7 additions & 69 deletions frontend/src/app/satellites/[satelliteSlug]/_infoSat/satImage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,55 +15,13 @@ export default function SatImage({
STRAPI_URL: string | undefined;
noradID: number | undefined;
}) {
const [selectedSatellite] = useSatelliteStore((state) => [
state.selectedSatellite,
]);
const satNumToEntry = useSatelliteStore((state) => state.satNumToEntry);

const [satImage, setSatImage] = useState<string | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);

const makeTheImagePublic = useCallback(
async (ID: number) => {
const requestDetails = {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
fileId: ID,
}),
};

const responseUrl = await fetch(
STRAPI_URL + "/api/slack-shared-url",
requestDetails,
);
if (!responseUrl.ok) {
throw new Error(`HTTP error! status: ${responseUrl.status}`);
}
},
[STRAPI_URL],
);

const createImageUrl = useCallback(
(originalURL: string, fileName: string) => {
if (originalURL !== undefined) {
const lastSegment = originalURL.split("/").pop();
if (!lastSegment) return;
const arrayInfo = lastSegment.split("-");
const userTeam = arrayInfo[0];
const fileId = arrayInfo[1];
const pubSecret = arrayInfo[2];
const fileNameLowered = fileName.toLowerCase();
return `https://files.slack.com/files-pri/${userTeam}-${fileId}/${fileNameLowered}?pub_secret=${pubSecret}`;
}
},
[],
);

const getMesasgeBySatellite = useCallback(
const getImageUrl = useCallback(
async (satName: string) => {
const requestDetails = {
method: "POST",
Expand All @@ -84,7 +42,10 @@ export default function SatImage({
}

const data = await response.json();
return data.message;
if (data.success === false) {
throw new Error(data.message.error || "Failed to fetch image");
}
return data.image;
},
[STRAPI_URL],
);
Expand All @@ -94,22 +55,7 @@ export default function SatImage({
try {
setLoading(true);
const satName = satNumToEntry[noradID as SatelliteNumber]?.name;
interface SlackFile {
id: number;
name: string;
permalink_public: string;
}
const message = (await getMesasgeBySatellite(
satName as string,
)) as SlackFile;
makeTheImagePublic(message?.id as number).catch((err) => {
console.error("Error making image public:", err);
setError("Failed to make image public.");
});
const imageUrl = createImageUrl(
message?.permalink_public as string,
message?.name as string,
);
const imageUrl = await getImageUrl(satName);
setSatImage(imageUrl ?? null);
} catch (err) {
console.error("Error fetching satellite images:", err);
Expand All @@ -119,15 +65,7 @@ export default function SatImage({
}
}
fetchSlackImages();
}, [
satImage,
selectedSatellite,
STRAPI_URL,
noradID,
satNumToEntry,
makeTheImagePublic,
createImageUrl,
]);
}, [satImage, noradID, satNumToEntry, getImageUrl]);

if (loading) {
return <div>Loading satellite image...</div>;
Expand Down

0 comments on commit da710c2

Please sign in to comment.