Skip to content

Commit

Permalink
v0.0.1
Browse files Browse the repository at this point in the history
  • Loading branch information
KunalSin9h committed Jan 13, 2023
1 parent 1c9d0d4 commit 395b771
Show file tree
Hide file tree
Showing 8 changed files with 255 additions and 29 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,6 @@

# Dependency directories (remove the comment below to include it)
# vendor/

database/
*.db
Binary file removed database/dev.db
Binary file not shown.
85 changes: 85 additions & 0 deletions src/api/getImage.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
package api

import (
"encoding/json"
"io"
"log"
"net/http"

"github.com/znip-in/tiddi/src/db"
)

type GetImageRequest struct {
Uiid string `json:"uiid"`
}

type GetImageResponse struct {
Title string `json:"title"`
Image []byte `json:"data"`
}

/*
GetImage is the endpoint to get the image details
Endpoint: POST https://your-domain.com/get-image/
@description
Request.Body = {
"uiid": "uiid of the image"
}
`uiid` -> Unique Image Id
@author Kunal Singh <[email protected]>
@type Api Handler Function
*/
func GetImage(w http.ResponseWriter, r *http.Request) {
EnableCors(&w)
data, err := io.ReadAll(r.Body)

if err != nil || len(data) == 0 {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("Bad Request"))
return
}

var request GetImageRequest
if err := json.Unmarshal(data, &request); err != nil {
log.Printf("[GET-IMAGE] unable to unmarshal data received: %v\n", err)
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("Internal Server Error"))
return
}

if request.Uiid == "" {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("Bad Request"))
return
}

title, image, err := db.GetImageDetails(request.Uiid)

if err != nil {
log.Printf("[GET-IMAGE] Unable to get image details: %v\n", err)
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("Internal Server Error"))
return
}

response := GetImageResponse{
Title: title,
Image: image,
}

resBytes, err := json.Marshal(response)

if err != nil {
log.Printf("[GET-IMAGE] Unable to marshal response: %v\n", err)
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("Internal Server Error"))
return
}

w.WriteHeader(http.StatusOK)
w.Write(resBytes)
}
25 changes: 23 additions & 2 deletions src/api/home.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ import (
"github.com/znip-in/tiddi/src/db"
)

type PostURL struct {
postURL string
}

/*
Home
Endpoint: https://your-domain.com/
Expand All @@ -27,7 +31,24 @@ func Home(w http.ResponseWriter, r *http.Request) {
*/
if r.URL.Path == "/" {
// show the sample client
w.Write([]byte("Home"))
// from ../frontend
http.ServeFile(w, r, "./src/frontend/index.html")
/*
html, err := template.ParseFiles("./src/frontend/index.html")
if err != nil {
log.Printf("[HOME HTML] Unable to parse html from ./src/frontend/index.html: %v", err)
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("Internal Server Error"))
return
}
pr := PostURL{
postURL: os.Getenv("HOST"),
}
html.Execute(w, pr)
*/
} else {
// GET https://your-domain.com/93s9x_
// Give the image with the id
Expand All @@ -44,7 +65,7 @@ func Home(w http.ResponseWriter, r *http.Request) {
return
}

image, err := db.GetImage(uiid)
image, err := db.GetImageBytes(uiid)

if err != nil {
log.Printf("[GET-IMAGE] unable to get image form db: %v", err)
Expand Down
25 changes: 9 additions & 16 deletions src/api/uploadImage.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ func UploadImage(w http.ResponseWriter, r *http.Request) {
Data, err := io.ReadAll(r.Body)

if err != nil {
log.Printf("[UPLOAD-IMAGE] Error Reading Request Body: %v", err)
log.Printf("[UPLOAD-IMAGE] Error Reading Request Body: %v\n", err)
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("Internal Server Error"))
return
Expand All @@ -51,14 +51,14 @@ func UploadImage(w http.ResponseWriter, r *http.Request) {
err = json.Unmarshal(Data, &request)

if err != nil {
log.Printf("[UPLOAD-IMAGE] Error Parsing Request Body: %v", err)
log.Printf("[UPLOAD-IMAGE] Error Parsing Request Body: %v\n", err)
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("Internal Server Error"))
return
}

if request.Data == nil {
log.Printf("[UPLOAD-IMAGE] Missing Data (image []byte) Request Body: %v", err)
log.Printf("[UPLOAD-IMAGE] Missing Data (image []byte) Request Body: %v\n", err)
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("Bad Request"))
return
Expand All @@ -67,7 +67,7 @@ func UploadImage(w http.ResponseWriter, r *http.Request) {
uniqueImageId, err := uuid.New(7)

if err != nil {
log.Printf("[UPLOAD-IMAGE] Error Generating Unique Image Id: %v", err)
log.Printf("[UPLOAD-IMAGE] Error Generating Unique Image Id: %v\n", err)
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("Internal Server Error"))
return
Expand All @@ -76,34 +76,27 @@ func UploadImage(w http.ResponseWriter, r *http.Request) {
err = db.StoreImage(uniqueImageId, request.Title, request.Data)

if err != nil {
log.Printf("[STORE IMAGE] Error storing Data into db, %v", err)
log.Printf("[STORE IMAGE] Error storing Data into db, %v\n", err)
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("Internal Server Error"))
return
}

if os.Getenv("DOMAIN") == "" {
log.Println("[UPLOAD-IMAGE] Domain is absent while preparing image url")
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("Internal Server Error"))
return
}

if os.Getenv("PORT") == "" {
log.Println("[UPLOAD-IMAGE] Port is absent while preparing image url")
if os.Getenv("HOST") == "" {
log.Println("[UPLOAD-IMAGE] HOST is absent while preparing image url")
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("Internal Server Error"))
return
}

response := UploadImageResponse{
URL: fmt.Sprintf("%s:%s/%s", os.Getenv("DOMAIN"), os.Getenv("PORT"), uniqueImageId),
URL: fmt.Sprintf("%s/%s", os.Getenv("HOST"), uniqueImageId),
}

jsonResponse, err := json.Marshal(response)

if err != nil {
log.Printf("[UPLOAD-IMAGE] Error while sending response Data: %v", err)
log.Printf("[UPLOAD-IMAGE] Error while sending response Data: %v\n", err)
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("Internal Server Error"))
return
Expand Down
15 changes: 14 additions & 1 deletion src/db/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ func StoreImage(uiid, title string, imageData []byte) error {
return nil
}

func GetImage(uiid string) ([]byte, error) {
func GetImageBytes(uiid string) ([]byte, error) {
var image []byte
err := DATABASE.QueryRow("SELECT image FROM images WHERE id = ?", uiid).Scan(&image)

Expand All @@ -56,3 +56,16 @@ func GetImage(uiid string) ([]byte, error) {
return image, nil

}

func GetImageDetails(uiid string) (string, []byte, error) {
var title string
var image []byte
err := DATABASE.QueryRow("SELECT title, image FROM images WHERE id = ?", uiid).Scan(&title, &image)

if err != nil {
return "", nil, errors.New("could not get image details from db")
}

return title, image, nil

}
106 changes: 106 additions & 0 deletions src/frontend/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Upload Image</title>
<style>
body {
padding: 0;
margin: 0;
background-color: antiquewhite;
font-family: Verdana, Geneva, Tahoma, sans-serif;
}
.form-container {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 70%;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
.link {
width: 100%;
max-width: 600px;
}
a {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
letter-spacing: 1px;
}

</style>
</head>
<body>
<div class="form-container">
<form id="form">
<input type="file" id="file" accept="image/*" name="filename ">
<input type="submit" id="submit" class="btn">
</form>
<div class="link">
</div>
</div>
<script>

const submit = document.getElementById("submit")
const file = document.getElementById("file")
const linkBox = document.querySelector('.link')

function showBox(color, colorLight, inner){
linkBox.style.padding = '5px'
linkBox.style.marginTop = '15px'
linkBox.style.borderRadius = '10px'
linkBox.style.border = `1px solid ${color}`
linkBox.style.backgroundColor = colorLight
linkBox.innerHTML = inner
}


async function postData(data) {
// Use Go template to provide url
const resp = await fetch("http://localhost:5656/upload-image/", {
method: "POST",
mode: "cors",
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
return resp.json()
}

submit.addEventListener('click', (e) => {
e.preventDefault()

showBox("black", "#d3d3d3", "<p>Getting URL...</p>")

const reader = new FileReader()

reader.readAsArrayBuffer(file.files[0])

reader.onload = function() {
const title = file.files[0].name
const uint8array = new Uint8Array(reader.result);
const bytes = Array.from(uint8array)

postData({
title,
data: bytes
}).then((data) => {
showBox("green", "#DAF7A6", `<p><strong>URL</strong>: <a href="${data.url}" target=_black>${data.url}</a>`)
}).catch(() => {
showBox("red", "#FFCCCB", "<p>Something went wrong, try again!</p>")
})
};

reader.onerror = function() {
showBox("red", "#FFCCCB", "<p>Something went wrong, try again!</p>")
};
})

</script>
</body>
</html>
Loading

0 comments on commit 395b771

Please sign in to comment.