Skip to content
Draft
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
Server version part 2
  • Loading branch information
serhack committed Aug 7, 2022
commit 4f01ba1b7b8fde6d977027946e8123460a5a942b
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,5 @@
# vendor/

*.pdf
generated/
generated/
data/
13 changes: 12 additions & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ type Pixel struct {
}

var rmaster, gmaster, bmaster float64
var hash1 string

func rgbaToPixel(r uint32, g uint32, b uint32, a uint32) Pixel {
return Pixel{uint8(r >> 8), uint8(g >> 8), uint8(b >> 8), uint8(a >> 8), false}
Expand Down Expand Up @@ -136,7 +137,7 @@ func CompareSingleImage(path1 string, path2 string, i int) {
}

// Create the file under "generated" folder
f, err := os.Create("generated/image-" + strconv.Itoa(i) + ".png")
f, err := os.Create("generated/" + hash1 + "/image-" + strconv.Itoa(i) + ".png")
if err != nil {
panic(err)
}
Expand Down Expand Up @@ -181,6 +182,7 @@ func Compare(PDF1 string, PDF2 string) {
// Compares the two files

shaPDF1 := ComputeSha256(PDF1)
hash1 = shaPDF1
shaPDF2 := ComputeSha256(PDF2)

if _, err := os.Stat("generated"); errors.Is(err, os.ErrNotExist) {
Expand All @@ -190,6 +192,15 @@ func Compare(PDF1 string, PDF2 string) {
}
}

if _, err := os.Stat("generated/" + shaPDF1); errors.Is(err, os.ErrNotExist) {
err := os.Mkdir("generated/"+shaPDF1, os.ModePerm)
if err != nil {
panic(err)
}
} else {
return
}

i := 1
k := 1
for {
Expand Down
Binary file removed pdf-diff
Binary file not shown.
183 changes: 170 additions & 13 deletions server.go
Original file line number Diff line number Diff line change
@@ -1,55 +1,212 @@
package main

import (
"errors"
"fmt"
"net/http"
"html/template"
"io"
"net/http"
"os"
//"os/exec"
"path/filepath"
"strings"
)

func indexController(w http.ResponseWriter, r *http.Request){
if r.Method != "GET"{
type DiffImage struct{
Number int // page number
Filename string // file1
}

type ResultPage struct{
Hash1 string
Hash2 string
Differences []DiffImage
}

func indexController(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
fmt.Println("A new request has been made on / but the method " + r.Method + " was not supported.")
return
}

// TODO (idea): list pdf on upload folders

// Display the compare page
t, _ := template.ParseFiles("templates/index.html")
t.Execute(w, nil)

}

func compareController(w http.ResponseWriter, r *http.Request){

if r.Method == "GET"{
func compareController(w http.ResponseWriter, r *http.Request) {
// Set a limit of 32 MB per request
r.Body = http.MaxBytesReader(w, r.Body, 32<<20)

if r.Method == "GET" {
// Redirect to index page
http.Redirect(w, r, "/", http.StatusMovedPermanently)
} else if r.Method == "POST"{
} else if r.Method == "POST" {
parseErr := r.ParseMultipartForm(32 << 20)
if parseErr != nil {
http.Error(w, "failed to parse multipart message", http.StatusBadRequest)
return
}

if len(r.MultipartForm.File) != 2 {
http.Error(w, "two file pdfs per comparision", http.StatusBadRequest)
return
}

// Grab the two PDF(s) from the form

pdfFile1 := r.MultipartForm.File["pdf-1"]
pdfFile2 := r.MultipartForm.File["pdf-2"]

// Check if it's a real PDF
// Check if the two files are PDF

// Sanitize the name of the pdf
file1, err := pdfFile1[0].Open()
if err != nil {
panic(err)
}
defer file1.Close()

// Write them in upload folder
buff := make([]byte, 512)
if _, err = file1.Read(buff); err != nil {
panic(err) // do something with that error
}

var pdf1hash string

if http.DetectContentType(buff) == "application/pdf" {
out, err := os.Create("uploads/" + filepath.Clean(pdfFile1[0].Filename))
if err != nil {
panic(err)
}
_, err = file1.Seek(0, io.SeekStart)
if err != nil{
panic(err)
}
io.Copy(out, file1)
pdf1hash = ComputeSha256("uploads/" + filepath.Clean(pdfFile1[0].Filename))
}

file2, err := pdfFile2[0].Open()
if err != nil {
panic(err)
}
defer file2.Close()
if _, err = file2.Read(buff); err != nil {
panic(err)
}

var pdf2hash string

if http.DetectContentType(buff) == "application/pdf" {
// Write them in upload folder
out, err := os.Create("uploads/" + filepath.Clean(pdfFile2[0].Filename))
if err != nil {
panic(err)
}
_, err = file2.Seek(0, io.SeekStart)
if err != nil{
panic(err)
}
io.Copy(out, file2)
pdf2hash = ComputeSha256("uploads/" + filepath.Clean(pdfFile2[0].Filename))
}

fmt.Println("Starting a new job....")
// Start the job

/*cmd := exec.Command("./pdf-diff" + "uploads/" + filepath.Clean(pdfFile1[0].Filename) + " uploads/" + filepath.Clean(pdfFile2[0].Filename))
err = cmd.Start()
if err != nil {
panic(err)
}
*/

hexToRGB("ff2010")
CreatePNG("uploads/" + filepath.Clean(pdfFile1[0].Filename))
CreatePNG("uploads/" + filepath.Clean(pdfFile2[0].Filename))
Compare("uploads/" + filepath.Clean(pdfFile1[0].Filename), "uploads/" + filepath.Clean(pdfFile2[0].Filename))

// Redirect to result page
http.Redirect(w, r, "/compare/"+pdf1hash+"-"+pdf2hash, http.StatusMovedPermanently)

} else {
fmt.Println("A new request has been made on /compare but the method " + r.Method + " was not supported.")
return
}

}

func StartServer(){
func retrieveFilesController(w http.ResponseWriter, r *http.Request) {
slug := r.URL.Path[len("/compare/"):]
hashes := strings.Split(slug, "-")
fmt.Printf("%s ", hashes[0])
fmt.Printf("%s \n", hashes[1])

// Checks if the folder were already created

if _, err := os.Stat("generated/" + hashes[0]); errors.Is(err, os.ErrNotExist) {
http.Error(w, "not available", http.StatusNotFound)
return
}

// Checks the result generated


// List all the images given a filename (e.g. filename-1.png)

f, err := os.Open("generated/" + hashes[0])
if err != nil {
fmt.Println(err)
return
}
files, err := f.Readdir(0)
if err != nil {
fmt.Println(err)
return
}
i := 0
var differences []DiffImage


for _, v := range files {
single := DiffImage{
Number: i,
Filename: v.Name(),
}
differences = append(differences, single)
i++
}

structure := ResultPage{
Hash1: hashes[0],
Hash2: hashes[1],
Differences: differences,
}

t := template.Must(template.ParseFiles("templates/result.html"))
if err != nil {
panic(err)
}

err = t.Execute(w, structure)
if err != nil{
panic(err)
}
}

func StartServer() {

http.HandleFunc("/", indexController)
http.HandleFunc("/compare", compareController)
http.HandleFunc("/compare/", retrieveFilesController)

http.Handle("/results/", http.StripPrefix("/results/", http.FileServer(http.Dir("./generated"))))

err := http.ListenAndServe(":8080", nil)
if err != nil {
panic(err)
}

}
}
6 changes: 3 additions & 3 deletions templates/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -35,16 +35,16 @@
<body>
<div class="content">
<h1>pdf-diff</h1>
<p>Choose two file pdfs with the same dimensions to compare. <pre>pdf-diff</pre> will captures each page as an image and compares those to produce a fantastic detailed result.</p>
<p>Choose two file pdfs with the same dimensions to compare. <pre>pdf-diff</pre> will captures each page as an image and compares those.</p>
<hr>
<form method="POST" enctype="multipart/form-data" action="/compare">
<div class="form-row">
<label for="pdf-1">First PDF file:</label>
<input type="file" id="pdf-1">
<input type="file" id="pdf-1" name="pdf-1">
</div>
<div class="form-row">
<label for="pdf-2">Second PDF file:</label>
<input type="file" id="pdf-2">
<input type="file" id="pdf-2" name="pdf-2">
</div>
<div class="form-row">
<input type="submit">
Expand Down
43 changes: 43 additions & 0 deletions templates/result.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<!DOCTYPE html>
<html>
<head>
<title>Result</title>
</head>
<style>
body {
font-family:Verdana, Geneva, Tahoma, sans-serif;
padding:10px;
}

pre{
display:inline-block;
}

.content{
width: 50%
}

img{
border: 1px solid black;
max-width: 800px;
}

</style>
<body>
<div class="content">
<h2>Result of the comparison</h2>
<p>The following is the result between <pre>{{.Hash1}}</pre> and <pre>{{.Hash2}}</pre> files.</p>

{{ range .Differences }}
<div class="result-box">
<p>Page {{.Number}}:</p>
<img src="/results/{{$.Hash1}}/{{.Filename}}">
</div>
{{ end }}
<hr>
<footer>
<small>Server source code available at <a href="https://github.com/serhack/pdf-diff">serhack/pdf-diff</a> repository.</small>
</footer>
</div>
</body>
</html>