Skip to content

Commit

Permalink
Merge pull request #117 from fga-eps-mds/i83_scannear_planta
Browse files Browse the repository at this point in the history
Adding scanner plant router
  • Loading branch information
joaovitorml authored Nov 26, 2020
2 parents f6d11e1 + d35fe36 commit cea945e
Show file tree
Hide file tree
Showing 9 changed files with 2,773 additions and 1,128 deletions.
3,622 changes: 2,516 additions & 1,106 deletions package-lock.json

Large diffs are not rendered by default.

164 changes: 160 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,11 @@
"lint:js:fix": "npm run lint:js -- --fix"
},
"lint-staged": {
"src/**/*.js": [
"src/**/*.{js,jsx}": [
"npx eslint . --fix",
"git add"
],
"src/*.js": [
"src/*.{js,jsx}": [
"npx eslint . --fix",
"git add"
]
Expand All @@ -36,10 +36,166 @@
},
"homepage": "https://github.com/fga-eps-mds/2020.1-GaiaDex-backend#readme",
"dependencies": {
"axios": "^0.21.0",
"abbrev": "^1.1.1",
"accepts": "^1.3.7",
"acorn": "^8.0.4",
"acorn-jsx": "^5.3.1",
"aggregate-error": "^3.1.0",
"ajv": "^6.12.6",
"ansi-align": "^3.0.0",
"ansi-colors": "^4.1.1",
"ansi-escapes": "^4.3.1",
"ansi-regex": "^5.0.0",
"ansi-styles": "^4.3.0",
"anymatch": "^3.1.1",
"argparse": "^2.0.1",
"aria-query": "^4.2.2",
"array-flatten": "^3.0.0",
"array-includes": "^3.1.1",
"array.prototype.flat": "^1.2.3",
"array.prototype.flatmap": "^1.2.3",
"ast-types-flow": "^0.0.7",
"astral-regex": "^2.0.0",
"axe-core": "^4.0.2",
"axobject-query": "^2.2.0",
"balanced-match": "^1.0.0",
"basic-auth": "^2.0.1",
"binary-extensions": "^2.1.0",
"bl": "^4.0.3",
"bluebird": "^3.7.2",
"body-parser": "^1.19.0",
"boxen": "^4.2.0",
"brace-expansion": "^2.0.0",
"braces": "^3.0.2",
"bson": "^4.2.0",
"buffer-equal-constant-time": "^1.0.1",
"bytes": "^3.1.0",
"cacheable-request": "^7.0.1",
"callsites": "^3.1.0",
"camelcase": "^6.1.0",
"chalk": "^4.1.0",
"chardet": "^1.3.0",
"chokidar": "^3.4.3",
"ci-info": "^2.0.0",
"clean-stack": "^3.0.0",
"cli-boxes": "^2.2.1",
"cli-cursor": "^3.1.0",
"cli-truncate": "^2.1.0",
"cli-width": "^3.0.0",
"clone-response": "^1.0.2",
"color-convert": "^2.0.1",
"color-name": "^1.1.4",
"commander": "^6.1.0",
"compare-versions": "^3.6.0",
"concat-map": "^0.0.1",
"configstore": "^5.0.1",
"confusing-browser-globals": "^1.0.9",
"contains-path": "^1.0.0",
"content-disposition": "^0.5.3",
"content-type": "^1.0.4",
"cookie": "^0.4.1",
"cookie-signature": "^1.1.0",
"core-js-pure": "^3.6.5",
"cosmiconfig": "^7.0.0",
"core-util-is": "^1.0.2",
"cross-spawn": "^7.0.3",
"crypto-random-string": "^3.3.0",
"damerau-levenshtein": "^1.0.6",
"debug": "^4.2.0",
"decompress-response": "^6.0.0",
"dedent": "^0.7.0",
"deep-extend": "^0.6.0",
"deep-is": "^0.1.3",
"defer-to-connect": "^2.0.0",
"define-properties": "^1.1.3",
"denque": "^1.4.1",
"depd": "^2.0.0",
"destroy": "^1.0.4",
"doctrine": "^3.0.0",
"dot-prop": "^6.0.0",
"axios": "^0.20.0",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"joi": "^17.3.0",
"external-editor": "^3.1.0",
"fast-deep-equal": "^3.1.3",
"fast-json-stable-stringify": "^2.1.0",
"fast-levenshtein": "^3.0.0",
"figures": "^3.2.0",
"file-entry-cache": "^5.0.1",
"fill-range": "^7.0.1",
"finalhandler": "^1.1.2",
"find-up": "^5.0.0",
"find-versions": "^3.2.0",
"flat-cache": "^2.0.1",
"flatted": "^3.1.0",
"forwarded": "^0.1.2",
"fresh": "^0.5.2",
"fs.realpath": "^1.0.0",
"function-bind": "^1.1.1",
"functional-red-black-tree": "^1.0.1",
"get-own-enumerable-property-symbols": "^3.0.2",
"get-stream": "^6.0.0",
"glob": "^7.1.6",
"glob-parent": "^5.1.1",
"global-dirs": "^2.0.1",
"globals": "^13.2.0",
"got": "^11.7.0",
"graceful-fs": "^4.2.4",
"has": "^1.0.3",
"has-flag": "^4.0.0",
"has-yarn": "^2.1.0",
"has-symbols": "^1.0.1",
"hosted-git-info": "^3.0.7",
"http-cache-semantics": "^4.1.0",
"http-errors": "^1.8.0",
"human-signals": "^2.1.0",
"iconv-lite": "^0.6.2",
"ignore": "^5.1.8",
"ignore-by-default": "^2.0.0",
"import-fresh": "^3.2.1",
"import-lazy": "^4.0.0",
"imurmurhash": "^0.1.4",
"indent-string": "^4.0.0",
"inflight": "^1.0.6",
"inherits": "^2.0.4",
"ini": "^1.3.5",
"inquirer": "^7.3.3",
"internal-slot": "^1.0.2",
"ipaddr.js": "^2.0.0",
"is-arrayish": "^0.3.2",
"is-binary-path": "^2.1.0",
"is-callable": "^1.2.2",
"is-ci": "^2.0.0",
"is-core-module": "^2.0.0",
"is-date-object": "^1.0.2",
"is-extglob": "^2.1.1",
"is-fullwidth-code-point": "^3.0.0",
"is-glob": "^4.0.1",
"is-installed-globally": "^0.3.2",
"is-negative-zero": "^2.0.0",
"is-npm": "^5.0.0",
"is-number": "^7.0.0",
"is-obj": "^2.0.0",
"is-path-inside": "^3.0.2",
"is-regex": "^1.1.1",
"is-regexp": "^2.1.0",
"is-stream": "^2.0.0",
"is-string": "^1.0.5",
"is-symbol": "^1.0.3",
"is-typedarray": "^1.0.0",
"is-yarn-global": "^0.3.0",
"isarray": "^2.0.5",
"isexe": "^2.0.0",
"form-data": "^3.0.0",
"joi": "^17.2.1",
"js-tokens": "^6.0.0",
"js-yaml": "^3.14.0",
"jsesc": "^3.0.1",
"json-buffer": "^3.0.1",
"json-parse-even-better-errors": "^2.3.1",
"json-schema-traverse": "^0.5.0",
"json-stable-stringify-without-jsonify": "^1.0.1",
"json5": "^2.1.3",
"jsonwebtoken": "^8.5.1",
"mongoose": "^5.10.11",
"morgan": "^1.10.0"
Expand Down
4 changes: 3 additions & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ const commentRoutes = require('./routes/commentRoutes');
const myPlantRoutes = require('./routes/myPlantRoutes');
const favoriteRoutes = require('./routes/favoriteRoutes');
const collectionRoutes = require('./routes/collectionRoutes');
const scanner = require('./routes/scanner');

// MongoDB connection
// mongodb://localhost:27017/noderest => meu banco de dados local polupado
Expand All @@ -22,8 +23,8 @@ mongoose
})
.then(() => console.log('MongoDB Connected'))
.catch((err) => console.log(err));

// middlewares
app.use(express.json({ limit: 20 * 1024 * 1024 }));
app.use(morgan('dev'));
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
Expand All @@ -37,6 +38,7 @@ app.use('/comment', commentRoutes);
app.use('/myplants', myPlantRoutes);
app.use('/favorites', favoriteRoutes);
app.use('/collection', collectionRoutes);
app.use('/scanner', scanner);

// starting the server
app.set('port', process.env.PORT || 3000);
Expand Down
7 changes: 0 additions & 7 deletions src/models/Plant.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,39 +16,32 @@ const PlantSchema = new mongoose.Schema({
},
specieName: {
type: String,
require: true,
},
commonName: {
type: String,
require: true,
},
usage: {
type: String,
require: true,
},
firstUser: {
type: String,
require: true,
},
collectionCount: {
type: Number,
require: true,
},
extinction: {
type: Boolean,
require: true,
},
profilePicture: {
type: String,
require: true,
},
gbifID: {
type: Number,
require: true,
},
stateProvince: {
type: String,
require: true,
},
topics: [
{
Expand Down
Binary file added src/planta.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
8 changes: 6 additions & 2 deletions src/routes/commentRoutes.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,18 @@ router.post('/create/:topicId/:userId', async (req, res) => {
user: req.params.userId,
topic: req.params.topicId,
});
const topic = await Topic.findById(req.params.topicId);
const topic = await Topic.findById(req.params.topicId).populate([
{ path: 'comments', populate: { path: 'user' } },
{ path: 'user' },
{ path: 'plant' },
]);

await comment.save();

topic.comments.push(comment);
await topic.save();

return res.send({ message: 'Comment successfully registered.' });
return res.send(topic);
} catch (err) {
return res.status(400).send({ error: `Error while commenting.${err}` });
}
Expand Down
10 changes: 8 additions & 2 deletions src/routes/plantRoutes.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,14 +50,20 @@ router.post('/register', async (req, res) => {

return res.send({ plant });
} catch (err) {
if (err.code === 11000) {
const { scientificName } = req.body;
const plant = await Plant.find({
scientificName,
}).populate('topics');
return res.send({ plant });
}
return res.send(err);
}
});
// Listagem de Todas as plantas
router.get('/', async (req, res) => {
try {
const plants = await Plant.find().populate('topics');

return res.send({ plants });
} catch (err) {
return res.status(400).send({ error: 'Loading plants failed' });
Expand All @@ -75,7 +81,7 @@ router.get('/:plantId', async (req, res) => {
.send({ error: 'error when searching for this plant ' });
}
});
// Deletando planta por id
// Detando planta por id
router.delete('/:plantId', async (req, res) => {
try {
const deleted = await Plant.findByIdAndRemove(req.params.plantId);
Expand Down
53 changes: 53 additions & 0 deletions src/routes/scanner.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
const express = require('express');

const router = express.Router();
const fs = require('fs'); // File System | Node.js
const axios = require('axios'); // HTTP client
const FormData = require('form-data'); // Readable "multipart/form-data" streams
const path = require('path');
require('dotenv').config();

function openFileReadStream(filePath) {
return new Promise((resolve, reject) => {
const readStream = fs.createReadStream(filePath);
readStream.on('open', () => resolve(readStream));
readStream.on('error', (err) => reject(err));
});
}

router.post('/', async (req, res, next) => {
try {
const apiKey = process.env.PLANT_NET_API_KEY; // api key do plant net
const { data, filename, mime, plantType } = req.body;
const requireFields = { data, filename, mime, plantType };
const erros = [];
Object.entries(requireFields).forEach(([key, value]) => {
if (!value) erros.push(`${key} is required`);
});
if (erros.length) throw erros;
const fileFormat = mime.split('/').pop();
const filePath = path.join(__dirname, '..', `${filename}.${fileFormat}`);
fs.writeFileSync(filePath, data, { encoding: 'base64' });
const form = new FormData();
form.append('organs', plantType);
const stream = await openFileReadStream(filePath);

form.append('images', stream);

const response = await axios.post(
`https://my-api.plantnet.org/v2/identify/all?api-key=${apiKey}`,
form,
{
headers: form.getHeaders(),
}
);
fs.unlinkSync(filePath);

res.send(response.data);
} catch (err) {
if (Array.isArray(err)) res.status(400).send({ errors: err });
next(err);
}
});

module.exports = router;
Loading

0 comments on commit cea945e

Please sign in to comment.