Skip to content

Commit

Permalink
Merge pull request #1 from sschonss/feature/add-api
Browse files Browse the repository at this point in the history
Feature/add api
  • Loading branch information
sschonss authored Jan 8, 2024
2 parents 768027b + 87afdf6 commit c946854
Show file tree
Hide file tree
Showing 14 changed files with 308 additions and 61 deletions.
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
print_log.txt
/.idea/.gitignore
/.idea/auto-print.iml
/.idea/modules.xml
/.idea/vcs.xml
/server/print_log.txt
174 changes: 165 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# AutoPrinter

### Português / Portuguese
## Português / Portuguese

Este sistema foi desenvolvido para automatizar o processo de impressão de imagens em uma impressora específica, registrando informações relevantes em um arquivo de log. O sistema possui dois scripts, um em Bash e outro em PowerShell, para sistemas Unix-like e Windows, respectivamente.
Funcionalidades:
Expand All @@ -17,25 +17,106 @@ Funcionalidades:

### Uso:

Acesse o diretório de scripts e execute o script correspondente ao seu sistema operacional.

- Bash (Sistemas Unix-like):
Para utilizar o script em Bash, execute-o no terminal fornecendo o nome do arquivo como argumento. Exemplo:

```bash
./autoprinter.sh "nome_da_imagem"
./autoprinter.sh "nome_da_imagem" "numero_de_copias" "sistema_operacional"
```

- PowerShell (Windows):

No PowerShell, execute o script fornecendo o nome do arquivo como argumento. Exemplo:

```arduino
.\autoprinter.ps1 "nome_da_imagem"
.\autoprinter.ps1 "nome_da_imagem" "numero_de_copias" "sistema_operacional"
```

### API Server (Go):

Para rodar a aplicação de forma mais eficiente e profissional, vamos usar uma API em Go para automatizar a execução dos scripts.

Acesse o diretório `server` e execute os passos abaixo.

Você pode usar o comando `go run main.go` para rodar a aplicação, ou `go build main.go` para gerar um executável.

#### Build

Caso você queira buildar seu projeto, rode o seguinte comando no terminal:

```bash
go build -o <nome_do_executavel>
```

No nosso caso, estamos usando o nome `autoprinter`, então o comando fica:

```bash
go build -o autoprinter
```

Lembre-se de que após o build, o arquivo só pode ser executado em sistemas operacionais compatíveis com o seu sistema de desenvolvimento. Por exemplo, se você estiver desenvolvendo no Windows, o executável só poderá ser executado em sistemas Windows.

Mas caso você queira buildar para outros sistemas, você pode usar o seguinte comando:

```bash
GOOS=<sistema_operacional> GOARCH=<arquitetura> go build -o <nome_do_executavel>
```

Por exemplo, para buildar para Windows, você pode usar:

```bash
GOOS=windows GOARCH=amd64 CGO_ENABLED=1 CC=x86_64-w64-mingw32-gcc go build -o nome_do_arquivo_windows.exe
```

Caso você queira buildar para Linux, você pode usar:

```bash
GOOS=linux GOARCH=amd64 go build -o nome_do_arquivo_linux
```

Muitas vezes, o comando acima não funciona, por que o compilador não está instalado. Para instalar o compilador, você pode usar o seguinte comando:

```bash
sudo apt install gcc-mingw-w64-x86-64
```

#### Execução

Para executar o programa, você pode usar o seguinte comando:

```bash
./autoprinter
```

Caso você tenha buildado para outro sistema, você pode usar o seguinte comando:

```bash
./nome_do_executavel
```

Logo após a execução, o programa irá rodar na porta 8080. Para acessar a API, você pode usar o seguinte link:

```bash
http://localhost:8080/print
```

Lá ira conter as instruções para a utilização da API.

#### Observações

Pode ser que ao rodar no Windows, você receba um erro de permissão. Para resolver isso, você pode usar o seguinte comando:

```bash
Set-ExecutionPolicy RemoteSigned
```

### Inglês / English
---

This system was developed to automate the process of printing images on a specific printer, logging relevant information to a log file. The system consists of two scripts, one in Bash for Unix-like systems and another in PowerShell for Windows.
Features:
## Inglês / English

This system was developed to automate the process of printing images on a specific printer while logging relevant information to a log file. The system consists of two scripts, one in Bash for Unix-like systems and another in PowerShell for Windows, respectively.Features:

- Automated Printing:
The scripts accept the image name as a parameter and check if the file exists in the specified directory.
Expand All @@ -53,13 +134,88 @@ Features:
To use the Bash script, execute it in the terminal providing the image name as an argument. Example:

```bash
./autoprinter.sh "image_name"
./autoprinter.sh "image_name" "number_of_copies" "operating_system"
```

- PowerShell (Windows):

In PowerShell, execute the script providing the image name as an argument. Example:

```arduino
.\autoprinter.ps1 "image_name"
```
.\autoprinter.ps1 "image_name" "number_of_copies" "operating_system"
```

### API Server (Go):

You can use the command go run main.go to run the application, or go build main.go to generate an executable.
Build

Access the `server` directory and follow the steps below.

If you want to build your project, run the following command in the terminal:

```bash
go build -o <executable_name>
```

In our case, we're using the name autoprinter, so the command is:

```bash
go build -o autoprinter
```

Remember that after the build, the file can only be executed on operating systems compatible with your development system. For example, if you're developing on Windows, the executable can only be run on Windows systems.

But if you want to build for other systems, you can use the following command:

```bash
GOOS=<operating_system> GOARCH=<architecture> go build -o <executable_name>
```

For example, to build for Windows, you can use:

```bash
GOOS=windows GOARCH=amd64 CGO_ENABLED=1 CC=x86_64-w64-mingw32-gcc go build -o filename_windows.exe
```

If you want to build for Linux, you can use:

```bash
GOOS=linux GOARCH=amd64 go build -o filename_linux
```

Often, the above command doesn't work because the compiler isn't installed. To install the compiler, you can use the following command:

```bash
sudo apt install gcc-mingw-w64-x86-64
```

### Execution

To run the program, you can use the following command:

```bash
./autoprinter
```

If you've built for another system, you can use the following command:

```bash
./executable_name
```

Immediately after execution, the program will run on port 8080. To access the API, you can use the following link:

```bash
http://localhost:8080/print
```

There, you'll find instructions for using the API.

### Notes

When running on Windows, you may receive a permission error. To fix this, you can use the following command:

```bash
Set-ExecutionPolicy RemoteSigned
```
26 changes: 0 additions & 26 deletions autoprinter.ps1

This file was deleted.

26 changes: 0 additions & 26 deletions autoprinter.sh

This file was deleted.

Binary file added files/123456.jpeg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
File renamed without changes
File renamed without changes
3 changes: 3 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module github.com/sschonss/auto-print

go 1.18
72 changes: 72 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
package main

import (
"fmt"
"log"
"net/http"
"os/exec"
)

func printImage(w http.ResponseWriter, r *http.Request) {
err := r.ParseForm()
if err != nil {
log.Println(err)
fmt.Fprintf(w, "Error parsing form: %s\n", err)
return
}

imageName := r.FormValue("image")
copies := r.FormValue("copies")
os := r.FormValue("os")

fmt.Fprintf(w, "Printing image %s %s times...\n", imageName, copies)

var cmd *exec.Cmd

fmt.Println("OS:", os)

if os == "linux" {
fmt.Println("Linux detected")
cmd = exec.Command("bash", "scripts/autoprinter.sh", imageName, copies)
} else if os == "win" {
fmt.Println("Windows detected")
cmd = exec.Command("powershell", "-File", "scripts/autoprinter.ps1", imageName, copies)

} else {
cmd = exec.Command("echo", "OS not detected")
fmt.Println("OS not detected")
}

output, err := cmd.CombinedOutput()
if err != nil {
log.Println(err)
fmt.Fprintf(w, "Error printing image: %s\n", err)
fmt.Fprintf(w, "Output: %s\n", output)
return
}

fmt.Fprintf(w, "Print request processed successfully.\n%s\n", output)
}

func explainAPI(w http.ResponseWriter, r *http.Request) {
explanation := `
Welcome to the AutoPrint API!
To print an image, send a POST request to /print with the following parameters:
- image: Image name
- copies: Number of copies
- os: Operating System ("linux" or "win")
Example:
curl -X POST -d "image=123456789&copies=2&os=linux" http://localhost:8080/print
`
fmt.Fprintln(w, explanation)
}

func main() {
fmt.Println("Starting server...")
http.HandleFunc("/", explainAPI)
http.HandleFunc("/print", printImage)
fmt.Println("Listening on port 8080...")
log.Fatal(http.ListenAndServe(":8080", nil))
}
5 changes: 5 additions & 0 deletions print_log.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
2024-01-08 08:36:28: Starting printing of 2 copies of file '../files/temp_123456.jpeg' (resized) on printer 'HL-L8350CDW'
2024-01-08 08:36:28: Printing of 2 copies of file '../files/temp_123456.jpeg' (resized) on printer 'HL-L8350CDW' completed
2024-01-08 08:36:41: Starting printing of 2 copies of file './files/temp_123456.jpeg' (resized) on printer 'HL-L8350CDW'
id de requisição é HL-L8350CDW-33 (1 arquivo(s))
2024-01-08 08:36:41: Printing of 2 copies of file './files/temp_123456.jpeg' (resized) on printer 'HL-L8350CDW' completed
27 changes: 27 additions & 0 deletions scripts/autoprinter.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
param(
[Parameter(Mandatory=$true)]
[string]$image_name,

[Parameter(Mandatory=$true)]
[int]$num_copies
)

$image_file = ".\files\$image_name.jpeg"

if (-not (Test-Path $image_file)) {
Write-Host "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss'): The image file '$image_file' was not found."
exit 1
}

$printer = Get-WmiObject -Query "SELECT * FROM Win32_Printer WHERE Default=$true"
$printerName = $printer.Name

Write-Host "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss'): Starting printing of $num_copies copies of file '$image_file' on printer '$printerName'"

for ($i = 0; $i -lt $num_copies; $i++) {
Start-Process -FilePath "C:\Windows\System32\mspaint.exe" -ArgumentList "/pt `"$image_file`" `"$printerName`""
}

Write-Host "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss'): Printing of $num_copies copies of file '$image_file' on printer '$printerName' completed"
"Image '$image_file' sent for printing ($num_copies copies) to $printerName" | Out-File -Append -FilePath print_log.txt
"Logs saved in print_log.txt" | Out-File -Append -FilePath print_log.txt
Loading

0 comments on commit c946854

Please sign in to comment.