Commit 1ff4d5b6 authored by Lukas Böhm's avatar Lukas Böhm 🎱
Browse files

add zipping feature

parent 9832cf3d
package main package main
import ( import (
"archive/zip"
"bytes"
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
...@@ -8,6 +10,7 @@ import ( ...@@ -8,6 +10,7 @@ import (
"github.com/gorilla/mux" "github.com/gorilla/mux"
"github.com/rs/cors" "github.com/rs/cors"
"gorm.io/gorm" "gorm.io/gorm"
"io"
"io/ioutil" "io/ioutil"
"log" "log"
"net/http" "net/http"
...@@ -55,7 +58,7 @@ func GetShare(w http.ResponseWriter, r *http.Request) *HTTPError { ...@@ -55,7 +58,7 @@ func GetShare(w http.ResponseWriter, r *http.Request) *HTTPError {
vars := mux.Vars(r) vars := mux.Vars(r)
shareID, err := uuid.Parse(vars["id"]) shareID, err := uuid.Parse(vars["id"])
if err != nil { if err != nil {
return &HTTPError{ errors.New("invalid URL"), "invalid URL param", 400 } return &HTTPError{ err, "invalid URL param", 400 }
} }
db, err := GetDatabase() db, err := GetDatabase()
...@@ -96,11 +99,11 @@ func DownloadFile(w http.ResponseWriter, r *http.Request) *HTTPError { ...@@ -96,11 +99,11 @@ func DownloadFile(w http.ResponseWriter, r *http.Request) *HTTPError {
vars := mux.Vars(r) vars := mux.Vars(r)
shareID, err := uuid.Parse(vars["id"]) shareID, err := uuid.Parse(vars["id"])
if err != nil { if err != nil {
return &HTTPError{ errors.New("invalid URL"), "invalid URL param", 400 } return &HTTPError{ err, "invalid URL param", 400 }
} }
attID, err := uuid.Parse(vars["att"]) attID, err := uuid.Parse(vars["att"])
if err != nil { if err != nil {
return &HTTPError{ errors.New("invalid URL"), "invalid URL param", 400 } return &HTTPError{ err, "invalid URL param", 400 }
} }
db, err := GetDatabase() db, err := GetDatabase()
...@@ -180,7 +183,7 @@ func CloseShare(w http.ResponseWriter, r *http.Request) *HTTPError { ...@@ -180,7 +183,7 @@ func CloseShare(w http.ResponseWriter, r *http.Request) *HTTPError {
vars := mux.Vars(r) vars := mux.Vars(r)
shareID, err := uuid.Parse(vars["id"]) shareID, err := uuid.Parse(vars["id"])
if err != nil { if err != nil {
return &HTTPError{ errors.New("invalid URL"), "invalid URL param", 400 } return &HTTPError{ err, "invalid URL param", 400 }
} }
db, err := GetDatabase() db, err := GetDatabase()
...@@ -223,7 +226,7 @@ func UploadAttachment(w http.ResponseWriter, r *http.Request) *HTTPError { ...@@ -223,7 +226,7 @@ func UploadAttachment(w http.ResponseWriter, r *http.Request) *HTTPError {
vars := mux.Vars(r) vars := mux.Vars(r)
shareID, err := uuid.Parse(vars["id"]) shareID, err := uuid.Parse(vars["id"])
if err != nil { if err != nil {
return &HTTPError{ errors.New("invalid URL"), "invalid URL param", 400 } return &HTTPError{ err, "invalid URL param", 400 }
} }
db, err := GetDatabase() db, err := GetDatabase()
...@@ -241,7 +244,7 @@ func UploadAttachment(w http.ResponseWriter, r *http.Request) *HTTPError { ...@@ -241,7 +244,7 @@ func UploadAttachment(w http.ResponseWriter, r *http.Request) *HTTPError {
return &HTTPError{err, "Can't fetch data", 500} return &HTTPError{err, "Can't fetch data", 500}
} }
if share.IsTemporary != true { if share.IsTemporary != true {
return &HTTPError{ errors.New("Can't upload to finalized shares"), "Can't upload to finalized Shares.", 403 } return &HTTPError{ err, "Can't upload to finalized Shares.", 403 }
} }
// Parse file from body // Parse file from body
...@@ -284,9 +287,74 @@ func UploadAttachment(w http.ResponseWriter, r *http.Request) *HTTPError { ...@@ -284,9 +287,74 @@ func UploadAttachment(w http.ResponseWriter, r *http.Request) *HTTPError {
return SendJSON(w, att) return SendJSON(w, att)
} }
func DownloadZip(w http.ResponseWriter, r *http.Request) *HTTPError {
fmt.Println("DownloadZip")
vars := mux.Vars(r)
shareID, err := uuid.Parse(vars["id"])
if err != nil {
return &HTTPError{ err, "invalid URL param", 400 }
}
share, er := RetrieveShare(shareID, true)
if er != nil {
return er
}
//comp, _ := zip2.Compressor(w)
zipWriter := zip.NewWriter(w)
for _, file := range share.Attachments {
filePath := filepath.Join(config.mediaDir, "data", file.ShareID.String(), file.ID.String())
fw, err := zipWriter.Create(filePath)
if err != nil {
return &HTTPError{ err, "error when zipping", 500}
}
fileContent, err := ioutil.ReadFile(filePath)
if err != nil {
return &HTTPError{ err, "error when reading file to zip", 500 }
}
_, err = io.Copy(fw, bytes.NewReader(fileContent))
if err != nil {
return &HTTPError{ err, "error when writing file to zip", 500 }
}
}
err = zipWriter.Close()
if err != nil {
return &HTTPError{ err, "error when closing zip", 500 }
}
return nil
}
///////////////////////////////// /////////////////////////////////
////////// functions //////////// ////////// functions ////////////
///////////////////////////////// /////////////////////////////////
func RetrieveShare(shareID uuid.UUID, withAtt bool) (*Share, *HTTPError) {
db, err := GetDatabase()
if err != nil {
return nil, &HTTPError{err, "Can't get database", 500}
}
var share Share
if withAtt == true {
err = db.Preload("Attachments").Where("ID = ?", shareID).First(&share).Error
}else {
err = db.Where("ID = ?", shareID).First(&share).Error
}
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, &HTTPError{err, "Record not found", 404}
}
if err != nil {
return nil, &HTTPError{err, "Can't fetch data", 500}
}
if share.IsTemporary == true {
return nil, &HTTPError{err, "Share is not finalized", 403}
}
return &share, nil
}
func ConfigureRoutes() { func ConfigureRoutes() {
router := mux.NewRouter().StrictSlash(true) router := mux.NewRouter().StrictSlash(true)
handler := cors.Default().Handler(router) handler := cors.Default().Handler(router)
...@@ -300,6 +368,7 @@ func ConfigureRoutes() { ...@@ -300,6 +368,7 @@ func ConfigureRoutes() {
router.Handle("/share/{id}/attachments", endpointREST(UploadAttachment)).Methods("POST") router.Handle("/share/{id}/attachments", endpointREST(UploadAttachment)).Methods("POST")
router.Handle("/share/{id}/attachment/{att}", endpointREST(DownloadFile)).Methods("GET") router.Handle("/share/{id}/attachment/{att}", endpointREST(DownloadFile)).Methods("GET")
router.Handle("/share/{id}/zip", endpointREST(DownloadZip)).Methods("GET")
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", config.port), handler)) log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", config.port), handler))
} }
......
...@@ -40,24 +40,26 @@ ...@@ -40,24 +40,26 @@
</svg> </svg>
<script> <script>
$("button:parent").click(function (e) { $("button:parent").click(function (e) {
console.log("download file");
e.preventDefault(); e.preventDefault();
window.location.href = `http://localhost:6969/share/{{ up.id }}/attachment/{{ file.id }}`; window.location.href = `http://localhost:6969/share/{{ up.id }}/attachment/{{ file.id }}`;
}) });
</script> </script>
</button> </button>
</li> </li>
{% endfor %} {% endfor %}
</ul> </ul>
{% if up.is_zipped %} <div class="input-group">
<div class="input-group"> <button class="btn btn-block btn-outline-primary" id="download-zip">
<a href="{{ url_for('zip_attachments', share_id=up.id) }}" download Dateien gepackt herunterladen
class="btn btn-block btn-outline-primary"> </button>
Dateien gepackt herunterladen </div>
</a> <script>
</div> $("#download-zip").click(function (e) {
{% endif %} e.preventDefault();
window.location.href = `http://localhost:6969/share/{{ up.id }}/zip`;
});
</script>
</div> </div>
</div> </div>
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment