이승윤

Merge branch 'feat/categori' into 'develop'

Feat/categori



See merge request !4
<!DOCTYPE html>
<html>
<body>
<div id="player0"></div>
<div id="player1"></div>
<div id="player2"></div>
<script>
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
var players = [];
players.push('player0');
players.push('player1');
players.push('player2');
var videoIds = [];
videoIds.push('037o6vxm0es');
videoIds.push('kR77WlHRZrs');
videoIds.push('R6IT_f0XPT8');
function onYouTubeIframeAPIReady()
{
for(var i = 0; i < videoIds.length; i++)
{
player = new YT.Player(players[i], {
height: '360',
width: '640',
videoId: videoIds[i],
events: {
// 'onReady': onPlayerReady,
// 'onStateChange': onPlayerStateChange
}
});
}
}
// function onPlayerReady(event) {
// }
// function onPlayerStateChange(event) {
// }
// function stopVideo() {
// }
</script>
</body>
</html>
\ No newline at end of file
......@@ -19,12 +19,12 @@ db.on('error', console.error);
db.once('open', function () {
console.log('mongo db Connection');
});
var connect = mongoose.connect('mongodb://127.0.0.1:27017/cookBook', {
var connect = mongoose.connect('mongodb://127.0.0.1:27017/test', {
useMongoClient: true,
});
//admin module get
var admin = require('./routes/admin');
//categori module get
var categori = require('./routes/categori');
var accounts = require('./routes/accounts');
var auth = require('./routes/auth');
var connectMongo = require('connect-mongo');
......@@ -69,18 +69,10 @@ app.use(function (req, res, next) {
//routes add
app.use('/', Search);
app.use('/admin', admin);
app.use('/categori', categori);
app.use('/accounts', accounts);
app.use('/auth', auth);
var server = app.listen(port, function () {
console.log('Express listening on port', port);
});
var listen = require('socket.io');
var io = listen(server);
//socket io passport 접근하기 위한 미들웨어 적용
io.use(function (socket, next) {
sessionMiddleWare(socket.request, socket.request.res, next);
});
require('./libs/socketConnection')(io);
......
require('./removeByValue')();
var userList = []; //사용자 리스트를 저장할곳
module.exports = function(io) {
io.on('connection', function(socket){
var session = socket.request.session.passport;
var user = (typeof session !== 'undefined') ? ( session.user ) : "";
// userList 필드에 사용자 명이 존재 하지 않으면 삽입
if(userList.indexOf(user.displayname) === -1){
userList.push(user.displayname);
}
io.emit('join', userList);
//사용자 명과 메시지를 같이 반환한다.
socket.on('client message', function(data){
io.emit('server message', { message : data.message , displayname : user.displayname });
});
socket.on('disconnect', function(){
userList.removeByValue(user.displayname);
io.emit('leave', userList);
});
});
};
\ No newline at end of file
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var CategoriSchema = new Schema({
title: {
type: String,
default: 'default',
required: [true, '카테고리명이 비어있습니다!'],
},
videoNum: String,
description: String, //설명
created_at: {
type: Date,
default: Date.now(),
},
username: String,
});
CategoriSchema.virtual('getDate').get(function () {
var date = new Date(this.created_at);
return {
year: date.getFullYear(),
month: date.getMonth() + 1,
day: date.getDate(),
};
});
module.exports = mongoose.model('categories', CategoriSchema);
......@@ -9,7 +9,7 @@ var ProductsSchema = new Schema({
required: [true, '제목은 입력해주세요'],
},
thumbnail: String, //이미지 파일명
price: Number, //가격
price: Number, //가격
description: String, //설명
created_at: {
//작성일
......@@ -31,5 +31,5 @@ ProductsSchema.virtual('getDate').get(function () {
// 1씩 증가하는 primary Key를 만든다
// model : 생성할 document 이름
// field : primary key , startAt : 1부터 시작
module.exports = mongoose.model('products', ProductsSchema);
module.exports = mongoose.model('products', ProductsSchema);
\ No newline at end of file
......
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var VideoSchema = new Schema({
username: {
type: String,
required: [true, '아이디는 필수입니다.'],
},
password: {
type: String,
required: [true, '패스워드는 필수입니다.'],
},
displayname: String,
created_at: {
type: Date,
default: Date.now(),
},
});
module.exports = mongoose.model('videos', VideoSchema);
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var VideoSchema = new Schema({
name: String,
title: String,
videoId: String,
description: String, //설명
url: String,
});
module.exports = mongoose.model('videos', VideoSchema);
......@@ -4,13 +4,12 @@ var youtube = new Youtube();
var express = require('express');
var router = express.Router();
var word = '백종원 레시피'; // 검색어 지정
var word = '백종원'; // 검색어 지정
var limit = 10; // 출력 갯수
var video = [];
var test = 'test';
var count = 0;
youtube.setKey('AIzaSyAsKr_oWGZIBbL5tLdIl98Lf9Pzqj8jX4o'); // API 키 입력
youtube.addParam('order', 'rating'); // 평점 순으로 정렬
youtube.addParam('type', 'video'); // 타입 지정
youtube.addParam('videoLicense', 'creativeCommon'); // 크리에이티브 커먼즈 아이템만 불러옴
......
var Youtube = require('youtube-node');
var youtube = new Youtube();
var express = require('express');
var router = express.Router();
var word = '백종원'; // 검색어 지정
var limit = 10; // 출력 갯수
var video = [];
var test = 'test';
var count = 0;
youtube.setKey('AIzaSyAsKr_oWGZIBbL5tLdIl98Lf9Pzqj8jX4o'); // API 키 입력
youtube.addParam('order', 'rating'); // 평점 순으로 정렬
youtube.addParam('type', 'video'); // 타입 지정
youtube.addParam('videoLicense', 'creativeCommon'); // 크리에이티브 커먼즈 아이템만 불러옴
youtube.search(word, limit, function (err, result) {
// 검색 실행
if (err) {
console.log(err);
} // 에러일 경우 에러공지하고 빠져나감
//console.log(JSON.stringify(result, null, 2)); // 받아온 전체 리스트 출력
var items = result['items']; // 결과 중 items 항목만 가져옴
for (var i in items) {
var it = items[i];
for (var j in it) {
if (it[j]['title'] != null) {
var title = it[j]['title'];
}
if (it[j]['videoId'] != null) {
var video_id = it[j]['videoId'];
}
var urls = 'https://www.youtube.com/watch?v=' + video_id;
}
var item = {
id: count,
title: title,
video_id: video_id,
urls: urls,
};
count++;
video.push(item);
}
});
router.get('/', function (req, res) {
res.render(
'home',
{ videos: video } // DB에서 받은 videos를 videos변수명으로 내보냄
);
});
module.exports = router;
var express = require('express');
var router = express.Router();
var ProductsModel = require('../models/ProductsModel');
var CommentsModel = require('../models/VideoModels');
var csrf = require('csurf');
var csrfProtection = csrf({ cookie: true });
var CategoriModel = require('../models/CategoriModel');
//var csrf = require('csurf');
//var csrfProtection = csrf({ cookie: true });
var loginRequired = require('../libs/loginRequired');
var path = require('path');
......@@ -29,62 +28,49 @@ var storage = multer.diskStorage({
var upload = multer({ storage: storage });
router.get('/', function (req, res) {
res.send('admin main page');
res.send('categori main page');
});
router.get('/products', function (req, res) {
ProductsModel.find(function (err, products) {
CategoriModel.find(function (err, products) {
res.render(
'admin/products',
{ products: products }
'category/products',
{ categories: products }
//ProductModel의 products를 받아서
//admin/products로 response를 보낸다.
//categori/products로 response를 보낸다.
);
});
});
router.get(
'/products/write',
loginRequired,
csrfProtection,
function (req, res) {
//edit에서도 같은 form을 사용하므로 빈 변수( product )를 넣어서 에러를 피해준다
res.render('admin/form', { product: '', csrfToken: req.csrfToken() });
}
);
router.get('/categories/write', loginRequired, function (req, res) {
//edit에서도 같은 form을 사용하므로 빈 변수( product )를 넣어서 에러를 피해준다
res.render('category/form', { categories: '' });
});
router.post(
'/products/write',
upload.single('thumbnail'),
loginRequired,
csrfProtection,
function (req, res) {
var product = new ProductsModel({
name: req.body.name,
thumbnail: req.file ? req.file.filename : '',
price: req.body.price,
description: req.body.description,
username: req.user.username,
router.post('/categories/write', loginRequired, function (req, res) {
var category = new CategoriModel({
title: req.body.title,
description: req.body.description,
username: req.user.username,
});
//이 아래는 수정되지 않았음
var validationError = category.validateSync();
if (validationError) {
res.send(validationError);
} else {
category.save(function (err) {
res.redirect('/categori/products');
});
//이 아래는 수정되지 않았음
var validationError = product.validateSync();
if (validationError) {
res.send(validationError);
} else {
product.save(function (err) {
res.redirect('/admin/products');
});
}
//이 위는 수정되지 않았음
}
);
//이 위는 수정되지 않았음
});
router.get('/products/detail/:id', function (req, res) {
//url 에서 변수 값을 받아올떈 req.params.id 로 받아온다
ProductsModel.findOne({ id: req.params.id }, function (err, product) {
CategoriModel.findOne({ _id: req.params.id }, function (err, product) {
//제품정보를 받고 그안에서 댓글을 받아온다.
CommentsModel.find({ product_id: req.params.id }, function (err, comments) {
res.render('admin/productsDetail', {
CategoriModel.find({ product_id: req.params.id }, function (err, comments) {
res.render('category/productsDetail', {
product: product,
comments: comments,
});
......@@ -92,29 +78,23 @@ router.get('/products/detail/:id', function (req, res) {
});
});
router.get(
'/products/edit/:id',
loginRequired,
csrfProtection,
function (req, res) {
//기존에 폼에 value안에 값을 셋팅하기 위해 만든다.
ProductsModel.findOne({ id: req.params.id }, function (err, product) {
res.render('admin/form', {
product: product,
csrfToken: req.csrfToken(),
});
router.get('/products/edit/:id', loginRequired, function (req, res) {
//기존에 폼에 value안에 값을 셋팅하기 위해 만든다.
CategoriModel.findOne({ _id: req.params.id }, function (err, product) {
res.render('category/form', {
categories: product,
});
}
);
});
});
router.post(
'/products/edit/:id',
loginRequired,
upload.single('thumbnail'),
csrfProtection,
// csrfProtection,
function (req, res) {
//그전에 지정되 있는 파일명을 받아온다
ProductsModel.findOne({ id: req.params.id }, function (err, product) {
CategoriModel.findOne({ _id: req.params.id }, function (err, product) {
//아래의 코드만 추가되면 된다.
if (req.file && product.thumbnail) {
//요청중에 파일이 존재 할시 이전이미지 지운다.
......@@ -128,11 +108,11 @@ router.post(
price: req.body.price,
description: req.body.description,
};
ProductsModel.update(
CategoriModel.update(
{ id: req.params.id },
{ $set: query },
function (err) {
res.redirect('/admin/products/detail/' + req.params.id);
res.redirect('/category/products/detail/' + req.params.id);
}
);
});
......@@ -140,13 +120,13 @@ router.post(
);
router.get('/products/delete/:id', function (req, res) {
ProductsModel.remove({ id: req.params.id }, function (err) {
res.redirect('/admin/products');
CategoriModel.deleteMany({ _id: req.params.id }, function (err) {
res.redirect('/categori/products');
});
});
router.post('/products/ajax_comment/insert', function (req, res) {
var comment = new CommentsModel({
var comment = new CategoriModel({
content: req.body.content,
product_id: parseInt(req.body.product_id),
});
......@@ -160,7 +140,7 @@ router.post('/products/ajax_comment/insert', function (req, res) {
});
router.post('/products/ajax_comment/delete', function (req, res) {
CommentsModel.remove({ id: req.body.comment_id }, function (err) {
CategoriModel.remove({ _id: req.body.comment_id }, function (err) {
res.json({ message: 'success' });
});
});
......
<% include ../includes/header.ejs %>
<form action="" method="post" enctype="multipart/form-data">
<input type="hidden" name="_csrf" value="<%=csrfToken%>" />
<table class="table table-bordered">
<tr>
<th>제품명</th>
<td><input type="text" name="name" class="form-control" value="<%=product.name%>"/></td>
</tr>
<tr>
<th>섬네일</th>
<td>
<input type="file" name="thumbnail" />
<% if(product.thumbnail){ %>
<a href="/uploads/<%=product.thumbnail%>" target="_blank">업로드 이미지 보기</a>
<% } %>
</td>
</tr>
<tr>
<th>가격</th>
<td><input type="text" name="price" class="form-control" value="<%=product.price%>"/></td>
</tr>
<tr>
<th>설명</th>
<td><input type="text" name="description" class="form-control" value="<%=product.description%>"/></td>
</tr>
</table>
<button class="btn btn-primary">작성하기</button>
</form>
<% include ../includes/footer.ejs %>
\ No newline at end of file
<% include ../includes/header.ejs %>
<form action="" method="post" >
<table class="table table-bordered">
<tr>
<th>카테고리명</th>
<td><input type="text" name="title" class="form-control" value="<%=categories.title%>"/></td>
</tr>
<tr>
<th>설명</th>
<td><input type="text" name="description" class="form-control" value="<%=categories.description%>"/></td>
</tr>
</table>
<input type="submit" name="submit" value="submit" class="btn btn-primary">
</form>
<% include ../includes/footer.ejs %>
\ No newline at end of file
<% include ../includes/header.ejs %>
<table class="table table-bordered table-hover">
<tr>
<th>제목</th>
<th>작성일</th>
<th width="100px" style="text-align: center;">카테고리명</th>
<th style="text-align: center;">개설 날짜</th>
<th>내용</th>
<th>사용자명</th>
<th>삭제</th>
</tr>
<%products.forEach(function(product){%>
<%categories.forEach(function(product){%>
<tr>
<td>
<a href="/admin/products/detail/<%=product.id%>"><%=product.name%></a>
<a href="/categori/products/detail/<%=product.id%>"><%=product.title%></a>
</td>
<td>
<%=product.getDate.year%> -
......@@ -16,12 +18,18 @@
<%=product.getDate.day%>
</td>
<td>
<a href="/admin/products/delete/<%=product.id%>" class="btn btn-danger" onclick="return confirm('삭제하시겠습니까?')">삭제</a>
<%=product.description%> -
</td>
<td>
<%=product.username%> -
</td>
<td>
<a href="/categori/products/delete/<%=product.id%>" class="btn btn-danger" onclick="return confirm('삭제하시겠습니까?')">삭제</a>
</td>
</tr>
<% }); %>
</table>
<a href="/admin/products/write" class="btn btn-default">작성하기</a>
<a href="categori/write" class="btn btn-default">작성하기</a>
<% include ../includes/footer.ejs %>
\ No newline at end of file
......
<% include ../includes/header.ejs %>
<div class="panel panel-default">
<div class="panel-heading">
<%=product.name%>
<%=product.title%>
</div>
<div class="panel-body">
<div style="padding-bottom: 10px">
......@@ -20,7 +20,7 @@
<div>
댓글작성하기
<form id="commentForm" action="" method="post">
<input type="hidden" name="product_id" value="<%=product.id%>" />
<input type="hidden" name="product_id" value="<%=product._id%>" />
<textarea class="form-control" name="content"></textarea>
<button class="btn btn-primary" style="margin-top: 10px">댓글작성</button>
</form>
......@@ -31,15 +31,15 @@
<% comments.forEach(function(comment){ %>
<div>
<%=comment.content%>
( <a class='comment_delete' comment_id='<%=comment.id%>'>삭제</a> )
( <a class='comment_delete' comment_id='<%=comment._id%>'>삭제</a> )
</div>
<% }); %>
</div>
</div>
</div>
<a href="/admin/products" class="btn btn-default">목록으로</a>
<a href="/admin/products/edit/<%=product.id%>" class="btn btn-primary">수정</a>
<a href="/categori/products" class="btn btn-default">목록으로</a>
<a href="/categori/products/edit/<%=product._id%>" class="btn btn-primary">수정</a>
<% include ../includes/footer.ejs %>
<script>
(function(){
......@@ -56,7 +56,7 @@
if(args.message==="success"){
$('#comment_area').append(
'<div>' + args.content +
" ( <a class='comment_delete' comment_id='"+ args.id +"'>삭제</a> ) </div>"
" ( <a class='comment_delete' comment_id='"+ args._id +"'>삭제</a> ) </div>"
);
$('#commentForm textarea[name=content]').val("");
}
......
<% include ./includes/header.ejs %>
<div class="container" id="masonry_container">
<div id="masonry_container">
한식
<% for (var i in videos) { %>
<div id="<%=videos[i].id%>" vid="<%=videos[i].video_id%>">
</div>
......
......@@ -33,7 +33,7 @@
<li class="active">
<a href="/">Home</a>
</li>
<li><a href="/admin/products">Categori</a></li>
<li><a href="/categori/products">Categori</a></li>
<% if(isLogin){%>
<li><a href="/accounts/logout" onclick="return confirm('로그아웃 하시겠습니까?')">LOGOUT</a></li>
<%}else{%>
......