Skip to content

Commit

Permalink
Documents (#8)
Browse files Browse the repository at this point in the history
* add route to receive urls...

* upload art fxn

* add layerdata

* good shape, good upload and merge data
  • Loading branch information
Kiel-H-Byrne authored Jun 15, 2022
1 parent fbc6b72 commit 9aac510
Show file tree
Hide file tree
Showing 5 changed files with 151 additions and 41 deletions.
67 changes: 57 additions & 10 deletions components/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,10 @@ import {
GridItem,
FormHelperText,
Progress,
Text,
} from "@chakra-ui/react"
import { BaseSyntheticEvent, useState } from "react"
import { uploadImage } from "./db/firebase"
import { artworkSet, storeImage } from "./db/firebase"

//get length
const BASE_PATH = `/gallery/`
Expand All @@ -31,26 +32,32 @@ function App() {
// const [imageURI, setImageURI] = useState("")
const [previewURI, setPreviewURI] = useState("")
const [errorMsg, setErrorMsg] = useState("")
const [projectId, setProjectId] = useState("")
const [uploadStatus, setUploadStatus] = useState("")
const [layerImages, setLayerImages] = useState([])
const [fuzzNum, setFuzzNum] = useState(0)
const [colorsNum, setColorsNum] = useState(0)

type ILayers = {
type IUploadSettings = {
awid: string
imageUrl: string | undefined
fuzz: number
fuzz: string
numDominantColorsToExtract: number
}

const onClickUpload = async () => {
setUploadStatus("UPLOADING...")
setUploadStatus("STORING IMAGE...")
if (userImage) {
const imageUrl = await uploadImage(userImage)
const imageUrl = await storeImage(userImage)
setUploadStatus("UPLOADING DOCUMENT....")
const awid = await artworkSet({ sourceImageUri: imageUrl })
const metadata = {
awid,
imageUrl,
fuzz: fuzzNum,
fuzz: `${fuzzNum}%`,
numDominantColorsToExtract: colorsNum,
}
setProjectId(awid)
setUploadStatus("GETTING LAYERS....")
// uri && setImageURI(uri)
imageUrl && getLayers(metadata)
Expand All @@ -74,10 +81,11 @@ function App() {
}

const getLayers = async ({
awid,
imageUrl,
fuzz,
numDominantColorsToExtract,
}: ILayers) => {
}: IUploadSettings) => {
// post image to url, get response back,
// response is array of images and metadata
// Example POST method implementation:
Expand All @@ -87,6 +95,8 @@ function App() {
imageUrl,
fuzz,
numDominantColorsToExtract,
isWhiteTransparent: true,
// filename
}

const response = await fetch(POST_URI, {
Expand Down Expand Up @@ -115,11 +125,47 @@ function App() {
setErrorMsg("Error Fetching Layers: " + err.message)
console.error("error", err)
})
console.log(response)
setLayerImages(response.urls) // parses JSON response into native JavaScript objects
const layerData = response.urls.map((url: string, i: number) => ({
[response.dominantColors[i].hexCode]: {
depthNumber: 1,
imageUri: url,
rarity: "normal",
},
}))
const ref = await artworkSet({ awid, layers: layerData })
setUploadStatus("")
}
const assembleImages = async () => {
// get urls of each layer, save to fs in certain way, then run generate script
const response = await fetch("./api/gen", {
method: "POST", // *GET, POST, PUT, DELETE, etc.
mode: "same-origin", // no-cors, *cors, same-origin
// cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
// credentials: "same-origin", // include, *same-origin, omit
headers: {
"Content-Type": "application/json",
},
// redirect: "follow", // manual, *follow, error
// referrerPolicy: "no-referrer", // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
body: JSON.stringify(layerImages), // body data type must match "Content-Type" header
})
.then((response) => {
if (!response.ok) {
return response
.text()
.then((result) => Promise.reject(new Error(result)))
}
setUploadStatus("DISPLAYING LAYERS....")
return response.json()
})
.then((data) => data)
.catch((err) => {
setErrorMsg("Error Fetching Layers: " + err.message)
console.error("error", err)
})
console.log(response)
}
return (
<Box className="App">
Expand All @@ -142,12 +188,12 @@ function App() {
/>
{previewURI && (
<Box>
<FormLabel width={"50%"}>Amount of Fuzz</FormLabel>
<FormLabel width={"50%"}>Amount of Fuzz (0-100%)</FormLabel>
<Input
id="fuzzNum"
type="number"
min={0}
max={2000}
max={100}
onChange={(ev) => setFuzzNum(Number(ev.target.value))}
/>
<FormLabel width={"50%"}>Amount of Colors (layers)</FormLabel>
Expand All @@ -163,9 +209,10 @@ function App() {
{uploadStatus && <Progress size="xs" isIndeterminate />}
</Box>
)}
{projectId && <Text>Project ID: {projectId}</Text>}
{layerImages?.length > 0 && (
<Grid
templateColumns="repeat(5, 1fr)"
templateColumns="repeat(3, 1fr)"
gap={5}
overflowX="scroll"
width="100vw"
Expand Down
60 changes: 57 additions & 3 deletions components/db/firebase.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,15 @@
import { initializeApp } from "firebase/app"
import { getDownloadURL, getStorage, ref, uploadBytes } from "firebase/storage"
import {
collection,
doc,
getDoc,
initializeFirestore,
setDoc,
} from "firebase/firestore"
// import { getAuth, useDeviceLanguage } from "firebase/auth"
// import { getAnalytics } from "firebase/analytics"
import { nanoid } from "nanoid"

const firebaseConfig = {
apiKey: "AIzaSyB_AvlJ-tlRx7dGtZ_qUmzCEw2ekQ11XoI",
Expand All @@ -12,12 +21,16 @@ const firebaseConfig = {
measurementId: "G-GXR2KSL74L",
}

export const appRef = initializeApp(firebaseConfig)
const appRef = initializeApp(firebaseConfig)
// export const analytics = getAnalytics(appRef)
export const fbStorage = getStorage(appRef)
const fsdb = initializeFirestore(appRef, {})
const fbStorage = getStorage(appRef)
// useDeviceLanguage(getAuth())
const uploadsRef = collection(fsdb, "UPLOADS")

// const storageRef = ref(fbStorage, "/uploads")

export const uploadImage = async (image: File) => {
export const storeImage = async (image: File) => {
if (image) {
const storageRef = ref(fbStorage, `/uploads/${image.name}`)
await uploadBytes(storageRef, image, {})
Expand All @@ -26,3 +39,44 @@ export const uploadImage = async (image: File) => {
return imageURI
}
}

// == ARTWORKS ================================== //

interface ILayer {
[name: string]: {
depthNumber?: number
imageUri: string
rarity?: string
}
}
interface IUploadedImage {
uid?: string
awid: string
sourceImageUri: string | undefined
dateTime?: string
fuzz?: number
numDominantColorsToExtract?: number
isWhiteTransparent?: boolean
layers?: ILayer
editions?: number
}
export const artworkSet = async function (data: Partial<IUploadedImage>) {
const artworkID = data.awid ?? nanoid()
const dateTime = data.dateTime ?? new Date().toISOString()
const origData = {
awid: artworkID,
dateTime,
}
const docRef = doc(uploadsRef, artworkID)
console.log("submitting to db...", { ...data, ...origData })
await setDoc(docRef, { ...origData, ...data }, { merge: true })
return artworkID
}

export const artworkFetch = async function (id: string) {
const docRef = doc(uploadsRef, id)
const docSnap = await getDoc(docRef)
return docSnap.exists() && docSnap.data()
}


36 changes: 36 additions & 0 deletions pages/api/gen/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,39 @@
// store images in folders
// run generate commands with params
// upload images to store and return urls to all images

import { createWriteStream } from "fs"
import { NextApiRequest, NextApiResponse } from "next"

export default async function downloadHandler(
req: NextApiRequest,
res: NextApiResponse,
) {
const { method } = req

switch (method) {
case "POST": {
const path = "./images/image.png"
const download = (url, path, callback) => {
console.log("downloading file...")
}
const uris = req.body as string[]
console.log(uris)
uris.forEach((uri) => {
download(uri, path, () => {
console.log(uri.substring(uri.lastIndexOf("/") + 1))
console.log("✅ Done!")
})
})
// download each uri
// link uri or file to config metadata
//
break
}

default:
res.status(400).json({ itemnotfound: "No file" })
break
}
}

28 changes: 0 additions & 28 deletions src/db/firebase.ts

This file was deleted.

1 change: 1 addition & 0 deletions tsconfig.tsbuildinfo

Large diffs are not rendered by default.

1 comment on commit 9aac510

@vercel
Copy link

@vercel vercel bot commented on 9aac510 Jun 15, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.