File size: 6,048 Bytes
d9d886e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
const express = require('express')
const multer = require('multer')
const path = require('path')
const fs = require('fs')
const { insertFireMissionMetadata, getFireMissionMetadata, deleteFireMissionMetadata } = require('./models/fireMissionModel')

const router = express.Router()

const IMAGES_WAYPOINTS_DIR = path.join(__dirname, '..', 'image_wp_result')

if (!fs.existsSync(IMAGES_WAYPOINTS_DIR)) {
  fs.mkdirSync(IMAGES_WAYPOINTS_DIR, { recursive: true })
}

const imageWaypointStorage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, IMAGES_WAYPOINTS_DIR)
  },
  filename: function (req, file, cb) {
    const timestamp = Date.now()
    const ext = path.extname(file.originalname) || '.jpg'
    const filename = `${timestamp}${ext}`
    cb(null, filename)
  }
})

const imageWaypointUpload = multer({
  storage: imageWaypointStorage,
  limits: {
    fileSize: 50 * 1024 * 1024
  },

  fileFilter: function (req, file, cb) {
    const allowedTypes = /jpeg|jpg|png/

    const mimetype = allowedTypes.test(file.mimetype)
    const extname = allowedTypes.test(
      path.extname(file.originalname).toLowerCase()
    )

    if (mimetype && extname) {
      return cb(null, true)
    }
    cb(new Error('Only image files like jpeg, jpg, or png that allowed'))
  }
})

router.post('/', imageWaypointUpload.single('file'), async (req, res) => {
  try {
    if (!req.file) {
      return res.status(400).json({
        success: false,
        error: 'No file given'
      })
    }
    let metadata
    try {
      metadata = JSON.parse(req.body.meta || '{}')
    } catch (parseError) {
      fs.unlinkSync(req.file.path)
      return res.status(400).json({
        success: false,
        error: 'Invalid metadata format. Expected JSON'
      })
    }
    const { lat, lon, timestamp } = metadata

    if (!lat || !lon) {
      fs.unlinkSync(req.file.path)
      return res.status(400).json({
        success: false,
        error: 'Invalid coordinates. Both lat and lon must be a valid number'
      })
    }
    const latitude = parseFloat(lat)
    const longitude = parseFloat(lon)

    if (latitude < -90 || latitude > 90) {
      fs.unlinkSync(req.file.path)
      return res.status(400).json({
        success: false,
        error: `Latitude must be between -90 (Antartica) and 90 (Kutub Utara), your latitude: ${latitude}`
      })
    }

    if (longitude < -180 || longitude > 180) {
      fs.unlinkSync(req.file.path)
      return res.status(400).json({
        success: false,
        error: `Longitude must be between -180 and 180, your longitude: ${longitude}`
      })
    }

    const fireId = await insertFireMissionMetadata({
      filename: req.file.filename,
      latitude,
      longitude,
      timestamp: timestamp || Date.now(),
      fileSize: req.file.size
    })

    const imageData = {
      fireId,
      filename: req.file.filename,
      lat: latitude,
      lon: longitude,
      timestamp: timestamp || Date.now()
    }

    const { getSocketIOInstance } = require('../lib/socketio_instance')
    const io = getSocketIOInstance()

    if (io) {
      io.emit('imagewp:new_image', imageData)
    } else {
      console.log('SocketIO.instance error')
    }

    res.json({
      success: true,
      message: 'Image upload succesfully',
      data: imageData
    })
  } catch (error) {
    console.log('Error uploading image and waypoint')
    if (req.file && fs.existsSync(req.file.path)) {
      fs.unlinkSync(req.file.path)
    }

    res.status(500).json({
      success: false,
      error: error.message || 'Internal server error'
    })
  }
})

router.get('/list', (req, res) => {
  try {
    if (!fs.existsSync(IMAGES_WAYPOINTS_DIR)) {
      return res.json({
        success: true,
        count: 0,
        images: []
      })
    }
    const files = fs.readdirSync(IMAGES_WAYPOINTS_DIR)
    const imageFiles = files.filter((file) => {
      return /\.(jpg|jpeg|png)$/i.test(file)
    })
    const images = imageFiles.map((filename) => {
      const filePath = path.join(IMAGES_WAYPOINTS_DIR, filename)
      const stats = fs.statSync(filePath)

      const timestampMatch = filename.match(/^(\d+)/)
      const timestamp = timestampMatch
        ? parseInt(timestampMatch[1])
        : stats.mtimeMs

      return {
        filename,
        timestamp,
        lat: null,
        lon: null,
        size: stats.size,
        uploadedAt: stats.mtime.toISOString(),
        url: `/api/imagewp/files/${filename}`
      }
    })

    images.sort((a, b) => b.timestamp - a.timestamp)

    const limit = parseInt(req.query.limit) || 100
    const limitedImages = images.slice(0, limit)

    res.json({
      success: true,
      count: limitedImages.length,
      total: images.length,
      images: limitedImages
    })
  } catch (error) {
    console.error('Internal server error: ', error)
    res.status(500).json({
      success: false,
      error: error.message
    })
  }
})

router.get('/metadata', async (req, res) => {
  try {
    const limit = parseInt(req.query.limit) || 100
    const metadata = await getFireMissionMetadata(limit)

    res.json({
      success: true,
      count: metadata.length,
      data: metadata
    })
  } catch (error) {
    console.error('Error fetching metadata:', error)
    res.status(500).json({
      success: false,
      error: error.message
    })
  }
})

router.delete('/:filename', async (req, res) => {
  try {
    const { filename } = req.params
    const filePath = path.join(IMAGES_WAYPOINTS_DIR, filename)

    if (!fs.existsSync(filePath)) {
      return res.status(404).json({
        success: false,
        error: 'File not found'
      })
    }

    fs.unlinkSync(filePath)
    await deleteFireMissionMetadata(filename)

    res.json({
      success: true,
      message: 'Image and metadata deleted successfully',
      filename
    })
  } catch (error) {
    console.error('Error deleting image:', error)
    res.status(500).json({
      success: false,
      error: error.message
    })
  }
})

module.exports = router