121 lines
2.8 KiB
JavaScript
121 lines
2.8 KiB
JavaScript
"use strict";
|
|
|
|
const express = require("express"),
|
|
fs = require("fs"),
|
|
url = require("url"),
|
|
config = require("config"),
|
|
moment = require("moment");
|
|
|
|
let photoDB;
|
|
|
|
require("../db").then(function(db) {
|
|
photoDB = db;
|
|
});
|
|
|
|
const router = express.Router();
|
|
|
|
/* Each photos has:
|
|
|
|
* locations
|
|
* people
|
|
* date
|
|
* tags
|
|
* photo info
|
|
|
|
*/
|
|
|
|
router.get("/*", function(req, res/*, next*/) {
|
|
let limit = parseInt(req.query.limit) || 50,
|
|
order = (parseInt(req.query.dir) == -1) ? "DESC" : "", id, cursor, index;
|
|
|
|
if (req.query.next) {
|
|
let parts = req.query.next.split("_");
|
|
cursor = parts[0];
|
|
id = parseInt(parts[1]);
|
|
} else {
|
|
cursor = "";
|
|
id = -1;
|
|
}
|
|
|
|
if (id == -1) {
|
|
index = "";
|
|
} else {
|
|
if (order == "DESC") {
|
|
if (id != -1) {
|
|
index = " AND ((taken=DATE(:cursor) AND id<"+id+ ") OR taken<DATE(:cursor))";
|
|
} else {
|
|
index = " AND (taken<=DATE(:cursor))";
|
|
}
|
|
} else {
|
|
if (id != -1) {
|
|
index = " AND ((taken=DATE(:cursor) AND id>"+id+ ") OR taken>DATE(:cursor))";
|
|
} else {
|
|
index = " AND (taken>=DATE(:cursor))";
|
|
}
|
|
}
|
|
}
|
|
|
|
let query = "SELECT * FROM photos WHERE path LIKE :path " + index + " ORDER BY taken " + order + ",id " + order + " LIMIT " + (limit * 2 + 1);
|
|
return photoDB.sequelize.query(query, {
|
|
replacements: {
|
|
cursor: cursor,
|
|
path: decodeURI(req.url).replace(/\?.*$/, "") + "%"
|
|
},
|
|
type: photoDB.Sequelize.QueryTypes.SELECT
|
|
}).then(function(photos) {
|
|
photos.forEach(function(photo) {
|
|
for (var key in photo) {
|
|
if (photo[key] instanceof Date) {
|
|
photo[key].setHours(0, 0, 0, 0);
|
|
photo[key] = moment(photo[key]);
|
|
}
|
|
}
|
|
});
|
|
|
|
if (order == "DESC") {
|
|
if (cursor) {
|
|
cursor = moment(cursor);
|
|
photos = photos.filter(function(photo) {
|
|
if (!cursor.isSame(photo.taken, "day")) {
|
|
return true;
|
|
}
|
|
return photo.id < id;
|
|
});
|
|
}
|
|
} else {
|
|
if (cursor) {
|
|
cursor = moment(cursor);
|
|
photos = photos.filter(function(photo) {
|
|
if (!cursor.isSame(photo.taken, "day")) {
|
|
return true;
|
|
}
|
|
return photo.id > id;
|
|
});
|
|
}
|
|
}
|
|
|
|
let more = photos.length > limit; /* We queried one extra item to see if there are more than LIMIT available */
|
|
|
|
if (more) {
|
|
photos.slice(limit, photos.length);
|
|
}
|
|
photos.forEach(function(photo) {
|
|
// photo.path = encodeURI(photo.path);
|
|
// photo.filename = encodeURI(photo.filename);
|
|
});
|
|
|
|
let results = {
|
|
items: photos
|
|
};
|
|
if (more) {
|
|
results.more = true;
|
|
}
|
|
return res.status(200).json(results);
|
|
}).catch(function(error) {
|
|
console.error("Query failed: " + query);
|
|
return Promise.reject(error);
|
|
});
|
|
});
|
|
|
|
module.exports = router;
|