Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: create new file page with improved UI, combine upload and downl… #58

Merged
merged 1 commit into from
Sep 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package downloadFileHandler
package downloadHandler

import (
"fmt"
Expand Down
17 changes: 9 additions & 8 deletions handler/download/download.go → handler/file/file.go
Original file line number Diff line number Diff line change
@@ -1,37 +1,38 @@
package downloadHandler
package fileHandler

import (
"fmt"
"github.com/fossyy/filekeeper/app"
"github.com/fossyy/filekeeper/view/client/download"
"net/http"

"github.com/fossyy/filekeeper/types"
"github.com/fossyy/filekeeper/utils"
fileView "github.com/fossyy/filekeeper/view/client/file"
"net/http"
"strconv"
)

func GET(w http.ResponseWriter, r *http.Request) {
userSession := r.Context().Value("user").(types.User)
files, err := app.Server.Database.GetFiles(userSession.UserID.String())
if err != nil {
fmt.Println(err.Error())
w.WriteHeader(http.StatusInternalServerError)
return
}

var filesData []types.FileData
for i := 0; i < len(files); i++ {
filesData = append(filesData, types.FileData{
ID: files[i].ID.String(),
Name: files[i].Name,
Size: utils.ConvertFileSize(files[i].Size),
Downloaded: files[i].Downloaded,
Downloaded: strconv.FormatUint(files[i].Downloaded, 10),
})
}

component := downloadView.Main("Filekeeper - Download Page", filesData)
component := fileView.Main("File Dashboard", filesData, userSession)
err = component.Render(r.Context(), w)
if err != nil {
fmt.Println(err.Error())
w.WriteHeader(http.StatusInternalServerError)
app.Server.Logger.Error(err.Error())
return
}
}
9 changes: 0 additions & 9 deletions handler/upload/upload.go → handler/file/upload/upload.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"fmt"
"github.com/fossyy/filekeeper/app"
"github.com/fossyy/filekeeper/types"
filesView "github.com/fossyy/filekeeper/view/client/upload"
"io"
"net/http"
"os"
Expand All @@ -13,14 +12,6 @@ import (
"strings"
)

func GET(w http.ResponseWriter, r *http.Request) {
component := filesView.Main("Filekeeper - Upload")
if err := component.Render(r.Context(), w); err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
}

func POST(w http.ResponseWriter, r *http.Request) {
fileID := r.PathValue("id")
if err := r.ParseMultipartForm(32 << 20); err != nil {
Expand Down
49 changes: 37 additions & 12 deletions handler/user/totp/setup.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bytes"
"encoding/base64"
"fmt"
"github.com/a-h/templ"
"github.com/fossyy/filekeeper/app"
"github.com/fossyy/filekeeper/view/client/user/totp"
"image/png"
Expand Down Expand Up @@ -41,10 +42,18 @@ func GET(w http.ResponseWriter, r *http.Request) {
return
}

component := userTotpSetupView.Main("Filekeeper - 2FA Setup Page", base64Str, secret, userSession, types.Message{
Code: 3,
Message: "",
})
var component templ.Component
if r.Header.Get("hx-request") == "true" {
component = userTotpSetupView.MainContent(base64Str, secret, userSession, types.Message{
Code: 3,
Message: "",
})
} else {
component = userTotpSetupView.Main("Filekeeper - 2FA Setup Page", base64Str, secret, userSession, types.Message{
Code: 3,
Message: "",
})
}
if err := component.Render(r.Context(), w); err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
Expand All @@ -69,26 +78,42 @@ func POST(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
return
}
var component templ.Component
if totp.Verify(code, time.Now().Unix()) {
if err := app.Server.Database.InitializeTotp(userSession.Email, secret); err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
app.Server.Service.DeleteUser(userSession.Email)
component := userTotpSetupView.Main("Filekeeper - 2FA Setup Page", base64Str, secret, userSession, types.Message{
Code: 1,
Message: "Your TOTP setup is complete! Your account is now more secure.",
})
if r.Header.Get("hx-request") == "true" {
component = userTotpSetupView.MainContent(base64Str, secret, userSession, types.Message{
Code: 1,
Message: "Your TOTP setup is complete! Your account is now more secure.",
})
} else {
component = userTotpSetupView.Main("Filekeeper - 2FA Setup Page", base64Str, secret, userSession, types.Message{
Code: 1,
Message: "Your TOTP setup is complete! Your account is now more secure.",
})
}

if err := component.Render(r.Context(), w); err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
return
} else {
component := userTotpSetupView.Main("Filekeeper - 2FA Setup Page", base64Str, secret, userSession, types.Message{
Code: 0,
Message: "The code you entered is incorrect. Please double-check the code and try again.",
})
if r.Header.Get("hx-request") == "true" {
component = userTotpSetupView.MainContent(base64Str, secret, userSession, types.Message{
Code: 0,
Message: "The code you entered is incorrect. Please double-check the code and try again.",
})
} else {
component = userTotpSetupView.Main("Filekeeper - 2FA Setup Page", base64Str, secret, userSession, types.Message{
Code: 0,
Message: "The code you entered is incorrect. Please double-check the code and try again.",
})
}
if err := component.Render(r.Context(), w); err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
Expand Down
33 changes: 23 additions & 10 deletions handler/user/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,6 @@ func GET(w http.ResponseWriter, r *http.Request) {
handlerWS(upgrade, userSession)
}

var component templ.Component
sessions, err := session.GetSessions(userSession.Email)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
Expand All @@ -86,21 +85,35 @@ func GET(w http.ResponseWriter, r *http.Request) {
AllowanceUsedPercent: fmt.Sprintf("%.2f", float64(usage)/float64(allowance.AllowanceByte)*100),
}

var component templ.Component
if err := r.URL.Query().Get("error"); err != "" {
message, ok := errorMessages[err]
if !ok {
message = "Unknown error occurred. Please contact support at bagas@fossy.my.id for assistance."
}

component = userView.Main("Filekeeper - User Page", userSession, allowanceStats, sessions, types.Message{
Code: 0,
Message: message,
})
if r.Header.Get("hx-request") == "true" {
component = userView.MainContent(userSession, allowanceStats, sessions, types.Message{
Code: 0,
Message: message,
})
} else {
component = userView.Main("Filekeeper - User Page", userSession, allowanceStats, sessions, types.Message{
Code: 0,
Message: message,
})
}
} else {
component = userView.Main("Filekeeper - User Page", userSession, allowanceStats, sessions, types.Message{
Code: 1,
Message: "",
})
if r.Header.Get("hx-request") == "true" {
component = userView.MainContent(userSession, allowanceStats, sessions, types.Message{
Code: 1,
Message: "",
})
} else {
component = userView.Main("Filekeeper - User Page", userSession, allowanceStats, sessions, types.Message{
Code: 1,
Message: "",
})
}
}
err = component.Render(r.Context(), w)
if err != nil {
Expand Down
91 changes: 31 additions & 60 deletions public/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -78,55 +78,32 @@ async function handleFile(file){
function addNewUploadElement(file){
const newDiv = document.createElement('div');
newDiv.innerHTML = `
<div class="p-6 rounded-lg shadow bg-gray-800 border-gray-700">
<div class="mb-2 flex justify-between items-center">
<div class="flex items-center gap-x-3">
<svg xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" width="100" height="100" viewBox="0 0 48 48">
<path fill="#90CAF9" d="M40 45L8 45 8 3 30 3 40 13z"></path>
<path fill="#E1F5FE" d="M38.5 14L29 14 29 4.5z"></path>
</svg>
<div>
<p class="text-sm font-medium text-white">${ file.name }</p>
<p class="text-xs text-gray-500">${ convertFileSize(file.size) }</p>
</div>
</div>
<div class="inline-flex items-center gap-x-2">
<a class="text-gray-500 hover:text-gray-800" href="#">
<svg class="flex-shrink-0 size-4" xmlns="http://www.w3.org/2000/svg" width="24" height="24"
viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"
stroke-linejoin="round">
<rect width="4" height="16" x="6" y="4" />
<rect width="4" height="16" x="14" y="4" />
</svg>
</a>
<a class="text-gray-500 hover:text-gray-800" href="#">
<svg class="flex-shrink-0 size-4" xmlns="http://www.w3.org/2000/svg" width="24" height="24"
viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"
stroke-linejoin="round">
<path d="M3 6h18" />
<path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6" />
<path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2" />
<line x1="10" x2="10" y1="11" y2="17" />
<line x1="14" x2="14" y1="11" y2="17" />
</svg>
</a>
</div>
</div>
<div class="flex items-center gap-x-3 whitespace-nowrap">
<div id="progress-${ file.name }-1" class="flex w-full h-2 rounded-full overflow-hidden bg-gray-200"
role="progressbar" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100">

<div id="progress-${ file.name }-2"
class="flex flex-col justify-center rounded-full overflow-hidden bg-teal-500 text-xs text-white text-center whitespace-nowrap transition duration-500">
</div>

</div>
<span id="progress-${ file.name }-3" class="text-sm text-white ">Starting...</span>
</div>
<div id="progress-${ file.name }-4" class="text-sm text-gray-500">Uploading 0%</div>
</div>
<div class="space-y-4">
<div class="p-4 flex justify-between items-center">
<div class="flex items-center space-x-2">
<div class="relative">
<svg class="w-12 h-12" viewBox="0 0 36 36" xmlns="http://www.w3.org/2000/svg">
<circle cx="18" cy="18" r="16" fill="none" class="stroke-current text-gray-200" stroke-width="2"></circle>
<circle id="progress-${ file.name }-1" cx="18" cy="18" r="16" fill="none" class="stroke-current text-blue-600" stroke-width="2" stroke-dasharray="100" stroke-dashoffset="100" transform="rotate(-90 18 18)"></circle>
</svg>
<div class="absolute inset-0 flex items-center justify-center">
<span id="progress-${ file.name }-2" class="text-xs font-medium">0%</span>
</div>
</div>
<div class="flex flex-col">
<span class="text-base font-medium truncate w-48">${ file.name }</span>
<div class="flex items-center gap-x-3 whitespace-nowrap">

</div>
<div id="progress-${ file.name }-3" class="text-sm text-gray-500">Starting...</div>
</div>
</div>
<button class="text-blue-500 text-base font-medium">Batal</button>
</div>
</div>
`;
document.getElementById('container').appendChild(newDiv);
document.getElementById('FileUploadBoxItem').appendChild(newDiv);
document.getElementById('uploadBox').classList.remove('hidden');
}

function convertFileSize(sizeInBytes) {
Expand All @@ -150,7 +127,6 @@ async function splitFile(file, chunkSize) {
const start = i * chunkSize;
const end = Math.min(fileSize, start + chunkSize);
const chunk = file.slice(start, end);
chunk.hash = "test"
fileChunks.push(chunk);
}

Expand All @@ -171,7 +147,6 @@ async function uploadChunks(name, size, chunks, chunkArray, FileID) {
let progress1 = document.getElementById(`progress-${name}-1`);
let progress2 = document.getElementById(`progress-${name}-2`);
let progress3 = document.getElementById(`progress-${name}-3`);
let progress4 = document.getElementById(`progress-${name}-4`);
let isFailed = false
for (let index = 0; index < chunks.length; index++) {
const percentComplete = Math.round((index + 1) / chunks.length * 100);
Expand All @@ -183,12 +158,12 @@ async function uploadChunks(name, size, chunks, chunkArray, FileID) {
formData.append('index', index);
formData.append('done', false);

progress1.setAttribute("aria-valuenow", percentComplete);
progress2.style.width = `${percentComplete}%`;
progress1.style.strokeDashoffset = 100 - percentComplete;
progress2.innerText = `${percentComplete}%`;

const startTime = performance.now();
try {
await fetch(`/upload/${FileID}`, {
await fetch(`/file/${FileID}`, {
method: 'POST',
body: formData
});
Expand All @@ -203,22 +178,18 @@ async function uploadChunks(name, size, chunks, chunkArray, FileID) {
const totalTime = (endTime - startTime) / 1000;
const uploadSpeed = chunk.size / totalTime / 1024 / 1024;
byteUploaded += chunk.size
progress3.innerText = `${uploadSpeed.toFixed(2)} MB/s`;
progress4.innerText = `Uploading ${percentComplete}% - ${convertFileSize(byteUploaded)} of ${ convertFileSize(size)}`;
progress3.innerText = `Uploading... ${uploadSpeed.toFixed(2)} MB/s`;
} else {
progress1.setAttribute("aria-valuenow", percentComplete);
progress2.style.width = `${percentComplete}%`;
progress1.style.strokeDashoffset = 100 - percentComplete;
progress2.innerText = `${percentComplete}%`;
progress3.innerText = `Fixing Missing Byte`;
progress4.innerText = `Uploading Missing Byte ${percentComplete}% - ${convertFileSize(byteUploaded)} of ${ convertFileSize(size)}`;
byteUploaded += chunk.size
}
}
if (isFailed) {
progress3.innerText = `Upload Failed`;
progress4.innerText = `There was an issue uploading the file. Please try again.`;
} else {
progress3.innerText = `Done`;
progress4.innerText = `File Uploaded 100% - ${convertFileSize(byteUploaded)} of ${ convertFileSize(size)}`;
}
}

Expand Down
20 changes: 8 additions & 12 deletions routes/client/routes.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,16 @@ import (
googleOauthCallbackHandler "github.com/fossyy/filekeeper/handler/auth/google/callback"
googleOauthSetupHandler "github.com/fossyy/filekeeper/handler/auth/google/setup"
totpHandler "github.com/fossyy/filekeeper/handler/auth/totp"
downloadHandler "github.com/fossyy/filekeeper/handler/download"
downloadFileHandler "github.com/fossyy/filekeeper/handler/download/file"
fileHandler "github.com/fossyy/filekeeper/handler/file"
downloadHandler "github.com/fossyy/filekeeper/handler/file/download"
uploadHandler "github.com/fossyy/filekeeper/handler/file/upload"
forgotPasswordHandler "github.com/fossyy/filekeeper/handler/forgotPassword"
forgotPasswordVerifyHandler "github.com/fossyy/filekeeper/handler/forgotPassword/verify"
indexHandler "github.com/fossyy/filekeeper/handler/index"
logoutHandler "github.com/fossyy/filekeeper/handler/logout"
signinHandler "github.com/fossyy/filekeeper/handler/signin"
signupHandler "github.com/fossyy/filekeeper/handler/signup"
signupVerifyHandler "github.com/fossyy/filekeeper/handler/signup/verify"
uploadHandler "github.com/fossyy/filekeeper/handler/upload"
userHandler "github.com/fossyy/filekeeper/handler/user"
userHandlerResetPassword "github.com/fossyy/filekeeper/handler/user/ResetPassword"
userSessionTerminateHandler "github.com/fossyy/filekeeper/handler/user/session/terminate"
Expand Down Expand Up @@ -109,20 +109,16 @@ func SetupRoutes() *http.ServeMux {
middleware.Auth(userHandlerTotpSetup.POST, w, r)
})

handler.HandleFunc("GET /upload", func(w http.ResponseWriter, r *http.Request) {
middleware.Auth(uploadHandler.GET, w, r)
handler.HandleFunc("GET /file", func(w http.ResponseWriter, r *http.Request) {
middleware.Auth(fileHandler.GET, w, r)
})

handler.HandleFunc("POST /upload/{id}", func(w http.ResponseWriter, r *http.Request) {
handler.HandleFunc("POST /file/{id}", func(w http.ResponseWriter, r *http.Request) {
middleware.Auth(uploadHandler.POST, w, r)
})

handler.HandleFunc("GET /download", func(w http.ResponseWriter, r *http.Request) {
middleware.Auth(downloadHandler.GET, w, r)
})

handler.HandleFunc("GET /download/{id}", func(w http.ResponseWriter, r *http.Request) {
downloadFileHandler.GET(w, r)
handler.HandleFunc("GET /file/{id}", func(w http.ResponseWriter, r *http.Request) {
downloadHandler.GET(w, r)
})

handler.HandleFunc("GET /logout", func(w http.ResponseWriter, r *http.Request) {
Expand Down
Loading
Loading