Skip to content

Commit

Permalink
Moving File
Browse files Browse the repository at this point in the history
  • Loading branch information
maxtyson123 committed Sep 24, 2024
1 parent 342d22d commit 9accda3
Show file tree
Hide file tree
Showing 2 changed files with 146 additions and 6 deletions.
68 changes: 62 additions & 6 deletions website/src/components/modal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -146,18 +146,23 @@ export function ImagePopup({show, hideCallback, id = 0}: ImagePopupProps) {

// Fetch the posts for this plant
const posts = await makeCachedRequest("editor_posts_"+id, "/api/posts/fetch?operation=siteFeed&plant_id=" + id)
let thisPlantPosts;
let thisPostsPosts;
if(posts){
// Reverse the posts
posts.reverse();

setThisImages(posts.filter((post: any) => post.post_in_use))
setPostImages(posts.filter((post: any) => !post.post_in_use))
setCurrentDisplayImages(posts.filter((post: any) => post.post_in_use))
thisPlantPosts = posts.filter((post: any) => post.post_in_use)
thisPostsPosts = posts.filter((post: any) => !post.post_in_use)

setThisImages(thisPlantPosts)
setPostImages(thisPostsPosts)
setCurrentDisplayImages(thisPlantPosts)

}


let cSelectedImages = [[], Array(posts.length).fill(false), Array(plantUserPosts.length).fill(false)]
let cSelectedImages = [Array(thisPlantPosts.length).fill(false), Array(thisPostsPosts.length).fill(false), Array(plantUserPosts.length).fill(false)]
setSelectedImages(cSelectedImages)


Expand Down Expand Up @@ -347,13 +352,64 @@ export function ImagePopup({show, hideCallback, id = 0}: ImagePopupProps) {

setMyImages((prev) => [...prev, newPost])
setThisImages((prev) => [...prev, newPost])
setSelectedImages((prev) => { console.log(prev); return prev})
let newSelectedImages = selectedImages
newSelectedImages[0].push(true)
newSelectedImages[2].push(true)
setSelectedImages(newSelectedImages)
setLoadingMessage("")
}

const moveImages = async () => {

// Find th
// Set the loading message
setLoadingMessage("Moving images")

// Find the selected images for the post gallery
let selectedPostImages : any = selectedImages[1].map((value, index) => {
if(value) return postImages[index]
})

// Remove the undefined values
selectedPostImages = selectedPostImages.filter((value: any) => value)

// If none are selected, return
if(!selectedPostImages) return

// Update the in use status of the selected images
await makeRequestWithToken("get","/api/posts/move?" + selectedPostImages.map((post: any) => `id=${post.id}`).join("&"))

// Move them to the plant images
setThisImages((prev) => {
setPostImages((prev) => [...prev, ...selectedPostImages])
return [...prev, ...selectedPostImages]
})

// If any are authored by the user, move them to the user images also
let selectedMyImages = selectedPostImages.filter((post: any) => post.post_user_id === (session?.user as RongoaUser).database.id)
if(selectedMyImages){
setMyImages((prev) => [...prev, ...selectedMyImages])
}

// Remove the selected images from the post images
let newPostImages = postImages.filter((post: any) => !selectedPostImages.includes(post))
setPostImages(newPostImages)

// Update the selected status
let newSelectedImages = selectedImages
newSelectedImages[0].push(...selectedPostImages.map(() => true))
newSelectedImages[1] = newSelectedImages[1].filter((value) => !value)
newSelectedImages[2].push(...selectedMyImages.map(() => true))
setSelectedImages(newSelectedImages)

// Clear the cache
sessionStorage.removeItem("editor_posts_"+id)
sessionStorage.removeItem("editor_posts_mine_"+id)

// Change tab
setTab(0)

// Clear loading message
setLoadingMessage("")

}

Expand Down
84 changes: 84 additions & 0 deletions website/src/pages/api/posts/move.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
import {NextApiRequest, NextApiResponse} from 'next';
import {getClient, getTables, makeQuery} from "@/lib/databse";
import {USE_POSTGRES} from "@/lib/constants";
import {getServerSession} from "next-auth";
import {authOptions} from "@/pages/api/auth/[...nextauth]";
import {checkApiPermissions} from "@/lib/api_tools";
import { Logger } from 'next-axiom';
import {MEMBER_USER_TYPE, RongoaUser} from "@/lib/users";

export default async function handler(
request: NextApiRequest,
response: NextApiResponse,
) {

// Get the logger
const logger = new Logger()


// Get the client
const client = await getClient()

// Check if the user is permitted to access the API
const session = await getServerSession(request, response, authOptions)
const permission = await checkApiPermissions(request, response, session, client, makeQuery, "api:plants:upload:access")
if(!permission) return response.status(401).json({error: "Not Authorized"})

// If there is no session then return an error
if(!session || !session.user) {
return response.status(401).json({ error: 'User not logged in'});
}

// Get the user details
const user = session.user as RongoaUser;
const user_id = user.database.id;
const user_is_member = user.database.user_type === MEMBER_USER_TYPE;

// Try uploading the data to the database
try {
let {
id,
} = request.query;


let ids = [];

// If no id is provided, return an error
if(!id) {
return response.status(400).json({error: "No ID provided"});
}

// If ids is an array, set it to the array
if(Array.isArray(id)) {
ids = id;
} else {
ids.push(id);
}

// Check if the data is being downloaded from the Postgres database
const tables = getTables()

// Update the posts in_use status
let query= "";
for (let i = 0; i < ids.length; i++) {
query = `UPDATE posts SET ${tables.post_in_use} = NOT ${tables.post_in_use} WHERE id = ${ids[i]};`;
}

// Make the query
await makeQuery(query, client, true);


// Log the upload
logger.info(`Move post ${id} by ${session?.user?.email}`);

return response.status(200).json({ message: "Upload Successful", id: id });
} catch (error) {
return response.status(500).json({message: "ERROR IN SERVER", error: error });
} finally {

if(USE_POSTGRES)
await client.end();

}
}

0 comments on commit 9accda3

Please sign in to comment.