-
Notifications
You must be signed in to change notification settings - Fork 0
/
photo.go
334 lines (250 loc) · 6.83 KB
/
photo.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
package main
import (
"bufio"
"errors"
"fmt"
"image"
"image/gif"
"image/jpeg"
"image/png"
"log"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"time"
humanize "github.com/dustin/go-humanize"
"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
"github.com/nfnt/resize"
)
type photo struct {
ID uint
UserID uint
Filename string
Caption string
CreatedAt time.Time
Likes uint
}
const thumbnailSize uint = 600
// FetchAllPhotos gets all photos for all users
func FetchAllPhotos(c *gin.Context) {
session := sessions.Default(c)
uid := session.Get(userKey)
if uid == nil {
c.AbortWithStatus(http.StatusNotFound)
return
}
user, err := findUserByID(uid.(uint))
if err != nil {
log.Println("Could not find user:", err)
}
photos := []photo{}
db.Order("id desc").Find(&photos)
currentUser, _ := findUserByID(uid.(uint))
c.HTML(http.StatusOK, "photos.html", gin.H{
"user": user,
"photos": photos,
"CurrentUser": currentUser,
})
}
// FetchSinglePhoto gets a single photo by ID
func FetchSinglePhoto(c *gin.Context) {
session := sessions.Default(c)
uid := session.Get(userKey)
if uid == nil {
c.AbortWithStatus(http.StatusNotFound)
return
}
// Load single photo
id := c.Params.ByName("id")
photo := &photo{}
db.Where("id = ?", id).Find(photo)
// Load user info
user, err := findUserByID(photo.UserID)
if err != nil {
log.Println("Could not find user:", err)
}
// Load comments
comments := []comment{}
db.Where("photo_id = ?", id).Find(&comments)
currentUser, _ := findUserByID(uid.(uint))
c.HTML(http.StatusOK, "photo.html", gin.H{
"user": user,
"photo": photo,
"comments": comments,
"CurrentUser": currentUser,
})
}
// CreatePhoto saves the file to disk, generates its thumbnails, and stores
// metadata in the database.
func CreatePhoto(c *gin.Context) {
session := sessions.Default(c)
uid := session.Get(userKey)
if err != nil {
c.String(http.StatusBadRequest, fmt.Sprintf("Could not find user: %s", uid))
return
}
form, err := c.MultipartForm()
if err != nil {
c.String(http.StatusBadRequest, fmt.Sprintf("get form err: %s", err.Error()))
return
}
infile := form.File["photofile"][0]
log.Println("Uploaded file:", infile.Filename)
caption := form.Value["caption"][0]
log.Println("Caption:", caption)
uploadsdir := fmt.Sprintf("./public/uploads/%d", uid)
if _, err := os.Stat(uploadsdir); os.IsNotExist(err) {
os.Mkdir(uploadsdir, os.ModePerm)
}
thumbnailsdir := fmt.Sprintf("./public/thumbnails/%d", uid)
if _, err := os.Stat(thumbnailsdir); os.IsNotExist(err) {
os.Mkdir(thumbnailsdir, os.ModePerm)
}
// Generate unique filename
ts := strconv.FormatInt(time.Now().UnixNano(), 10)
fn := ts + filepath.Ext(infile.Filename)
outfile := filepath.Join(uploadsdir, fn)
// Save photo
if err := c.SaveUploadedFile(infile, outfile); err != nil {
c.String(http.StatusBadRequest, fmt.Sprintf("upload file err: %s", err.Error()))
return
}
log.Println("Uploaded file:", outfile)
// Insert DB record for photo and user
photoid, err := insertPhoto(uid.(uint), fn, caption)
if err != nil {
c.String(http.StatusBadRequest, fmt.Sprintf("Insert photo err: %s", err.Error()))
return
}
// Generate thumbnail
err = generateThumbnail(uid.(uint), outfile, thumbnailSize)
if err != nil {
c.String(http.StatusBadRequest, fmt.Sprintf("Error generating thumbnail: %s", err.Error()))
return
}
c.Redirect(http.StatusFound, fmt.Sprintf("/photos/%d", photoid))
}
// UpdatePhoto updates a single photo by ID
func UpdatePhoto(c *gin.Context) {
}
// DeletePhoto deletes a single photo by ID
func DeletePhoto(c *gin.Context) {
id := c.Params.ByName("id")
var p photo
if err := db.Where("id = ?", id).Delete(&p).Error; err != nil {
log.Println("Error deleting photo:", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": err})
return
}
c.JSON(http.StatusOK, gin.H{"id": id})
}
// LikePhoto increments the 'Likes' count
func LikePhoto(c *gin.Context) {
photoid := c.Params.ByName("id")
photo := &photo{}
db.Where("id = ?", photoid).Find(photo)
photo.Likes++
if err := db.Save(photo); err.Error != nil {
log.Println("Error updating photo:", err.Error)
}
c.JSON(http.StatusOK, gin.H{"likes": photo.Likes})
}
// CommentPhoto adds a comment to a photo
func CommentPhoto(c *gin.Context) {
photoid, _ := strconv.ParseUint(c.Params.ByName("id"), 10, 64)
var comment struct {
Comment string `json:"comment"`
}
if err := c.BindJSON(&comment); err != nil {
log.Println("BindJSON error:", err.Error())
}
log.Printf("Comment: %v\n", comment.Comment)
session := sessions.Default(c)
uid := session.Get(userKey)
id, err := InsertComment(uint(photoid), uid.(uint), comment.Comment)
if err != nil {
log.Println("Error inserting comment:", err.Error())
}
user, _ := findUserByID(uid.(uint))
c.JSON(http.StatusOK, gin.H{"id": id, "username": user.Username})
}
// Insert photo record into database
func insertPhoto(uid uint, fn string, caption string) (uint, error) {
photo := &photo{
UserID: uid,
Filename: fn,
Caption: caption,
CreatedAt: time.Now(),
}
if err := db.Create(photo); err.Error != nil {
return 0, err.Error
}
log.Println("Inserted photo record:", photo.ID)
return photo.ID, nil
}
func generateThumbnail(uid uint, photopath string, maxWidth uint) error {
log.Println("Generating thumbnail for:", photopath)
_, format, err := decodeConfig(photopath)
if err != nil {
log.Println(err)
return err
}
log.Println("Image format:", format)
file, err := os.Open(photopath)
if err != nil {
log.Println("Error opening photo:", err)
}
var img image.Image
switch format {
case "jpeg":
img, err = jpeg.Decode(file)
case "png":
img, err = png.Decode(file)
case "gif":
img, err = gif.Decode(file)
default:
err = errors.New("Unsupported file type")
}
if err != nil {
log.Println("Error decoding photo:", err)
}
file.Close()
log.Printf("Resizing image to %dpx\n", maxWidth)
thumb := resize.Resize(maxWidth, 0, img, resize.Lanczos3)
thumbnailPath := strings.Replace(photopath, "uploads", "thumbnails", -1)
out, err := os.Create(thumbnailPath)
if err != nil {
log.Println("Error creating thumbnail path:", err)
}
defer out.Close()
switch format {
case "jpeg":
err = jpeg.Encode(out, thumb, nil)
case "png":
err = png.Encode(out, thumb)
case "gif":
err = gif.Encode(out, thumb, nil)
default:
err = errors.New("Unsupported file type")
}
if err != nil {
log.Println("Error encoding thumbnail:", err)
return err
}
return nil
}
// Detect image file format (i.e. jpeg, png, gif)
func decodeConfig(filename string) (image.Config, string, error) {
f, err := os.Open(filename)
if err != nil {
return image.Config{}, "", err
}
defer f.Close()
return image.DecodeConfig(bufio.NewReader(f))
}
func (p *photo) TimeAgo() string {
return humanize.Time(p.CreatedAt)
}