이승윤

Merge branch 'feat/Video' into 'develop'

Feat/video



See merge request !6
......@@ -28,7 +28,7 @@ var categori = require('./routes/categori');
var accounts = require('./routes/accounts');
var auth = require('./routes/auth');
var connectMongo = require('connect-mongo');
var Search = require('./routes/Search');
var Video = require('./routes/Videos');
var MongoStore = connectMongo(session);
app.set('views', path.join(__dirname, 'views'));
......@@ -68,7 +68,7 @@ app.use(function (req, res, next) {
});
//routes add
app.use('/', Search);
app.use('/', Video);
app.use('/categori', categori);
app.use('/accounts', accounts);
app.use('/auth', auth);
......
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
//생성될 필드명을 정한다.
var ProductsSchema = new Schema({
name: {
//제품명
type: String,
required: [true, '제목은 입력해주세요'],
},
thumbnail: String, //이미지 파일명
price: Number, //가격
description: String, //설명
created_at: {
//작성일
type: Date,
default: Date.now(),
},
username: String, //작성자추가
});
ProductsSchema.virtual('getDate').get(function () {
var date = new Date(this.created_at);
return {
year: date.getFullYear(),
month: date.getMonth() + 1,
day: date.getDate(),
};
});
// 1씩 증가하는 primary Key를 만든다
// model : 생성할 document 이름
// field : primary key , startAt : 1부터 시작
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(),
},
categori: String,
id: Number,
title: String,
video_id: String,
urls: String,
});
module.exports = mongoose.model('videos', VideoSchema);
......
......@@ -9,7 +9,7 @@ var limit = 10; // 출력 갯수
var video = [];
var test = 'test';
var count = 0;
youtube.setKey('AIzaSyAsKr_oWGZIBbL5tLdIl98Lf9Pzqj8jX4o'); // API 키 입력
youtube.setKey('AIzaSyCAaeW1qMSInEdN1OzU20FZlToIZYkb1bc'); // API 키 입력
youtube.addParam('order', 'rating'); // 평점 순으로 정렬
youtube.addParam('type', 'video'); // 타입 지정
youtube.addParam('videoLicense', 'creativeCommon'); // 크리에이티브 커먼즈 아이템만 불러옴
......@@ -19,9 +19,7 @@ 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];
......
var Youtube = require('youtube-node');
var youtube = new Youtube();
var express = require('express');
var CategoriModel = require('../models/CategoriModel');
var VideoModel = require('../models/VideoModel');
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'];
router.get('/', function (req, res) {
CategoriModel.find(function (err, category) {
VideoModel.find(function (err, video) {
var item = []; // 카테고리별 비디오 목록을 담아두는 배열
for (var i in category) {
var videos = []; // 비디오 목록을 담는 임시 배열
for (var j in video) {
if (category[i].title == video[j].categori) {
videos.push(video[j]);
}
var urls = 'https://www.youtube.com/watch?v=' + video_id;
}
var item = {
id: count,
title: title,
video_id: video_id,
urls: urls,
if (videos.length != 0) {
// 빈 배열 체크
console.log(videos);
var items = {
category: category[i],
videos: videos,
};
count++;
video.push(item);
item.push(items);
}
});
router.get('/', function (req, res) {
}
//console.log(item[2].category.title);
//console.log(item[2].videos);
res.render(
'home',
{ videos: video } // DB에서 받은 videos를 videos변수명으로 내보냄
{ video: item, categories: category } // DB에서 받은 videos와 category를 videos변수명으로 내보냄
);
});
});
});
module.exports = router;
......
var express = require('express');
var router = express.Router();
var CategoriModel = require('../models/CategoriModel');
//var csrf = require('csurf');
//var csrfProtection = csrf({ cookie: true });
var loginRequired = require('../libs/loginRequired');
var path = require('path');
var uploadDir = path.join(__dirname, '../uploads'); // 루트의 uploads위치에 저장한다.
var fs = require('fs');
var VideoModel = require('../models/VideoModel');
var Youtube = require('youtube-node');
var youtube = new Youtube();
//multer 셋팅
var multer = require('multer');
var storage = multer.diskStorage({
destination: function (req, file, callback) {
//이미지가 저장되는 도착지 지정
callback(null, uploadDir);
},
filename: function (req, file, callback) {
// products-날짜.jpg(png) 저장
callback(
null,
'products-' + Date.now() + '.' + file.mimetype.split('/')[1]
);
},
});
var loginRequired = require('../libs/loginRequired');
var upload = multer({ storage: storage });
var limit = 10; // 출력 갯수
youtube.setKey('AIzaSyCAaeW1qMSInEdN1OzU20FZlToIZYkb1bc'); // API 키 입력
router.get('/', function (req, res) {
res.send('categori main page');
......@@ -43,7 +26,6 @@ router.get('/products', function (req, res) {
});
router.get('/categories/write', loginRequired, function (req, res) {
//edit에서도 같은 form을 사용하므로 빈 변수( product )를 넣어서 에러를 피해준다
res.render('category/form', { categories: '' });
});
......@@ -67,15 +49,83 @@ router.post('/categories/write', loginRequired, function (req, res) {
router.get('/products/detail/:id', function (req, res) {
//url 에서 변수 값을 받아올떈 req.params.id 로 받아온다
var word = req.query.keyword;
CategoriModel.findOne({ _id: req.params.id }, function (err, product) {
var video = [];
//제품정보를 받고 그안에서 댓글을 받아온다.
CategoriModel.find({ product_id: req.params.id }, function (err, comments) {
if (word != null) {
var count = 0;
youtube.addParam('order', 'rating'); // 평점 순으로 정렬
youtube.addParam('type', 'video'); // 타입 지정
youtube.addParam('videoLicense', 'creativeCommon'); // 크리에이티브 커먼즈 아이템만 불러옴
youtube.search(word, limit, function (err, result) {
// 검색 실행
console.log(word);
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,
categori: product.title,
};
count++;
video.push(item);
}
res.render('category/productsDetail', {
product: product,
comments: comments,
videos: video,
});
});
} else {
res.render('category/productsDetail', {
product: product,
comments: comments,
videos: video,
});
}
});
});
});
router.post('/products/detail/:id', loginRequired, function (req, res) {
var item = [];
var count = 1;
for (var i in req.body.videoNum) {
item.push(req.body.videoNum[i].split('///'));
var video = new VideoModel({
categori: item[i][2],
id: count,
title: item[i][1],
video_id: item[i][3],
urls: item[i][4],
});
var validationError = video.validateSync();
if (validationError) {
res.send(validationError);
} else {
video.save(function (err) {});
}
count++;
}
res.redirect('/categori/products');
});
router.get('/products/edit/:id', loginRequired, function (req, res) {
......@@ -87,21 +137,9 @@ router.get('/products/edit/:id', loginRequired, function (req, res) {
});
});
router.post(
'/products/edit/:id',
loginRequired,
upload.single('thumbnail'),
// csrfProtection,
function (req, res) {
router.post('/products/edit/:id', loginRequired, function (req, res) {
//그전에 지정되 있는 파일명을 받아온다
CategoriModel.findOne({ _id: req.params.id }, function (err, product) {
//아래의 코드만 추가되면 된다.
if (req.file && product.thumbnail) {
//요청중에 파일이 존재 할시 이전이미지 지운다.
fs.unlinkSync(uploadDir + '/' + product.thumbnail);
}
//위의 코드만 추가되면 된다.
//넣을 변수 값을 셋팅한다
var query = {
name: req.body.name,
thumbnail: req.file ? req.file.filename : product.thumbnail,
......@@ -112,12 +150,11 @@ router.post(
{ id: req.params.id },
{ $set: query },
function (err) {
res.redirect('/category/products/detail/' + req.params.id);
res.redirect('/categori/products/detail/' + req.params.id);
}
);
});
}
);
});
router.get('/products/delete/:id', function (req, res) {
CategoriModel.deleteMany({ _id: req.params.id }, function (err) {
......
......@@ -10,6 +10,6 @@
<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">
<input type="submit" name="submit" value="완료" class="btn btn-primary">
</form>
<% include ../includes/footer.ejs %>
\ No newline at end of file
......
......@@ -3,6 +3,32 @@
<div class="panel-heading">
<%=product.title%>
</div>
<form method="get" action="">
<div class="input-group">
<input type="text" class="form-control" placeholder="검색 키워드를 입력하세요!" name="keyword" autocomplete='off'>
<span class="input-group-btn">
<button class="btn btn-secondary" type="submit">찾기</button>
</span>
</div>
</form>
<form method="post" action="">
<% for (var i in videos) { %>
<div style="float:left;
padding: 15px;
">
<input type="checkbox" name="videoNum" style="
position: absolute;
margin-top: 5px;
margin-left: 5px;
z-index: 4;
zoom:3.0;
" value="<%=videos[i].id + '///' + videos[i].title +'///'+ videos[i].categori +'///'+ videos[i].video_id +'///'+ videos[i].urls%>"/>
<div id="<%=videos[i].id%>" vid="<%=videos[i].video_id%>">
</div>
</div>
<%};%>
<button class="btn btn-primary" style="margin-top: 10px; margin-left: 15px;" >영상담기</button>
</form>
<div class="panel-body">
<div style="padding-bottom: 10px">
작성일 :
......@@ -20,9 +46,9 @@
<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>
<button class="btn btn-primary" style="margin-top: 10px" type="submit">댓글작성</button>
</form>
</div>
<!-- 댓글영역 -->
......@@ -91,3 +117,44 @@ $(document).on('click' , '.comment_delete' , function(){
}
});
</script>
<script src="https://unpkg.com/masonry-layout@4/dist/masonry.pkgd.min.js"></script>
<script type="text/javascript"
src="https://cdnjs.cloudflare.com/ajax/libs/jquery.imagesloaded/4.1.1/imagesloaded.pkgd.min.js"></script>
<script type="text/javascript">
var $masonry_container = $('#masonry_container');
$masonry_container.imagesLoaded(function () {
$masonry_container.masonry({
itemSelector: '.masonry-grid',
columnWidth: 270
});
});
</script>
<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 = [];
var videoIds = [];
for (var i = 0; i < 10; i++) {
players.push(String(i));
videoIds.push($('#' + i).attr('vid'));
}
function onYouTubeIframeAPIReady() {
for (var i = 0; i < videoIds.length; i++) {
player = new YT.Player(players[i], {
height: '300',
width: '500',
videoId: videoIds[i],
events: {
// 'onReady': onPlayerReady,
// 'onStateChange': onPlayerStateChange
}
});
}
}
</script>
\ No newline at end of file
......