2020-02-23 18:00:08 +01:00
|
|
|
package scanner
|
|
|
|
|
|
|
|
import (
|
|
|
|
"database/sql"
|
|
|
|
"log"
|
|
|
|
"path"
|
2020-02-26 19:44:47 +01:00
|
|
|
|
|
|
|
"github.com/viktorstrate/photoview/api/graphql/models"
|
2020-02-23 18:00:08 +01:00
|
|
|
)
|
|
|
|
|
2020-07-10 14:26:19 +02:00
|
|
|
func ScanPhoto(tx *sql.Tx, photoPath string, albumId int) (*models.Media, bool, error) {
|
2020-02-23 18:00:08 +01:00
|
|
|
photoName := path.Base(photoPath)
|
|
|
|
|
|
|
|
// Check if image already exists
|
2020-02-26 21:23:13 +01:00
|
|
|
{
|
2020-06-24 10:43:20 +02:00
|
|
|
row := tx.QueryRow("SELECT * FROM photo WHERE path_hash = MD5(?)", photoPath)
|
2020-07-10 14:26:19 +02:00
|
|
|
photo, err := models.NewMediaFromRow(row)
|
2020-02-26 21:23:13 +01:00
|
|
|
if err != sql.ErrNoRows {
|
|
|
|
if err == nil {
|
|
|
|
log.Printf("Image already scanned: %s\n", photoPath)
|
|
|
|
return photo, false, nil
|
|
|
|
} else {
|
|
|
|
return nil, false, err
|
|
|
|
}
|
2020-02-23 18:00:08 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-06-23 16:42:02 +02:00
|
|
|
log.Printf("Scanning image: %s\n", photoPath)
|
|
|
|
|
2020-06-24 10:43:20 +02:00
|
|
|
result, err := tx.Exec("INSERT INTO photo (title, path, path_hash, album_id) VALUES (?, ?, MD5(path), ?)", photoName, photoPath, albumId)
|
2020-02-23 18:00:08 +01:00
|
|
|
if err != nil {
|
|
|
|
log.Printf("ERROR: Could not insert photo into database")
|
2020-02-26 21:23:13 +01:00
|
|
|
return nil, false, err
|
2020-02-23 18:00:08 +01:00
|
|
|
}
|
2020-07-10 14:26:19 +02:00
|
|
|
media_id, err := result.LastInsertId()
|
2020-02-23 18:00:08 +01:00
|
|
|
if err != nil {
|
2020-02-26 21:23:13 +01:00
|
|
|
return nil, false, err
|
2020-02-23 18:00:08 +01:00
|
|
|
}
|
|
|
|
|
2020-07-10 14:26:19 +02:00
|
|
|
row := tx.QueryRow("SELECT * FROM photo WHERE media_id = ?", media_id)
|
|
|
|
photo, err := models.NewMediaFromRow(row)
|
2020-02-23 18:00:08 +01:00
|
|
|
if err != nil {
|
2020-02-26 21:23:13 +01:00
|
|
|
return nil, false, err
|
2020-02-23 18:00:08 +01:00
|
|
|
}
|
|
|
|
|
2020-02-24 23:30:08 +01:00
|
|
|
_, err = ScanEXIF(tx, photo)
|
|
|
|
if err != nil {
|
|
|
|
log.Printf("ERROR: ScanEXIF for %s: %s\n", photoName, err)
|
|
|
|
}
|
|
|
|
|
2020-02-26 21:23:13 +01:00
|
|
|
return photo, true, nil
|
2020-02-23 18:00:08 +01:00
|
|
|
}
|