Skip to content

Commit

Permalink
more stuff
Browse files Browse the repository at this point in the history
  • Loading branch information
Turbotailz committed Mar 14, 2021
1 parent 861d3f7 commit b356f0a
Show file tree
Hide file tree
Showing 15 changed files with 3,477 additions and 92 deletions.
34 changes: 25 additions & 9 deletions actions/get-image.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,30 @@
const db = require('../database');

module.exports = async (id) => {
let image;
async function getImage(id) {
return !isNaN(parseInt(id)) ? db('images').where({ id }).first() : null;
}

if (id) {
image = await db('images').where({ id }).first();
} else {
const { rows } = await db.raw('SELECT * FROM images TABLESAMPLE SYSTEM_ROWS(1)');
image = rows[0];
}
async function getImages(currentPage, sort) {
return db('images').orderBy('created_at', sort).paginate({ currentPage });
}

return image;
async function getRandomImage() {
const { rows } = await db.raw('SELECT * FROM images TABLESAMPLE SYSTEM_ROWS(1)');
return rows[0];
}

async function getLatestImage() {
return db('images').whereNotNull('taken_at').orderBy('taken_at', 'desc').first();
}

async function getLatestImages(currentPage, sort) {
return db('images').whereNotNull('taken_at').orderBy('taken_at', sort).paginate({ currentPage });
}

module.exports = {
getImage,
getImages,
getLatestImage,
getLatestImages,
getRandomImage,
}
6 changes: 5 additions & 1 deletion actions/index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
const getImage = require('./get-image');
const { getImage, getImages, getLatestImage, getLatestImages, getRandomImage } = require('./get-image');
const putImage = require('./put-image');

module.exports = {
getImage,
getImages,
getLatestImage,
getLatestImages,
getRandomImage,
putImage,
};
5 changes: 3 additions & 2 deletions actions/put-image.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@ const exifr = require('exifr');
const AWS = require('aws-sdk');
const { env } = process;
const FileType = require('file-type');
const crypto = require('crypto');

async function putImage(filename, image, caption, knex) {
async function putImage(image, caption, knex) {
const db = knex || database;

let taken_at;
Expand All @@ -27,7 +28,7 @@ async function putImage(filename, image, caption, knex) {
});

const { mime: ContentType } = await FileType.fromBuffer(image);
const Key = env.S3_IMAGE_DIR + filename;
const Key = env.S3_IMAGE_DIR + crypto.randomBytes(10).toString('hex');

try {
const data = await s3.upload({
Expand Down
5 changes: 4 additions & 1 deletion database/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
const environment = process.env.ENVIRONMENT || 'development';
const config = require('../knexfile')[environment];
const knex = require('knex')(config);
const { attachPaginate } = require('knex-paginate');
attachPaginate();

module.exports = require('knex')(config);
module.exports = knex;
15 changes: 15 additions & 0 deletions database/migrations/20210314013831_create_users_table.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@

exports.up = (knex) => {
return knex.schema.createTable('users', (table) => {
table.increments();
table.string('email').notNullable();
table.string('password').notNullable();
table.string('token');
table.timestamp('created_at').defaultTo(knex.fn.now());
table.timestamp('updated_at').defaultTo(knex.fn.now());
})
};

exports.down = (knex) => {
return knex.schema.dropTable('users');
};
38 changes: 19 additions & 19 deletions database/seeds/01_images.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,23 +4,23 @@ const filePath = __dirname + '/images/'
const images = fs.readdirSync(filePath);

exports.seed = async knex => {
// Deletes ALL existing entries
console.log('Deleting all image records...');
await knex('images').del();
console.log('Done');

// Inserts images into the database
console.log('Inserting images to database...');
const promises = [];

for (const image of images) {
const buffer = fs.readFileSync(filePath + image);
promises.push(putImage(image, buffer, null, knex));
}

console.log('Done');

return Promise.all(promises).then(() => {
console.log('Done');
});
// // Deletes ALL existing entries
// console.log('Deleting all image records...');
// await knex('images').del();
// console.log('Done');
//
// // Inserts images into the database
// console.log('Inserting images to database...');
// const promises = [];
//
// for (const image of images) {
// const buffer = fs.readFileSync(filePath + image);
// promises.push(putImage(buffer, null, knex));
// }
//
// console.log('Done');
//
// return Promise.all(promises).then(() => {
// console.log('Done');
// });
};
14 changes: 14 additions & 0 deletions database/seeds/02_users.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
require('dotenv').config();

const { getHash } = require('../../util/password');

exports.seed = async (knex) => {
// Deletes ALL existing entries
await knex('users').del();

// Inserts seed entries
await knex('users').insert([
{ id: 1, email: '[email protected]', password: getHash('yeet') },
]);

};
3 changes: 1 addition & 2 deletions events/discord-ready.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
module.exports = client => {
module.exports = () => {
console.log('Logged in to Discord');
console.log(client);
}
26 changes: 0 additions & 26 deletions get-image.js

This file was deleted.

67 changes: 40 additions & 27 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,38 +1,51 @@
require('dotenv').config();

const express = require('express');
const { ENVIRONMENT_DOMAIN, DISCORD_TOKEN, PORT, SECRET_TOKEN } = process.env;

const bodyParser = require('body-parser');
const cors = require('cors');
const Discord = require('discord.js');
const { getRandomImageId, getImageName } = require('./get-image');
const { DISCORD_TOKEN, PORT } = process.env;
const client = new Discord.Client();
const app = express();
const express = require('express');
const expressSession = require('express-session')({
secret: SECRET_TOKEN,
cookie: {
maxAge: 24 * 60 * 60 * 1000
},
resave: false,
saveUninitialized: false,
unset: 'destroy',
});
const morgan = require('morgan');
const passport = require('./util/passport');
const router = require('./routes');
const db = require('./database');

const { discordMessage, discordReady } = require('./events');

// Register Discord events
client.on('message', discordMessage);
client.on('ready', discordReady);

// Login to Discord client
client.login(DISCORD_TOKEN);
const app = express();
const corsOptions = {
origin: ENVIRONMENT_DOMAIN,
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
credentials: true,
exposedHeaders: ['set-cookie'],
};

app.use(morgan('dev'));
app.use(expressSession);
app.use(passport.initialize());
app.use(passport.session());
app.use(cors(corsOptions));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(router);
// app.get('/', (req, res) => {
// const id = getRandomImageId();
// res.redirect(`/${id}`);
// });
//
// app.get('/:id', (req, res) => {
// const image = getImageName(req.params.id);
// if (image) {
// res.sendFile(`${__dirname}/images/${image}`);
// } else {
// res.sendStatus(404);
// }
// });

app.listen(PORT || 6969, () => {
console.log(`Example app listening at http://localhost:${PORT}`)
console.log(`App started. Listening on http://localhost:${PORT}`);
});

const client = new Discord.Client();

// Register Discord events
client.on('message', discordMessage);
client.on('ready', discordReady);

// Login to Discord client
// client.login(DISCORD_TOKEN);
Loading

0 comments on commit b356f0a

Please sign in to comment.