Last active
December 11, 2015 04:29
-
-
Save pphetra/4545635 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| var environment = require('../environment'), | |
| service = require('../service'), | |
| passport = require('passport'), | |
| model = service.useModel('model'), | |
| http = require('http'), | |
| KEYS = require('../key'), | |
| im = require('imagemagick'), | |
| knox = require('knox'); | |
| // amazon s3 | |
| var client = knox.createClient({ | |
| key: KEYS.AMAZON_S3_ACCESS | |
| , secret: KEYS.AMAZON_S3_SECERT | |
| , bucket: KEYS.AMAZON_S3_BUCKET | |
| }); | |
| exports.add = function(req, res){ | |
| model.Report.find({},function(err, docs){ | |
| res.render('add.jade', { title: 'City bug', report: docs }); | |
| }); | |
| }; | |
| exports.reports_campaign = function(req, res) { | |
| console.log('get campaign feed'); | |
| var url = req.url; | |
| var campaign_id = url.match( /[^\/]+\/?$/ ); | |
| var maxNumber = 30; | |
| getAllReports({campaign:campaign_id}, function(reports) { | |
| console.log(reports); | |
| responseReportsJSONToClient(res, reports, maxNumber); | |
| return; | |
| }); | |
| } | |
| //GET report imin by username | |
| exports.reports_imin = function(req, res) { | |
| console.log('get imin user feed'); | |
| var url = req.url; | |
| var username = url.match( /[^\/]+\/?$/ ); | |
| model.User.findOne({username: username}, {_id:1}, function(err, user){ | |
| if (err) { | |
| res.writeHead(500, { 'Content-Type' : 'application/json;charset=utf-8'}); | |
| res.end(); | |
| return; | |
| } else if(!user) { | |
| res.writeHead(404, { 'Content-Type' : 'application/json;charset=utf-8'}); | |
| res.end(); | |
| return; | |
| } else { | |
| model.Imin.find({user: user._id}, function(err, imins) { | |
| var queryIminReport = {}; | |
| queryIminReport["$or"] = []; | |
| for (i in imins) { | |
| queryIminReport["$or"].push({"_id":imins[i].report}); | |
| } | |
| if (queryIminReport['$or'].length <= 0) { | |
| res.writeHead(200, { 'Content-Type' : 'application/json;charset=utf-8'}); | |
| res.write('{"reports":[]}'); | |
| res.end(); | |
| return; | |
| } | |
| getAllReports(queryIminReport, function(reports) { | |
| console.log(reports); | |
| res.writeHead(200, { 'Content-Type' : 'application/json;charset=utf-8'}); | |
| res.write('{"reports":' + JSON.stringify(reports) + '}'); | |
| res.end(); | |
| }); | |
| }); | |
| } | |
| }); | |
| } | |
| //GET report by username | |
| exports.reports_username = function(req, res) { | |
| console.log('get user feed'); | |
| var url = req.url; | |
| var username = url.match( /[^\/]+\/?$/ ); | |
| model.User.findOne({username: username}, {_id:1, username:1, display_name:1, account_type:1, email:1, thumbnail_image:1, last_modified:1, created_at:1}, function(err, user){ | |
| if (err) { | |
| res.writeHead(500, { 'Content-Type' : 'application/json;charset=utf-8'}); | |
| res.end(); | |
| return; | |
| } else if(!user) { | |
| res.writeHead(404, { 'Content-Type' : 'application/json;charset=utf-8'}); | |
| res.end(); | |
| return; | |
| } else { | |
| model.Subscription.count({user: user._id}, function(err,subscription_count) { | |
| getAllReports({user: user._id}, function(reports) { | |
| var new_report = {}; | |
| new_report["user"] = { | |
| _id:user._id | |
| , username:user.username | |
| , display_name:user.display_name | |
| , account_type:user.account_type | |
| , email:user.email | |
| , thumbnail_image:user.thumbnail_image | |
| , subscription_count:subscription_count | |
| , reports:reports}; | |
| console.log("Get user detail of "+username); | |
| res.writeHead(200, { 'Content-Type' : 'application/json;charset=utf-8'}); | |
| // res.write(JSON.stringify(new_report)); | |
| res.write('{"reports":' + JSON.stringify(reports) + '}'); //return only array of reports | |
| res.end(); | |
| }); | |
| }); | |
| } | |
| }); | |
| } | |
| //GET reports by id_foursquare | |
| exports.reports_place = function(req, res) { | |
| var url = req.url; | |
| var currentId4sq = url.match( /[^\/]+\/?$/ ); | |
| console.log('get place feed from '+ url); | |
| model.Place.findOne({id_foursquare: currentId4sq}, function(err, place) { | |
| if (err || place == null) { | |
| res.writeHead(500, { 'Content-Type' : 'application/json;charset=utf-8', 'Text' : 'can not get reports place'}); //can not get reports place | |
| res.end(); | |
| return; | |
| } | |
| getAllReports({place: place}, function(reports){ | |
| res.writeHead(200, { 'Content-Type' : 'application/json;charset=utf-8'}); | |
| res.write('{"reports":' + JSON.stringify(reports.slice(0,30)) + '}'); //return only array of reports | |
| res.end(); | |
| }); | |
| }); | |
| } | |
| // GET /api/reports >> get list of entries | |
| exports.all_reports = function(req, res) { | |
| console.log('Get all report list'); | |
| getAllReports({}, function(new_report){ | |
| res.writeHead(200, { 'Content-Type' : 'application/json;charset=utf-8'}); | |
| res.write('{ "reports":' + JSON.stringify(new_report) + '}'); | |
| res.end(); | |
| return; | |
| }); | |
| }; | |
| exports.getAllReports = function(queryString, callbackFunction) { | |
| getAllReports(queryString, function (report) { | |
| return callbackFunction(report); | |
| }); | |
| } | |
| function getAllReports(queryString, callbackFunction) { | |
| // Query all report with all attribute | |
| // create custom json because relation database that | |
| // report can get comment, but comment can get only _id | |
| // so we query user in comment and make a new json | |
| // return have 3, none of report, report with comment, report without comment | |
| var new_report = []; | |
| var queryCount = 0; | |
| var maxQueryCount = 0; | |
| model.Report.find(queryString) | |
| .populate('user','username display_name account_type email thumbnail_image created_at last_modified') | |
| .populate('categories','title') | |
| .populate('comments') | |
| .populate('imins') | |
| .populate('place') | |
| .populate('campaign') | |
| .exec(function (err, report) { | |
| if (err) { | |
| console.log(err); | |
| } | |
| // have none of report | |
| if (report == null || report.length == 0) { | |
| report = []; | |
| callbackFunction(report); | |
| return; | |
| }; | |
| // find max comment, imin | |
| // find need to do before query | |
| for (r in report) { | |
| for (i in report[r].comments) { | |
| if (report[r].comments[i]._id != null && report[r].comments.length > 0) { | |
| if (i == 0) { | |
| maxQueryCount++; | |
| } | |
| } | |
| } | |
| for (i in report[r].imins) { | |
| if (report[r].imins[i]._id != null && report[r].imins.length > 0) { | |
| if (i == 0) { | |
| maxQueryCount++; | |
| } | |
| } | |
| } | |
| } | |
| for (r in report) { | |
| // add query comment where _id:id or _id:id .... | |
| var query_comments = {}; | |
| query_comments["$or"] = []; | |
| for (i in report[r].comments) { | |
| if (report[r].comments.length > 0 && report[r].comments[i]._id != null) { | |
| query_comments["$or"].push({"_id":report[r].comments[i]._id}); | |
| } | |
| } | |
| // add query imin where _id:id or _id:id .... | |
| // get all comment | |
| queryListComment(query_comments, r, function(comments, index, isQueryComment) { | |
| if (isQueryComment) { | |
| queryCount++; | |
| } | |
| var query_imins = {}; | |
| query_imins["$or"] = []; | |
| for (i in report[index].imins) { | |
| if (report[index].imins.length > 0 && report[index].imins[i]._id != null) { | |
| query_imins["$or"].push({"_id":report[index].imins[i]._id}); | |
| } | |
| } | |
| // get all imin | |
| queryListImin(query_imins, index, function(imins, index, isQueryImins) { | |
| // add data to report | |
| new_report.push( | |
| {"user":report[index].user, | |
| "_id":report[index]._id, | |
| "comments":comments, | |
| "title":report[index].title, | |
| "lat":report[index].lat, | |
| "lng":report[index].lng, | |
| "address":report[index].address, | |
| "note":report[index].note, | |
| "full_image":report[index].full_image, | |
| "thumbnail_image":report[index].thumbnail_image, | |
| "is_resolved":report[index].is_resolved, | |
| "is_shared_to_facebook":report[index].is_shared_to_facebook, | |
| "categories":report[index].categories, | |
| "campaign":report[index].campaign, | |
| "place":report[index].place, | |
| "imins":imins, | |
| "imin_count":report[index].imin_count, | |
| "last_modified":report[index].last_modified, | |
| "created_at":report[index].created_at | |
| }); | |
| if (isQueryImins) { | |
| queryCount++; | |
| } | |
| // have comment in any report | |
| if (maxQueryCount == queryCount && maxQueryCount != 0) { | |
| //Sorted by last_modified | |
| new_report = new_report.sort(function(a, b) { | |
| return new Date(b.last_modified).getTime() - new Date(a.last_modified).getTime(); | |
| }); | |
| // Return all Reports with all fields to callback function | |
| callbackFunction(new_report); | |
| } | |
| if (index == report.length) { | |
| callbackFunction(new_report); | |
| } | |
| }); | |
| }); | |
| } | |
| //Sorted by last_modified | |
| new_report = new_report.sort(function(a, b) { | |
| return new Date(b.last_modified).getTime() - new Date(a.last_modified).getTime(); | |
| }); | |
| // none of comment in any report | |
| if (maxQueryCount == 0) { | |
| callbackFunction(new_report); | |
| }; | |
| }); | |
| } | |
| function isSignInWithUser(currentUser) { | |
| return true; | |
| // return false; | |
| } | |
| /* | |
| //sort by distance | |
| for ( i in report ) { | |
| if (report[i].campaign == null) { | |
| report[i].campaign = new model.Campaign(); | |
| } | |
| var dt = 0; | |
| if (report[i].campaign.lat.length < 2 || report[i].campaign.lng.length < 2) { | |
| dt = 1000000000; | |
| } | |
| // find center of lat lng in campaign | |
| var centerLat = (report[i].campaign.lat[0] + report[i].campaign.lat[1]) / 2; | |
| var centerLng = (report[i].campaign.lng[0] + report[i].campaign.lng[1]) / 2; | |
| dt = service.distanceCalculate(centerLat, centerLng, currentLat, currentLng) | |
| report[i].campaign.distance = dt; | |
| console.log("distance > " + i + " => "+ report[i].campaign.distance); | |
| } | |
| //ใช้ตัวแปร distance จาก place | |
| report = report.sort(function(a, b) { | |
| if (a.campaign.distance < b.campaign.distance) { return -1; } | |
| if (a.campaign.distance > b.campaign.distance) { return 1; } | |
| return 0; | |
| }); | |
| callbackFunction(report); | |
| */ | |
| function sortReportByDistance(report, currentDistance, currentLat, currentLng, callbackFunction) { | |
| //sort by distance | |
| for ( i in report ) { | |
| if (report[i].campaign == null) { | |
| report[i].campaign = new model.Campaign(); | |
| } | |
| // ระยะห่างระหว่าง lat lng ของ report กับ current lat lng | |
| report[i].campaign.distance = service.distanceCalculate(currentLat, currentLng, report[i].lat, report[i].lng); | |
| // console.log("distance > " + i + " => "+ report[i].place.distance); | |
| } | |
| //ใช้ตัวแปร distance จาก place | |
| report = report.sort(function(a, b) { | |
| if (a.campaign.distance < b.campaign.distance) { return -1; } | |
| if (a.campaign.distance > b.campaign.distance) { return 1; } | |
| return 0; | |
| }); | |
| if (currentDistance == null || currentDistance == undefined) { | |
| console.log("****** SORTED BY LOCATION "); | |
| callbackFunction(report); | |
| return; | |
| } | |
| // ถ้า distance ไม่เป็น null | |
| var reportWithDistance = []; | |
| for (i in report) { | |
| if (report[i].campaign.distance <= currentDistance) { | |
| reportWithDistance.push(report[i]); | |
| } | |
| } | |
| console.log("****** SORTED BY LOCATION & DISTANCE"); | |
| callbackFunction(reportWithDistance); | |
| } | |
| function responseReportsJSONToClient(res, report, limit, offset) { | |
| var resultReports; | |
| if (offset == null || offset < 1) | |
| offset = 1; | |
| var startReport = (offset - 1) * limit; | |
| var endReport = offset * limit; | |
| console.log("::: RANGE SLICE ::: "+ startReport + " - to - " + endReport); | |
| if (report != null && report.length > limit) | |
| resultReports = report.slice(startReport, endReport); | |
| else | |
| resultReports = report; | |
| // res.json(resultReports); | |
| //Response to client | |
| res.writeHead(200, { 'Content-Type' : 'application/json;charset=utf-8'}); | |
| res.write('{ "reports":' + JSON.stringify(resultReports) + '}'); | |
| res.end(); | |
| return; | |
| } | |
| function responseReportsJSONToClient(res, report, limit, offset, startFeedDateTime, startFeedLat, startFeedLng) { | |
| var resultReports; | |
| if (offset == null || offset < 1) | |
| offset = 1; | |
| var startReport = (offset - 1) * limit; | |
| var endReport = offset * limit; | |
| console.log("::: RANGE SLICE ::: "+ startReport + " - to - " + endReport); | |
| if (report != null && report.length > limit) | |
| resultReports = report.slice(startReport, endReport); | |
| else | |
| resultReports = report; | |
| var ans = {}; | |
| ans["reports"] = resultReports; | |
| ans["result"] = | |
| {"offset":offset, | |
| "limit":limit, | |
| "start_feed_date":startFeedDateTime, | |
| "start_feed_lat":startFeedLat, | |
| "start_feed_lng":startFeedLng | |
| }; | |
| //Response to client | |
| // res.json(ans); | |
| res.writeHead(200, { 'Content-Type' : 'application/json;charset=utf-8'}); | |
| res.write(JSON.stringify(ans)); | |
| // res.write(JSON.stringify(ans) + req.query.callback + '(' + JSON.stringify(ans) + ');'); | |
| res.end(); | |
| return; | |
| } | |
| exports.reports_explore = function(req, res) { | |
| console.log('Get report explore list'); | |
| var currentLat = req.query.lat; | |
| var currentLng = req.query.lng; | |
| var currentDistance = req.query.distance; | |
| if (currentLat != null && currentLng != null) { | |
| console.log("get location from request lat:"+ currentLat +" lng:" + currentLng); | |
| } else { | |
| console.log("not get location from request"); | |
| } | |
| console.log(">> current distance : " + currentDistance); | |
| // Default number of report | |
| var maxNumber = 30; | |
| if (req.query.limit != null && !isNaN(req.query.limit)) { | |
| maxNumber = req.query.limit; | |
| } | |
| getAllReports({}, function(report){ | |
| if (report == null) { | |
| console.log(err); | |
| console.log("report is null"); | |
| responseReportsJSONToClient(res, report, maxNumber); | |
| return; | |
| } | |
| //ถ้า USER ไม่ sign in และมี lat lng จะแสดง feed โดยเรียงลำดับตามระยะห่าง เทียบกับ report.lat lng (30อันแรก) | |
| if ( currentLat != null && currentLng != null ) { | |
| console.log("current lat ="+ currentLat+" lng = "+ currentLng); | |
| //sort by distance | |
| sortReportByDistance(report, currentDistance, currentLat, currentLng, function(sortedReport){ | |
| responseReportsJSONToClient(res, sortedReport, maxNumber); | |
| return; | |
| }); | |
| } else { | |
| responseReportsJSONToClient(res, report, maxNumber); | |
| return; | |
| } | |
| }); | |
| } | |
| // Feed | |
| // GET /api/reports >> get list of reports | |
| exports.reports = function(req, res) { | |
| console.log('Get report list'); | |
| console.log('Get user ' + req.user); | |
| var currentLat = req.query.lat; | |
| var currentLng = req.query.lng; | |
| var currentDistance = req.query.distance; | |
| //sort=[recent,subscription,location] | |
| var currentSort = req.query.sort; | |
| console.log("current SORT :: " + currentSort); | |
| if (currentLat != null && currentLng != null) { | |
| console.log("get location from request lat:"+ currentLat +" lng:" + currentLng); | |
| } else { | |
| console.log("not get location from request"); | |
| } | |
| console.log(">> current distance : " + currentDistance); | |
| // Default number of report | |
| var maxNumber = 30; | |
| if (req.query.limit != null && !isNaN(req.query.limit)) { | |
| maxNumber = req.query.limit; | |
| } | |
| // Default offset | |
| // Start index at 1 | |
| var offset = 1; | |
| if (req.query.offset != null && !isNaN(req.query.offset) && req.query.offset > 0) { | |
| offset = req.query.offset; | |
| } | |
| // Last feed request 's date time | |
| var startFeedDateTime; | |
| if (req.query.start_feed_date == null) { | |
| startFeedDateTime = new Date(); | |
| } else { | |
| startFeedDateTime = new Date(unescape(req.query.start_feed_date));//, "yyyy-MM-dd HH:mm:ss") ('2012-12-15 04:58:49 +0000'); | |
| } | |
| console.log('Start feed date time +++++++' + req.query.start_feed_date + '------' + startFeedDateTime); | |
| // Last feed request 's location | |
| var startFeedLat = req.query.start_feed_lat; | |
| var startFeedLng = req.query.start_feed_lng; | |
| var currentUsername = ''; | |
| var currentPassword = ''; | |
| var currentAccountType = 0; | |
| console.log("get req.user :: " + req.user); | |
| if (req.user != undefined && req.user != null) { | |
| currentUsername = req.user.username; | |
| currentPassword = req.user.password; | |
| currentAccountType = req.user.account_type; | |
| }; | |
| console.log(currentUsername + ",,," + currentPassword + ",,," + currentAccountType); | |
| // ------------------------------------- Sort By Recent || Location --------------------------------------------- | |
| if (currentSort == 'recent' || currentSort == 'location') { | |
| if (currentSort == 'recent' && startFeedDateTime != null) { // if startFeedDateTime != null | |
| // แสดงเฉพาะตัวที่ โดนแก้ไข ก่อนหน้าค่าที่ส่งมา | |
| getAllReports({last_modified: { $lte: startFeedDateTime }}, function(report){ | |
| if (report == null) { | |
| console.log("report is null with error :: " + err); | |
| responseReportsJSONToClient(res, report, maxNumber, offset, startFeedDateTime, startFeedLat, startFeedLng); | |
| return; | |
| } | |
| console.log("****** SORTED BY RECENT"); | |
| responseReportsJSONToClient(res, report, maxNumber, offset, startFeedDateTime, startFeedLat, startFeedLng); | |
| return; | |
| }); | |
| } | |
| else if (currentSort == 'location' && startFeedLat != null && startFeedLng != null) { | |
| getAllReports({}, function(report){ | |
| if (report == null) { | |
| console.log("report is null with error :: " + err); | |
| responseReportsJSONToClient(res, report, maxNumber, offset, startFeedDateTime, startFeedLat, startFeedLng); | |
| return; | |
| } | |
| if (currentSort == 'location' && startFeedLat != null && startFeedLng != null ) { | |
| console.log("start lat ="+ startFeedLat+" lng = "+ startFeedLng); | |
| //sort by distance (Location) | |
| sortReportByDistance(report, currentDistance, startFeedLat, startFeedLng, function(sortedReport){ | |
| responseReportsJSONToClient(res, sortedReport, maxNumber, offset, startFeedDateTime, startFeedLat, startFeedLng); | |
| return; | |
| }); | |
| } | |
| else { // if sort by location but not receive lat / lng | |
| console.log("****** EMPTY REPORT"); | |
| var emptyReport = []; | |
| responseReportsJSONToClient(res, emptyReport, maxNumber, offset, startFeedDateTime, startFeedLat, startFeedLng); | |
| return; | |
| } | |
| }); | |
| } | |
| else { | |
| getAllReports({}, function(report){ | |
| if (report == null) { | |
| console.log("report is null with error :: " + err); | |
| responseReportsJSONToClient(res, report, maxNumber, offset, startFeedDateTime, startFeedLat, startFeedLng); | |
| return; | |
| } | |
| if (currentSort == 'recent') { | |
| console.log("****** SORTED BY RECENT"); | |
| responseReportsJSONToClient(res, report, maxNumber, offset, startFeedDateTime, startFeedLat, startFeedLng); | |
| return; | |
| } | |
| else if (currentSort == 'location' && currentLat != null && currentLng != null ) { | |
| console.log("current lat ="+ currentLat+" lng = "+ currentLng); | |
| //sort by distance (Location) | |
| sortReportByDistance(report, currentDistance, currentLat, currentLng, function(sortedReport){ | |
| responseReportsJSONToClient(res, sortedReport, maxNumber, offset, startFeedDateTime, startFeedLat, startFeedLng); | |
| return; | |
| }); | |
| } | |
| else { // if sort by location but not receive lat / lng | |
| console.log("****** EMPTY REPORT"); | |
| var emptyReport = []; | |
| responseReportsJSONToClient(res, emptyReport, maxNumber, offset, startFeedDateTime, startFeedLat, startFeedLng); | |
| return; | |
| } | |
| }); | |
| } | |
| return; | |
| } | |
| // ------------------------------------- Sort By Subscription ---------------------------------------------------- | |
| model.User.findOne( { username: currentUsername , password: currentPassword , account_type: currentAccountType } , function(err,currentUser) { | |
| if (err ) { | |
| console.log("Can not find username:"+ currentUsername+" with error:"+ err); | |
| console.log("****** EMPTY REPORT"); | |
| var emptyReport = []; | |
| responseReportsJSONToClient(res, emptyReport, maxNumber, offset, startFeedDateTime, startFeedLat, startFeedLng); | |
| return; | |
| } | |
| //ถ้า USER sign in และ subscription ไม่เป็น null จะแสดง feed โดยเรียงลำดับตามเวลาที่แก้ไขล่าสุด และ แสดงเฉพาะสถานที่(place) ที่ถูก subscribe เท่านั้น | |
| else if ( currentUser != null && isSignInWithUser(currentUser) == true ) { | |
| console.log("logged in with user "+ currentUser); | |
| model.SubscriptionCampaign.find({user: currentUser}, function(err,subscribes) { | |
| if (err || subscribes == null || subscribes.length < 1) { | |
| console.log("Can not find subscription with error "+ err); | |
| // ถ้า User sign in แล้ว แต่ไม่ได้ subscribe ใครเลย จะส่ง array ว่างๆไป | |
| console.log("****** EMPTY REPORT"); | |
| var emptyReport = []; | |
| responseReportsJSONToClient(res, emptyReport, maxNumber, offset, startFeedDateTime, startFeedLat, startFeedLng); | |
| return; | |
| } else { //have subscription | |
| console.log("Can find subscription"); | |
| // ถ้า User sign in แล้ว มี subscribe จะแสดงตาม feed ที่ subscribed | |
| // create query where subscribe.user._id = "user._id" | |
| var query = {}; | |
| query["$or"] = []; | |
| query["$or"].push({"user":currentUser._id}); //check report.user is current user feed | |
| for (i in subscribes) { | |
| //console.log(i + " subscribes >> "+ subscribes[i]); | |
| if (subscribes[i].campaign != null && subscribes[i].campaign != undefined) { | |
| query["$or"].push({"campaign":subscribes[i].campaign}); //check report.campaign is in subscribe | |
| } | |
| } | |
| console.log("query[$or] subscribe is => "+ JSON.stringify(query["$or"]) + "query ===== " + JSON.stringify(query)); | |
| var qq = {}; | |
| if(query["$or"].length != 0) { | |
| qq = query; | |
| } | |
| if (startFeedDateTime != null) { | |
| var allQuery = {}; | |
| allQuery["$and"] = []; | |
| allQuery["$and"].push(qq); | |
| allQuery["$and"].push({"last_modified": { $lte: startFeedDateTime }}); | |
| console.log("last query text ===> " + JSON.stringify(allQuery)); | |
| //find only subscribed report | |
| getAllReports(allQuery, function(report){ | |
| if (err) { | |
| console.log("can not find report with error "+err); | |
| } | |
| console.log("****** SORTED BY SUBSCRIPTION"); | |
| responseReportsJSONToClient(res, report, maxNumber, offset, startFeedDateTime, startFeedLat, startFeedLng); | |
| return; | |
| }); | |
| } | |
| else { | |
| console.log("last query text ===> " + JSON.stringify(qq)); | |
| //find only subscribed report | |
| getAllReports(qq, function(report){ | |
| if (err) { | |
| console.log("can not find report with error "+err); | |
| } | |
| console.log("****** SORTED BY SUBSCRIPTION"); | |
| responseReportsJSONToClient(res, report, maxNumber, offset, startFeedDateTime, startFeedLat, startFeedLng); | |
| return; | |
| }); | |
| } | |
| } | |
| }); | |
| } | |
| // เลือก sort by subscribe แต่ว่าหา user ไม่เจอ | |
| else if (err || currentUser == null || currentUser == undefined || isSignInWithUser(currentUser) == false ) { | |
| console.log("Not signed in user >> Can not find user at /api/reports"); | |
| console.log("****** EMPTY REPORT"); | |
| var emptyReport = []; | |
| responseReportsJSONToClient(res, emptyReport, maxNumber, offset, startFeedDateTime, startFeedLat, startFeedLng); | |
| return; | |
| } | |
| }); | |
| }; | |
| // GET /api/report/{id} >> get one report from id | |
| exports.report = function(req, res) { | |
| var url = req.url; | |
| var currentID = url.match( /[^\/]+\/?$/ ); | |
| var urlparts= currentID.toString().split('?'); | |
| if (urlparts.length>=2) { | |
| currentID = urlparts[0]; | |
| } | |
| console.log('get report ID: ' + currentID); | |
| // Query all report with all attribute | |
| // create custom json because relation database that | |
| // report can get comment, but comment can get only _id | |
| // so we query user in comment and make a new json | |
| // Query all report with all attribute | |
| // return have 3, none of report, report with comment, report without comment | |
| var new_report = []; | |
| var queryCount = 0; | |
| var maxQueryCount = 0; | |
| model.Report.findOne({_id:currentID}) | |
| .populate('user','username email thumbnail_image display_name account_type created_at last_modified') | |
| .populate('categories','title') | |
| .populate('comments') | |
| .populate('imins') | |
| .populate('place') | |
| .populate('campaign') | |
| .exec(function (err, report) { | |
| if (err) { | |
| console.log(err); | |
| return; | |
| } | |
| // have none of report | |
| if (report == null || report.length == 0) { | |
| if (!req.query.callback) { | |
| res.writeHead(200, { 'Content-Type' : 'application/json;charset=utf-8'}); | |
| res.write('{ "reports":' + JSON.stringify(report) + '}'); | |
| res.end(); | |
| } else { | |
| // jsonp callback | |
| res.json({reports:new_report}); | |
| } | |
| return; | |
| }; | |
| // find max comment, imin | |
| // find need to do before query | |
| for (i in report.comments) { | |
| if (report.comments[i]._id != null && report.comments.length > 0) { | |
| if (i == 0) { | |
| maxQueryCount++; | |
| } | |
| } | |
| } | |
| for (i in report.imins) { | |
| if (report.imins[i]._id != null && report.imins.length > 0) { | |
| if (i == 0) { | |
| maxQueryCount++; | |
| }; | |
| }; | |
| } | |
| // add query comment where _id:id or _id:id .... | |
| var query_comments = {}; | |
| query_comments["$or"] = []; | |
| for (i in report.comments) { | |
| if (report.comments[i]._id != null && report.comments.length > 0) { | |
| query_comments["$or"].push({"_id":report.comments[i]._id}); | |
| } | |
| } | |
| // add query imins where _id:id or _id:id .... | |
| // get all list | |
| queryListComment(query_comments, 0, function(comments, index, isQueryComment) { | |
| if (isQueryComment) { | |
| queryCount++; | |
| } | |
| var query_imins = {}; | |
| query_imins["$or"] = []; | |
| for (i in report.imins) { | |
| if (report.imins[i]._id != null && report.imins.length > 0) { | |
| query_imins["$or"].push({"_id":report.imins[i]._id}); | |
| } | |
| } | |
| // get all comment | |
| queryListImin(query_imins, 0, function(imins, index, isQueryImins) { | |
| // add data to report | |
| new_report.push( | |
| {"user":report.user, | |
| "_id":report._id, | |
| "comments":comments, | |
| "title":report.title, | |
| "lat":report.lat, | |
| "lng":report.lng, | |
| "address":report.address, | |
| "note":report.note, | |
| "full_image":report.full_image, | |
| "thumbnail_image":report.thumbnail_image, | |
| "is_shared_to_facebook":report.is_shared_to_facebook, | |
| "is_resolved":report.is_resolved, | |
| "categories":report.categories, | |
| "campaign":report.campaign, | |
| "place":report.place, | |
| "imins":imins, | |
| "imin_count":report.imin_count, | |
| "last_modified":report.last_modified, | |
| "created_at":report.created_at | |
| }); | |
| if (isQueryImins) { | |
| queryCount++; | |
| } | |
| // have comment in report | |
| if (maxQueryCount == queryCount && maxQueryCount != 0) { | |
| if (!req.query.callback) { | |
| res.writeHead(200, { 'Content-Type' : 'application/json;charset=utf-8'}); | |
| res.write('{ "reports":' + JSON.stringify(new_report) + '}'); | |
| res.end(); | |
| } else { | |
| // jsonp callback | |
| res.json({reports:new_report}); | |
| } | |
| } | |
| }); | |
| }); | |
| // none of comment in report | |
| if (maxQueryCount == 0) { | |
| if (!req.query.callback) { | |
| res.writeHead(200, { 'Content-Type' : 'application/json;charset=utf-8'}); | |
| res.write('{ "reports":' + JSON.stringify(new_report) + '}'); | |
| res.end(); | |
| } else { | |
| // jsonp callback | |
| res.json({reports:new_report}); | |
| } | |
| }; | |
| }); | |
| }; | |
| exports.report_post = function(req, res) { | |
| var fs = require('fs'); | |
| // create directory | |
| var path = require('path'); | |
| // functon create directory | |
| fs.mkdirParent = function(dirPath, mode, callback) { | |
| //Call the standard fs.mkdir | |
| fs.mkdir(dirPath, mode, function(error) { | |
| //When it fail in this way, do the custom steps | |
| if (error && error.errno === 34) { | |
| //Create all the parents recursively | |
| fs.mkdirParent(path.dirname(dirPath), mode, callback); | |
| //And then the directory | |
| fs.mkdirParent(dirPath, mode, callback); | |
| } | |
| //Manually run the callback since we used our own callback to do all these | |
| callback && callback(error); | |
| }); | |
| }; | |
| // save data to db | |
| var report = new model.Report(); | |
| var full_image_type = req.files.full_image.type.split("/"); | |
| var thumbnail_image_type = full_image_type; | |
| /* | |
| console.log("unicode of received title = "); | |
| for (i in req.body.title) { | |
| console.log(i + ">> "+ req.body.title.charCodeAt(i)); | |
| } | |
| */ | |
| report.title = req.body.title; | |
| report.lat = req.body.lat; | |
| report.lng = req.body.lng; | |
| report.note = req.body.note; | |
| report.address = req.body.address; | |
| if (req.body.is_shared_to_facebook == null || req.body.is_shared_to_facebook == false) { | |
| report.is_shared_to_facebook = false; | |
| } else { | |
| report.is_shared_to_facebook = true; | |
| } | |
| console.log('....,,,.....' + report.is_shared_to_facebook); | |
| report.is_resolved = false; | |
| report.imin_count = 0; | |
| report.last_modified = new Date(); | |
| report.created_at = new Date(); | |
| if (req.body.campaign_id != null && req.body.campaign_id != '(null)') { | |
| console.log('req.body.campaign_id ' + req.body.campaign_id); | |
| report.campaign = req.body.campaign_id; | |
| } | |
| if (req.files.full_image != null && full_image_type[0] == 'image' && full_image_type[1] != 'gif') { | |
| var full_image_extension = req.files.full_image.type.match( /[^\/]+\/?$/ ); | |
| var full_image_short_path = "/images/report/" + report._id + "." + full_image_extension; | |
| report.full_image = full_image_short_path; | |
| var thumbnail_image_short_path = "/images/report/" + report._id + "_thumbnail." + full_image_extension; | |
| report.thumbnail_image = thumbnail_image_short_path; | |
| }; | |
| //Find User from username | |
| model.User.findOne({username: req.user.username, account_type: req.user.account_type }, function(err,user) { | |
| if (user == null) { | |
| // if can not find user > then delete temp upload file | |
| var tmp_path = req.files.full_image.path; | |
| fs.unlink(tmp_path, function() { | |
| console.log('Delete temporary file'); | |
| }); | |
| res.writeHead(500, { 'Content-Type' : 'application/json;charset=utf-8'}); | |
| res.end(); | |
| return; | |
| }; | |
| // Set user to Report | |
| report.user = user._id; | |
| //Find Category from request | |
| var query = {}; | |
| query["$or"]=[]; | |
| for (cat in req.body.categories) { | |
| query["$or"].push({"title":req.body.categories[cat]}); | |
| } | |
| // convert format text to readable text | |
| var x = req.body.categories; | |
| var r = /\\u([\d\w]{4})/gi; | |
| x = x.replace(r, function (match, grp) { | |
| return String.fromCharCode(parseInt(grp, 16)); } ); | |
| x = x.split('"'); | |
| //Category can not add from client | |
| model.Category.find({title: x[1]}, function(err,catTitleFromClient) { | |
| if (!err && catTitleFromClient != null) { | |
| for (i in catTitleFromClient ) { | |
| // Push category to Report's category list | |
| report.categories.push(catTitleFromClient[i]._id); | |
| console.log('categories' + catTitleFromClient); | |
| } | |
| } else { | |
| console.log('err' + err); | |
| } | |
| // ********************************* SAVE report to server ******************************** | |
| report.save(function (err) { | |
| if (!err){ | |
| console.log('Success! with ' + report); | |
| res.writeHead(200, { 'Content-Type' : 'application/json;charset=utf-8', 'Text' : 'posted'}); | |
| res.end(); | |
| // ---------------------- Send full image & thumbnail image to amazon s3 ---------------------- | |
| if (req.files.full_image != null && full_image_type[0] == 'image' && full_image_type[1] != 'gif') { | |
| // get the temporary location of the file : ./uploads | |
| var tmp_path = req.files.full_image.path; | |
| var full_image_path = './public' + full_image_short_path; | |
| // Put full image to amazon s3 | |
| client.putFile(tmp_path, full_image_short_path, { 'x-amz-acl': 'public-read' }, function(err){ | |
| if (err) { | |
| console.log('Can not upload file from '+tmp_path+' to '+full_image_short_path+' (amazon S3) with error : ' + err); | |
| // move the file from the temporary location to fail folder | |
| fs.rename(tmp_path, full_image_path, function(err) { | |
| if (err) { | |
| console.log('Can not move file from '+tmp_path+' to '+full_image_path+' with error : ' + err); | |
| return; | |
| } | |
| }); | |
| return; | |
| } | |
| console.log('Full Image uploaded to S3: ' + full_image_short_path + ' - ' + req.files.full_image.size + ' bytes'); | |
| // ---------------------------------------- RESIZE Thumbnail Image ---------------------------------------------- | |
| // resize full image | |
| var fixedWidth = 532; | |
| var thumbnail_image_path = './public' + thumbnail_image_short_path; | |
| // resize image to 532x532 pixel | |
| im.resize({ | |
| srcData: fs.readFileSync(tmp_path, 'binary'), | |
| width: fixedWidth | |
| }, function(err, stdout, stderr){ | |
| if (err) { | |
| console.log('Can not resize file '+tmp_path+' to '+thumbnail_image_path+' with error : ' + err); | |
| throw err; | |
| } else { | |
| fs.writeFileSync(thumbnail_image_path, stdout, 'binary'); | |
| console.log('resized ' + tmp_path + ' to fit within 532 x 532 px >> THUMBNAIL SOURCE = '+ thumbnail_image_path); | |
| client.putFile(thumbnail_image_path, thumbnail_image_short_path, { 'x-amz-acl': 'public-read' }, function(err){ | |
| if (err) { | |
| console.log('Can not upload file from '+thumbnail_image_path+' to '+thumbnail_image_short_path+' (amazon S3) with error : ' + err); | |
| throw err; | |
| } | |
| console.log('Thumbnail Image uploaded to S3: ' + thumbnail_image_short_path ); | |
| // delete thumbnail tmp file | |
| fs.unlink(thumbnail_image_path, function() { | |
| if (err) | |
| throw err; | |
| }); | |
| }); | |
| } | |
| // delete tmp file | |
| fs.unlink(tmp_path, function() { | |
| if (err) | |
| console.log('can not remove file at '+tmp_path); | |
| }); | |
| }); | |
| }); | |
| } else { | |
| var tmp_path = req.files.full_image.path; | |
| fs.unlink(tmp_path, function() { | |
| console.log('Delete temporary file'); | |
| }); | |
| } | |
| } else { // if can not save report to server | |
| console.log('Error !'+ err); | |
| res.writeHead(500, { 'Content-Type' : 'application/json;charset=utf-8'}); | |
| res.end(); | |
| } | |
| }); | |
| }); | |
| /* | |
| // make directory | |
| fs.mkdirParent("./public/images/report/"); | |
| //save picture to /public/images/report/:id | |
| if (req.files.full_image != null && full_image_type[0] == 'image' && full_image_type[1] != 'gif') { | |
| // get the temporary location of the file : ./uploads | |
| var tmp_path = req.files.full_image.path; | |
| // set where the file should actually exists - in this case it is in the "images" directory | |
| var full_image_path = './public' + full_image_short_path; | |
| // move the file from the temporary location to the intended location | |
| fs.rename(tmp_path, full_image_path, function(err) { | |
| if (err) throw err; | |
| // delete the temporary file, so that the explicitly set temporary upload dir does not get filled with unwanted files | |
| fs.unlink(tmp_path, function() { | |
| if (err) throw err; | |
| console.log('File uploaded to: ' + full_image_path + ' - ' + req.files.full_image.size + ' bytes'); | |
| // ---------------------------------------- RESIZE Thumbnail Image ---------------------------------------------- | |
| // set where the file should actually exists - in this case it is in the "images" directory | |
| var thumbnail_image_path = './public' + thumbnail_image_short_path; | |
| // resize full image | |
| var fixedWidth = 532; | |
| // resize image to 532x532 pixel | |
| im.resize({ | |
| srcData: fs.readFileSync(full_image_path, 'binary'), | |
| width: fixedWidth | |
| }, function(err, stdout, stderr){ | |
| if (err) | |
| throw err; | |
| fs.writeFileSync(thumbnail_image_path, stdout, 'binary'); | |
| console.log('resized ' + full_image_path + ' to fit within 532 x 532 px >> THUMBNAIL SOURCE = '+ thumbnail_image_path); | |
| }); | |
| }); | |
| }); | |
| } else { | |
| var tmp_path = req.files.full_image.path; | |
| fs.unlink(tmp_path, function() { | |
| console.log('Delete temporary file'); | |
| }); | |
| } | |
| */ | |
| }); | |
| }; | |
| function queryListComment(query, r, callbackFunction) { | |
| if (query['$or'].length <= 0) { | |
| var emptyQuery = []; | |
| callbackFunction(emptyQuery, r, false); | |
| return; | |
| } | |
| model.Comment.find(query) | |
| .populate('user','username email thumbnail_image display_name account_type created_at last_modified') | |
| .exec(function (err, comments) { | |
| if (err) { | |
| console.log('query comment ' + err); | |
| return; | |
| } | |
| if (comments != null && comments.length > 0) { | |
| callbackFunction(comments, r, true); | |
| } | |
| return; | |
| }); | |
| } | |
| function queryListImin(query, r, callbackFunction) { | |
| if (query['$or'].length <= 0) { | |
| var emptyQuery = []; | |
| callbackFunction(emptyQuery, r, false); | |
| return; | |
| } | |
| model.Imin.find(query) | |
| .populate('user','username email thumbnail_image display_name account_type created_at last_modified') | |
| .exec(function (err, imins) { | |
| if (err) { | |
| console.log('query imin' + err); | |
| return; | |
| } | |
| if (imins != null && imins.length > 0) { | |
| callbackFunction(imins, r, true); | |
| } | |
| return; | |
| }); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment