From 6844fe42bca96ab92e296f240f0084281b869f04 Mon Sep 17 00:00:00 2001 From: benny Date: Thu, 20 Jun 2024 19:00:42 +0300 Subject: [PATCH] now filling the form with the fucking data. currently, unidentified --- .gitignore | 3 +- html/lastob.json | 10 +++ html/uploadfile.html | 12 +-- main.go | 80 ++++++++++++------- packages.go | 179 ++++++++++++++++++++++++++++++++++++++++--- public/script.js | 42 ++++++++++ 6 files changed, 279 insertions(+), 47 deletions(-) create mode 100644 html/lastob.json diff --git a/.gitignore b/.gitignore index 5fdba2d..44e54ba 100644 --- a/.gitignore +++ b/.gitignore @@ -3,4 +3,5 @@ Logs/ progs.db tmpdir/ .vscode/ -data/ \ No newline at end of file +data/ +Data/ \ No newline at end of file diff --git a/html/lastob.json b/html/lastob.json new file mode 100644 index 0000000..ce5b743 --- /dev/null +++ b/html/lastob.json @@ -0,0 +1,10 @@ +{{define "main"}} +{ + "Identifier" :"{{.Identifier}}", + "Version" :"{{.Version}}", + "Type" : "{{.Type}}", + "Location": "{{.Location}}", + "Checksum": "{{.Checksum}}", + "Url" : "{{.Url}}" +} +{{end}} \ No newline at end of file diff --git a/html/uploadfile.html b/html/uploadfile.html index ecd0d74..7cbf802 100644 --- a/html/uploadfile.html +++ b/html/uploadfile.html @@ -11,29 +11,29 @@ -
+
- +
- +
- +
Installers
- +
- +
diff --git a/main.go b/main.go index f4a9a3b..576105c 100644 --- a/main.go +++ b/main.go @@ -7,7 +7,7 @@ import ( "fmt" "html/template" "io" - "log" + "log/slog" "net/http" "os" "strings" @@ -15,22 +15,24 @@ import ( _ "modernc.org/sqlite" // Importing SQLite driver for database interaction. ) - +var c chan bool // readHtml function reads an HTML file and applies a CSS template to it before sending it to the client. -func readHtml(res http.ResponseWriter, req *http.Request) { +func readHtml(res http.ResponseWriter, _ *http.Request) { g := template.CSS("./html/public/mod.css") // Define the CSS path. f, err := template.ParseFiles("./html/wsb.html") // Parse the HTML file. if err != nil { - log.Println(err) // Log any errors encountered. + slog.Error(err.Error()) + // Log any errors encountered. } err = f.Execute(res, g) // Execute the template with the CSS and send it to the client. if err != nil { - log.Println(err) // Log any errors encountered. + slog.Error(err.Error()) + // Log any errors encountered. } } // simpRequestResp sends a simple response to the client. -func simpRequestResp(res http.ResponseWriter, req *http.Request) { +func simpRequestResp(res http.ResponseWriter, _ *http.Request) { fmt.Fprint(res, "Hello, M'Lord", 153*4, " I'm here to serveè") // Print a formatted string to the client. } @@ -58,13 +60,13 @@ func queryPacks(sqldb *sql.DB, element *elements) []packages { defer res.Close() // Ensure the result set is closed after the function returns. err = res.Err() // Check for any errors during query execution. if err != nil { - log.Panicln(err) // Log and panic on any errors. + slog.Error(err.Error()) // Log and panic on any errors. } for res.Next() { npkg := packages{} // Create a new package instance. err := res.Scan(&npkg.Id, &npkg.Name, &npkg.Version, &npkg.ExtraCommand, &npkg.Tag, &npkg.Warning) // Scan the result into the package instance. if err != nil { - log.Fatalln(err) // Log and exit on any errors. + slog.Error(err.Error()) // Log and exit on any errors. } npkg.Element = element // Associate the element with the package. pkgs = append(pkgs, npkg) // Append the package to the slice. @@ -82,7 +84,8 @@ func queryDatabase(sqldb *sql.DB, queryRow string) []string { var values []string err := res.Scan(&values) if err != nil { - log.Println(err) + slog.Error(err.Error()) + } return values } @@ -118,7 +121,7 @@ func searchDownloads(sqldb *sql.DB, table string, columns ...string) []DownloadE defer runquery.Close() err = runquery.Err() if err != nil { - log.Fatalln(err) + slog.Error(err.Error()) } var elems []DownloadElements var e DownloadElements @@ -163,11 +166,13 @@ func stats(sqldb *sql.DB, lang string) http.Handler { } templates, err := template.ParseFiles("html/master.html", "html/statsitics.html") if err != nil { - log.Println(err) + slog.Error(err.Error()) + } err = templates.ExecuteTemplate(res, "master", Counter) if err != nil { - log.Println(err) + slog.Error(err.Error()) + } res.WriteHeader(http.StatusOK) }) @@ -181,20 +186,21 @@ func getPkgIdFromDB(sqldb *sql.DB) []string { defer query.Close() err = query.Err() if err != nil { - log.Println(err) + slog.Error(err.Error()) } var pkgs []string var tmpstr string for query.Next() { err = query.Scan(&tmpstr) if err != nil { - log.Println(err) + slog.Error(err.Error()) + } pkgs = append(pkgs, tmpstr) } // query.Scan(&pkgs) if err != nil { - log.Println(err) + slog.Error(err.Error()) } return pkgs } @@ -238,11 +244,11 @@ func uploadFileForServer(sqldb *sql.DB, lang string) http.Handler{ } templates, err := template.ParseFiles("html/master.html", "html/uploadfile.html") if err != nil { - log.Println(err) + slog.Error(err.Error()) } err = templates.ExecuteTemplate(res, "master", data) if err != nil { - log.Println(err) + slog.Error(err.Error()) } // upload(res, req) res.WriteHeader(http.StatusOK) @@ -261,7 +267,7 @@ func upload() http.Handler { fn,_:=os.OpenFile("Data/"+filename, os.O_WRONLY|os.O_CREATE, 0666) defer fn.Close() fn.Write(fileBytes) - log.Println(getDataFromFile("Data/"+filename)) + slog.Info(fmt.Sprint(getDataFromFile("Data/"+filename))) })} // index creates an HTTP handler that serves the main page with data from the database. @@ -294,11 +300,11 @@ func index(sqldb *sql.DB, lang string) http.Handler { templates, err := template.ParseFiles("html/master.html", "html/main.html") if err != nil { - log.Println(err) + slog.Error(err.Error()) } err = templates.ExecuteTemplate(res, "master", data) if err != nil { - log.Println(err) + slog.Error(err.Error()) } res.WriteHeader(http.StatusOK) @@ -315,13 +321,30 @@ func public() http.Handler { // main initializes the application, sets up logging, database connection, HTTP routing, and starts the server. func main() { - logfilename := "Logs/" + time.Now().Format("2006-01-02--15-04-05") + ".log" - file, err := os.OpenFile(logfilename, os.O_APPEND|os.O_CREATE, 0777) - if err != nil { - os.Exit(12) - } - log.SetOutput(file) + // Check if the directory exists + if _, err := os.Stat("Logs/"); os.IsNotExist(err) { + // Create your directory if it does not exist + err = os.Mkdir("Logs/", 0755) + if err != nil { + fmt.Println(err) + } + } + handlerOpts := &slog.HandlerOptions{ + Level: slog.LevelDebug, + } + logfilename := "Logs/" + time.Now().Format("2006-01-02--15-04-05") + ".log" + file, err := os.OpenFile(logfilename, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0777) + defer file.Close() + log:=slog.New(slog.NewTextHandler(file,handlerOpts )) + slog.SetDefault(log) + if err != nil { + panic(err) + } + + + // Write a log entry + slog.Info("This is a test log entry") db, _ := sql.Open("sqlite", "file:progs.db") mux := http.NewServeMux() mux.Handle("/public/", public()) @@ -330,6 +353,7 @@ func main() { mux.Handle("/stats", stats(db,"eng")) mux.Handle("/up", uploadFileForServer(db,"eng")) mux.Handle("/upload",upload()) + mux.Handle("/pkg",getJson(db)) addr := fmt.Sprintf(":%s", "12312") server := http.Server{ Addr: addr, @@ -340,9 +364,9 @@ func main() { } if err := server.ListenAndServe(); err != nil { - log.Fatalf("main: couldn't start simple server: %v\n", err) + log.Error("main: couldn't start simple server: %v\n", err) } lang := "heb" - log.Println(getMsgFromDB(db, "title", lang)) + log.Info(getMsgFromDB(db, "title", lang)) } diff --git a/packages.go b/packages.go index 4c984ae..ead48e9 100644 --- a/packages.go +++ b/packages.go @@ -1,15 +1,32 @@ package main import ( + "crypto/sha256" + "database/sql" "fmt" - "log" + "log/slog" + "net/http" "os" "os/exec" + "encoding/hex" "regexp" "runtime" "strconv" + "strings" + "html/template" + + _ "modernc.org/sqlite" ) +type jsonStruct struct { + Identifier string + Version string + Type string + Location string + Checksum string + Url string +} + // packages struct represents a package with its details. type packages struct { Id string @@ -66,8 +83,8 @@ type DownloadElements struct { // Printer struct is an empty struct. Its purpose is not clear from the provided code. type Printer struct{} -func getDataFromFile(path string) map[string]string { - log.Println(regexp.MustCompile(`\.\w+$`).FindString(path)) +func getDataFromFile(path string) jsonStruct { + slog.Debug(regexp.MustCompile(`\.\w+$`).FindString(path)) switch extention := regexp.MustCompile(`\.\w+$`).FindString(path); extention { case ".exe": return getParamsFromExif(path) @@ -75,32 +92,35 @@ func getDataFromFile(path string) map[string]string { case ".msi": return getParamsFromMsi(path) } - return make(map[string]string) + return jsonStruct{} } // getParamsFromExif extracts EXIF parameters from a file at the given path using the exiftool command. // It returns a map where the keys are the EXIF parameter names and the values are the corresponding EXIF parameter values. -func getParamsFromExif(path string) map[string]string { +func getParamsFromExif(path string) jsonStruct { exiftool := os.Getenv("exiftool") e, _ := exec.Command(exiftool, "-f", path).Output() - return splitData(e) + data := splitData(e) + data["Extention"] = data["File Type Extension"] + data["Path"] = path + return createObject(data) } func splitData(commandOutput []byte) map[string]string { tags := make(map[string]string) spliter := regexp.MustCompile(`\r?\n`) crop := spliter.Split(string(commandOutput), -1) - head := regexp.MustCompile(`\s+(:\s)?`) + head := regexp.MustCompile(`\t|(\s+:\s?)`) for _, c := range crop { if len(c) > 1 { data := head.Split(c, -1) - log.Println("My Raw Data: ", c) + slog.Debug("My Raw Data: ", c) tags[data[0]] = data[1] } } - log.Println(tags) + slog.Debug(fmt.Sprint(tags)) return tags } -func getParamsFromMsi(path string) map[string]string { +func getParamsFromMsi(path string) jsonStruct { if runtime.GOOS == "windows" { // orca :=os.Getenv("orca") @@ -113,8 +133,143 @@ func getParamsFromMsi(path string) map[string]string { } else { msiinfo := os.Getenv("msiinfo") e, _ := exec.Command(msiinfo, "export", path, "Property").Output() - return splitData(e) + data := splitData(e) + data["Extention"] = "msi" + data["Path"] = path + return createObject(data) } - return make(map[string]string) + return jsonStruct{} +} +func getVendor(data map[string]string) string { + for key, val := range data { + switch key { + case "Author": + return strings.ToLower(strings.Replace(val," ","",-1)) + + case "Company Name": + return strings.ToLower(strings.Replace(val," ","",-1)) + + case "Publisher": + return strings.ToLower(strings.Replace(val," ","",-1)) + + } + } + return "" +} +func getProgram(data map[string]string) string { + for key, val := range data { + switch key { + case "Title": + return strings.ToLower(strings.Replace(val," ","",-1)) + + case "Product Name": + return strings.ToLower(strings.Replace(val," ","",-1)) + + case "Subject": + return strings.ToLower(strings.Replace(val," ","",-1)) + } + } + return "" +} +func getVersion(data map[string]string) string { + replacer:=regexp.MustCompile(`[, ]+`) + for key, val := range data { + switch key { + case "Version": + return replacer.ReplaceAllString(val,".") + case "Product Version": + return replacer.ReplaceAllString(val,".") + case "ProductVersion": + return replacer.ReplaceAllString(val,".") + case "File Version": + return replacer.ReplaceAllString(val,".") + case "FileVersion": + return replacer.ReplaceAllString(val,".") + } + } + return "" +} +func detectProblems(data map[string]string) bool { + exe, err := data["Extention"] + mime, _ := data["MIME Type"] + if !err || (exe == "exe" && !(mime == "application/octet-stream")) { + return false + } + if (exe != "msi" && exe != "exe" && exe != "zip") { + return false + } + return true +} +func getInstallerType(data map[string]string) string { + for _, val := range data { + if val == "msi" { + return "msi" + } + if strings.Contains(strings.ToLower(val), "nullsoft") { + return "nullsoft" + } + if strings.Contains(strings.ToLower(val), "inno") { + return "inno" + } + } + return "exe" +} +func moveToNewLocationAndName(data map[string]string) string { + newLoc := os.Getenv("installationDirectory") + "/" + newFileLoc := getVendor(data) + "." + getProgram(data) + ".v." + newFileLoc += getVersion(data) + "." + newFileLoc += data["Extention"] + newLoc += newFileLoc + file, _ := os.OpenFile(newLoc, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666) + defer file.Close() + oldFile, _ := os.ReadFile(data["Path"]) + file.Write(oldFile) + return newFileLoc +} +func createObject(object map[string]string) jsonStruct { + if detectProblems(object) { + prop := jsonStruct{ + Identifier: getVendor(object) + "." + getProgram(object), + Version: getVersion(object), + Type: getInstallerType(object), + } + + loc, _ := os.ReadFile(object["Directory"] + "/" + object["File Name"]) + chksum:=sha256.Sum256(loc) + prop.Checksum = hex.EncodeToString(chksum[:]) + lc := moveToNewLocationAndName(object) + prop.Url = os.Getenv("uri") + lc + prop.Location = os.Getenv("installationDirectory") + "/" + lc + newJson(prop) + return prop + } + return jsonStruct{} +} +func newJson(object jsonStruct) { + + sqldb, err := sql.Open("sqlite", "file:progs.db") + if err != nil { + slog.Error(err.Error()) + } + sqldb.Exec("INSERT OR IGNORE INTO newapps(identifier, version, type, location, checksum, url) values (?,?,?,?,?,?)", object.Identifier, object.Version, object.Type, object.Location, object.Checksum, object.Url) } +func getJson(sqldb *sql.DB) http.Handler { + return http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { + quer := generateSQL("newapps", []string{"identifier", "version", "type", "location", "checksum", "url"}) + " ORDER BY ROWID DESC LIMIT 1" + data := sqldb.QueryRow(quer) + jsonelement := jsonStruct{} + err := data.Scan(&jsonelement.Identifier, &jsonelement.Version, &jsonelement.Type, &jsonelement.Location, &jsonelement.Checksum, &jsonelement.Url) + if err != nil { + slog.Error(err.Error()) + } + temp,err:=template.ParseFiles("html/lastob.json") + if err != nil { + slog.Error(err.Error()) + } + err=temp.ExecuteTemplate(res, "main", jsonelement) + if err != nil { + slog.Error(err.Error()) + } + }) +} diff --git a/public/script.js b/public/script.js index 64c0cc2..8831258 100644 --- a/public/script.js +++ b/public/script.js @@ -120,4 +120,46 @@ function convertHtml(dt){ function showContainer(className){ classShow = document.getElementsByClassName(className)[0]; classShow.style.display = classShow.style.display=="flex"?"none":"flex"; +} +function runme(data){ + alert(data) +} +async function fetchContent(uri) { + try { + const response = await fetch(uri); + if (!response.ok) { + throw new Error(`HTTP error! status: ${response.status}`); + } + const content = await response.text(); + return content; + } catch (error) { + console.error(`There was a problem with the fetch operation: ${error.message}`); + } +} +function updateForm(uri, eid){ + fetchContent(uri).then(content => { + switch(eid){ + case "PackageIdentifier":{ + document.getElementById("PackageIdentifier").value=content.Identifier + break + } + case "PackageVersion":{ + document.getElementById("PackageVersion").value=content.Version + break + } + case "InstallerType":{ + document.getElementById("InstallerType").value=content.Type + break + } + case "InstallerUrl":{ + document.getElementById("InstallerUrl").value=content.Url + break + } + case "InstallerSha256":{ + document.getElementById("InstallerSha256").value=content.Checksum + break + } + } + console.log(content) + }) } \ No newline at end of file