Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

A lot of changes

  • Loading branch information...
commit 2e85d9807c88e87fcfcd9f47cb4834f523790977 1 parent 94568b8
@toantran authored
Showing with 2,110 additions and 1,167 deletions.
  1. +187 −0 coffee/controllers/profile.coffee
  2. +25 −10 coffee/controllers/team.coffee
  3. +14 −4 coffee/public/js/app.coffee
  4. +1 −20 coffee/public/js/home.coffee
  5. +104 −10 coffee/public/js/profile.coffee
  6. +1 −88 coffee/public/js/team.coffee
  7. +12 −0 coffee/public/js/todoinvite.coffee
  8. +18 −0 coffee/public/js/todoteam.coffee
  9. +11 −0 coffee/services/match.coffee
  10. +247 −0 coffee/services/post.coffee
  11. +1 −12 coffee/services/team.coffee
  12. +134 −5 coffee/services/user.coffee
  13. +12 −27 coffee/services/utils.coffee
  14. +2 −1  controllers/player.js
  15. +207 −751 controllers/profile.js
  16. +28 −7 controllers/team.js
  17. BIN  public/images/profiles/4f2ff1e2f71781c399000001.jpg
  18. BIN  public/images/profiles/4f2ff57bf71781c399000008.jpg
  19. BIN  public/images/profiles/4f2ff9fff71781c399000009.jpg
  20. BIN  public/images/profiles/4f30686593b96a2e9b000002.jpg
  21. BIN  public/images/profiles/4f313d881e052301a7000002.jpg
  22. BIN  public/images/profiles/4f3180084829a50da9000009.jpg
  23. BIN  public/images/profiles/4f3195024829a50da9000015.jpg
  24. BIN  public/images/profiles/4f3551ea31d4bf5ae7000002.jpg
  25. BIN  public/images/profiles/4f3562ad31d4bf5ae700000f.jpg
  26. BIN  public/images/profiles/4f35639231d4bf5ae7000012.jpg
  27. BIN  public/images/profiles/4f35690031d4bf5ae7000019.jpg
  28. BIN  public/images/profiles/4f358f4f31d4bf5ae7000030.jpg
  29. BIN  public/images/profiles/4f4fd6144a0245cb1f000025.jpg
  30. BIN  public/images/profiles/4f4fe41b4a0245cb1f00002b.jpg
  31. BIN  public/images/profiles/4f56c220dae789c518000001.png
  32. 0  public/images/profiles/df566c882b017a3aabad5534604a73d5
  33. +15 −3 public/js/app.js
  34. +0 −19 public/js/home.js
  35. +118 −10 public/js/profile.js
  36. +0 −86 public/js/team.js
  37. +19 −0 public/js/todoinvite.js
  38. +24 −0 public/js/todoteam.js
  39. +274 −0 public/lib/jquery.autoresize.js
  40. +5 −5 public/stylesheets/profile.less
  41. +12 −0 services/match.js
  42. +266 −0 services/post.js
  43. +1 −12 services/team.js
  44. +191 −6 services/user.js
  45. +9 −34 services/utils.js
  46. +3 −4 views/layout.jade
  47. +4 −0 views/post/challengecancelled.jade
  48. +5 −0 views/post/challengedeclined.jade
  49. +4 −0 views/post/challengedeclining.jade
  50. +5 −0 views/post/challengeremoved.jade
  51. +5 −0 views/post/invite.jade
  52. +3 −0  views/post/jointeam.jade
  53. +10 −0 views/post/matchresult.jade
  54. +5 −0 views/post/newmatch.jade
  55. +3 −0  views/post/newteam.jade
  56. +3 −0  views/post/post.jade
  57. +4 −0 views/post/recruit.jade
  58. +13 −0 views/post/teamchallenged.jade
  59. +13 −0 views/post/teamchallenging.jade
  60. +3 −0  views/post/teamjoin.jade
  61. +18 −5 views/profile/challenge.jade
  62. +7 −3 views/profile/invite.jade
  63. +11 −6 views/profile/post.jade
  64. +23 −6 views/profile/show.jade
  65. +30 −33 views/profile/todoteam.jade
View
187 coffee/controllers/profile.coffee
@@ -0,0 +1,187 @@
+userSvc = require '../services/user'
+
+
+###
+ POST
+ URL /profile/:id/removecomment
+###
+exports.removecomment = (req, res, next) ->
+ userid = req.params.id
+ postid = req.param 'postid', ''
+ commentid = req.param 'commentid', ''
+
+ return res.send() if not userid
+
+ try
+ userSvc.removeComment userid, postid, commentid, (error, comment) ->
+ result = success: true
+
+ if error
+ result.success = false
+ result.error = error
+ else
+ result.comment = comment
+
+ res.send result
+ catch e
+ console.trace e
+ req.flash 'error', e
+ next e
+exports.removecomment.authenticated = true
+exports.removecomment.methods = ['POST']
+exports.removecomment.action = ':id/removecomment'
+
+
+###
+ POST
+ URL /profile/:id/addcomment
+###
+exports.addcomment = (req, res, next) ->
+ userid = req.params.id
+ postid = req.param 'postid', ''
+ posterid = req.param 'posterid', ''
+ msg = req.param 'msg', ''
+ comment = posterid: posterid, msg: msg
+
+ try
+ userSvc.addComment userid, postid, comment, (error, addedcomment) ->
+ result = success: true
+
+ if error
+ result.success = false
+ result.error = error
+ res.send result
+ else
+ postSvc = require '../services/post'
+
+ try
+ postSvc.loadComment comment, (error, fullComment) ->
+ if error
+ result.comment = comment
+ else
+ result.comment = fullComment
+ res.send result
+ catch e
+ console.trace e
+ req.flash 'error', e
+ next()
+ catch e
+ console.trace e
+ req.flash 'error', e
+ next e
+exports.addcomment.authenticated = true
+exports.addcomment.methods = ['POST']
+exports.addcomment.action = ':id/addcomment'
+
+
+###
+ POST
+ URL /profile/:id/removepost
+###
+exports.removePost = (req, res, next) ->
+ userid = req.params.id
+ postid = req.param 'postid', ''
+
+ return res.send() if not userid
+
+ try
+ userSvc.removePost userid, postid, (error, post) ->
+ result = success: true
+
+ if error
+ result.success = false
+ result.error = error
+ else
+ result.post = post
+
+ res.send result
+ catch e
+ console.trace e
+ req.flash 'error', e
+ next e
+exports.removePost.authenticated = true
+exports.removePost.methods = ['POST']
+exports.removePost.action = ':id/removepost'
+
+
+###
+ POST
+ URL /profile/:id/addpost
+###
+exports.addPost = (req, res, next) ->
+ userid = req.params.id
+ posterid = req.param 'posterid', ''
+ msg = req.param 'msg', ''
+ post =
+ type: 'post'
+ data:
+ posterid: posterid
+ msg: msg
+ createdat: new Date()
+
+ return res.send() if not userid
+
+ try
+ userSvc.addPost userid, post, (error, fullPost) ->
+ result = success: true
+
+ if error
+ result.success = false
+ result.error = error
+ else
+ postSvc = require '../services/post'
+ postSvc.init()
+ postSvc.makePostGen(req.user) post, (err, fullpost) ->
+ if fullpost?
+ result.post = fullpost
+ else
+ result.post = post
+ res.send result
+ catch e
+ console.trace e
+ req.flash 'error', e
+ next e
+exports.addPost.authenticated = true
+exports.addPost.action = ':id/addpost'
+exports.addPost.methods = ['POST']
+
+###
+ GET
+ URL /profile
+ Redirect to /profile/show with current user id
+###
+exports.index = (req, res, next) ->
+ userId = req?.user?._id ? ''
+
+ # redirect to show with current user id
+ res.redirect '/profile/' + userId
+
+exports.index.methods = ['GET']
+exports.index.authenticated = true
+
+
+###
+ GET
+ URL /profile/show
+###
+exports.show = (req, res, next) ->
+ playerid = req.params?.id
+
+ return next() unless playerid and playerid isnt 'undefined'
+
+
+ try
+ userSvc.getFullUser playerid, (err, fullplayer) ->
+ if err
+ req.flash 'error', err
+ next err
+ else
+ res.render fullplayer,
+ layout: true
+ title: 'WFL - Profile'
+ catch e
+ console.trace e
+ req.flash 'error', e
+ next e
+exports.show.methods = ['GET'];
+exports.show.authenticated = true;
View
35 coffee/controllers/team.coffee
@@ -99,7 +99,7 @@ exports.challengeaccept = (req, res, next) ->
success: false
error: 'Ids empty'
catch e
- console.log e
+ console.trace e
res.send
success: false
error: e
@@ -130,7 +130,7 @@ exports.challengecancel = (req, res) ->
success: false
error: 'Ids empty'
catch e
- console.log e
+ console.trace e
res.send
success: false
error: e
@@ -161,7 +161,7 @@ exports.getChallenge = (req, res, next) ->
success: true
result: result
catch e
- console.log e
+ console.trace e
res.send
success: false
error: e
@@ -178,10 +178,10 @@ exports.getChallenge.methods = ['GET']
exports.index = (req, res, next) ->
availableOnly = req.param 'available', ''
utils = require '../services/utils'
-
+
utils.execute( teamSvc.getAll, availableOnly ) # get all teams
.then (err, teams, cb = ->) ->
- return next() if err?
+ return next( err ) if err
makeMemberMapper = ->
userSvc = require '../services/user'
@@ -191,14 +191,14 @@ exports.index = (req, res, next) ->
makeTeamMapper = ->
(team, teammapcb = ->) ->
return teammapcb() unless team?
- utils.mapAsync team.members, makeMemberMapper(), (err, members) ->
- return teammapcb(err) if err?
+ utils.mapAsync team?.members, makeMemberMapper(), (err, members) ->
+ return teammapcb(err) if err
team.members = members
teammapcb null, team
utils.mapAsync teams, makeTeamMapper(), cb
.then (err, teams, cb = ->) ->
- return next() if err? or not teams?
+ return next(err) if err or not teams?
teams.sort teamSvc.sortingTeams
if (availableOnly)
@@ -256,8 +256,23 @@ exports.create = (req, res, next) ->
req.session.user = @user
res.send
success: true
-exports.create.authenticated = true;
-
+exports.create.authenticated = true
+###
+ GET
+ URL /team/:id
+ Render a team detail page
+###
+exports.show = (req, res, next) ->
+ teamId = req.params.id
+
+ teamSvc.getById teamId, (error, team) ->
+ if error
+ req.flash 'error', error
+ res.render team,
+ layout: true
+ title: 'WFL - Team'
+ user: req.session.user
+exports.show.authenticated = true
View
18 coffee/public/js/app.coffee
@@ -3,9 +3,15 @@ jQuery ($) ->
global = makethis.call()
+
+ ###
+ Publish helper
+ ###
$.publish = (title, body) ->
console.log title, body
-
+ ###
+ Publish helper end
+ ###
###
Template engine
@@ -31,7 +37,6 @@ jQuery ($) ->
selected: 1
setProperty = ( el, key, value ) ->
- console.log key, value
prop = directProperties[ key ]
if prop
el[ prop ] = '' + (value ? '')
@@ -50,7 +55,9 @@ jQuery ($) ->
appendChildren el, node
else
if typeof node is 'string'
- node = doc.createTextNode node
+ spanEl = doc.createElement 'span'
+ spanEl.innerHTML = node
+ node = spanEl
el.appendChild node
@@ -58,7 +65,6 @@ jQuery ($) ->
splitter = /(#|\.)/
create = ( tag, props, children ) ->
- console.log tag, props, children
if props instanceof Array
children = props;
props = null;
@@ -89,3 +95,7 @@ jQuery ($) ->
thisEl
$.el = el()
+
+ ###
+ Template engine end
+ ###
View
21 coffee/public/js/home.coffee
@@ -1,23 +1,4 @@
jQuery ($) ->
$('.carousel').carousel
interval: 5000
- ###
- rendernews = (news) ->
- if news? and Array.isArray(news)
- _(news)
- .map (val) ->
- '<li><span>' + val?.newscontent + '</span></li>'
- .reduce (prev, val) ->
- prev + val
- , ''
-
- $.get('/news')
- .success (data) ->
- if (data? && data.success)
- html = rendernews data.news
- $(html).prependTo('ul.#league-news')
- .show('slow')
-
- $('ul#league-news').liScroll();
- ###
-
+
View
114 coffee/public/js/profile.coffee
@@ -1,10 +1,93 @@
jQuery ($) ->
makethis = -> @
+
+ $('#upload-picture-dlg').modal
+ backdrop: true
+ keyboard: true
+ show: false
+
+ changePictureClick = ->
+ profileid = $(@).attr('data-profileid')
+ $('#upload-picture-dlg').modal 'show'
+ $('#player-picture-change a').on 'click', changePictureClick
+
global = makethis.call()
global.setActiveMenu 5
- $('.new-post button').on 'click', ->
+ $('.post-text').on 'focus', ->
+ $(@).addClass 'active'
+
+ $('.post-text').on 'blur', ->
+ val = $(@).val()
+ if not val
+ $(@).removeClass 'active'
+
+ onpostcloseclick = ->
+ postpnl = $(@).closest('.post-panel')
+ postid = $(postpnl).attr 'data-postid'
+ profileid = $(postpnl).attr 'data-profileid'
+
+ if postid and profileid
+ $.post("/profile/#{profileid}/removepost", postid: postid )
+ .success (data) ->
+ $(postpnl).hide 'slow'
+
+ $('.post-panel > a.post-close-btn').on 'click', onpostcloseclick
+
+ oncommentcloseclick = ->
+ commentpnl = $(@).closest('.comment-panel')
+ postpnl = $(@).closest('.post-panel')
+ commentid = $(commentpnl).attr 'data-commentid'
+ profileid = $(commentpnl).attr 'data-profileid'
+ postid = $(postpnl).attr 'data-postid'
+
+ if commentid and profileid
+ $.post("/profile/#{profileid}/removecomment", {postid: postid, profileid: profileid, commentid: commentid} )
+ .success (data) ->
+ $(commentpnl).hide 'slow'
+
+ $('.comment-panel > a.post-close-btn').on 'click', oncommentcloseclick
+
+ $('textarea').autoResize( extraSpace: 16)
+
+ newcommentclick = ->
+ profileid = $(@).attr('data-profileid')
+ posterid = $(@).attr('data-posterid')
+ postid = $(@).attr('data-postid')
+ input = $(@).closest('.new-comment').find('textarea.post-text')[0]
+ msg = $(input).val()
+
+ if msg # has a comment
+ $.post("/profile/#{profileid}/addcomment", {postid, posterid, msg})
+ .success (data) =>
+ if data?.success
+ comment = data.comment
+
+ el = $.el('div.row.comment-panel', {'data-commentid':comment.id, 'data-profileid':profileid}, [
+ $.el('a.post-close-btn'),
+ $.el('div.span1.poster-picture', {}, [
+ $.el('img', {src:comment.pictureurl}, []) if comment.pictureurl
+ ]),
+ $.el('div.span4.comment-item', {}, [
+ $.el('a', {href: "/profile/#{comment.posterid}"}, [comment.postername]),
+ ' wrote',
+ $.el('p', {}, [comment.msg]),
+ $.el('div.postmark', {}, ["on #{comment.createdat}"])
+ ])
+ ])
+
+ $(@).closest('.new-comment').before(el).show('slow')
+ console.log $(el)
+ $(el).find('a.post-close-btn').on 'click', oncommentcloseclick
+
+ $(input).val('')
+
+
+ $('.new-comment button').on 'click', newcommentclick
+
+
+ newpostclick = ->
profileid = $(@).attr('data-profileid')
userid = $(@).attr('data-userid')
msg = $('#newpost-msg').val()
@@ -15,18 +98,18 @@ jQuery ($) ->
if data?.success
post = data.post
- el = $.el( 'div.row.post-panel', {postid: post.id, profileid: profileid}, [
+ el = $.el( 'div.row.post-panel', {'data-postid': post.id, 'data-profileid': profileid}, [
$.el('a.post-close-btn'),
$.el('div.span1', [$.el('img', {src: post.pictureurl} if post.pictureurl)]),
$.el('div.span5', [
- $.el('div.post-item', , post.desc),
- $.el('div.postmark', ,"on #{post.createdat}"),
+ $.el('div.post-item', null, [post.desc]),
+ $.el('div.postmark', null,["on #{post.createdat}"]),
$.el('div.post-comment-list', [
$.el('div.row.new-comment', [
$.el('div.span5', [
$.el('textarea.post-text', {rows:1, placeholder:'Type your comment...'}),
- $.el('button.btn.btn-mini.btn-primary.pull-right', {postid: post.id, profileid:profileid, posterid:userid}, [
+ $.el('button.btn.btn-mini.btn-primary.pull-right', {'data-postid': post.id, 'data-profileid':profileid, 'data-posterid':userid}, [
$.el('i.icon-comment.icon-white'),
'&nbsp;Post'
])
@@ -37,11 +120,22 @@ jQuery ($) ->
])
el = $(el).prependTo('.post-list').show('slow')
+
+ el.find('textarea').autoResize extraSpace: 16
-# el.find('.post-new-comment textarea')
-# .watermark('Write something...')
-# .elastic();
-# el.find('.post-new-comment button').button();
-# el.find('.post-new-comment button').click(profile.newcommentclick);
+ el.find('.post-text').on 'focus', ->
+ $(@).addClass 'active'
+
+ el.find('.post-text').on 'blur', ->
+ val = $(@).val()
+ if not val
+ $(@).removeClass 'active'
+
+ el.find('.new-comment button').on 'click', newcommentclick
+ el.find('.post-panel > a.post-close-btn').on 'click', onpostcloseclick
+
$('#newpost-msg').val('')
+
+ $('.new-post button').on 'click', newpostclick
+
View
89 coffee/public/js/team.coffee
@@ -54,92 +54,5 @@ jQuery ($) ->
.append '<div class="alert alert-error"><a class="close" data-dismiss="alert">x</a><h4>Error!</h4>' + data.error + '</div>'
$('#team-challenge-sent-dlg a.btn.btn-primary').on 'click', ->
- $.publish 'Challenge', 'Blah blah blah'
-
-###
-var team = {
-
- challengedialog: null
-
- , poplateMemberNames: function() {
- $('.member-list .member-name').each( team.populateMember );
- }
-
-
- , populateMember: function(index, nameEl) {
- var userid = $(nameEl).attr('memberid');
-
- if (userid) {
- $.get('/profile/' + userid + '.json')
- .success( function(data) {
- var html = '<a href="/profile/' + userid + '">' + data.nickname + '</a>';
-
- $(nameEl).empty();
- $(nameEl).append(html);
- });
- }
- }
-
- , challengebtnclick: function(e) {
- var challengerid= $(this).attr('challengerid')
- teamid = $(this).attr('challengeeteamid');
-
- team.challengedialog.ajaxdata = {
- challengerid: challengerid
- , teamid: teamid
- };
-
- team.challengedialog.dialog('open');
- }
-
- , challengeopen: function() {
-
- }
-
- , challengesendclick: function(e) {
- var values = team.challengedialog.ajaxdata
- , form = $('form#team-challenge-form');
-
- $.each(form.serializeArray(), function(i, field) {
- values[field.name] = field.value;
- });
-
- $.post('/team/challenge', values)
- .success( function(data) {
- if (data && data.success) {
- $('<div style="font-size: 20px; color: red;"><img src="/images/challenge2.jpg" width=100px height=100px">Challenge sent!</div>').dialog({
- modal: true
- , title: 'Sent'
- , stack: true
- , close: function() {
- team.challengedialog.dialog('close');
- }
- , buttons: {
- OK: function() {
- $(this).dialog('close');
- }
- }
- });
- } else {
- $('<div>You have already challenged this team.</div>').dialog({
- modal: true
- , title: 'Challenge'
- , stack: true
- , close: function() {
- team.challengedialog.dialog('close');
- }
- , buttons: {
- OK: function() {
- $(this).dialog('close');
- }
- }
- });
- }
- })
- .error( function(res, status) {
- });
- }
-};
-###
-
+ $.publish 'Challenge', 'Blah blah blah'
View
12 coffee/public/js/todoinvite.coffee
@@ -0,0 +1,12 @@
+jQuery ($) ->
+ accceptinviteclick= (e) ->
+ teamid = $(@).attr('data-teamid')
+ userid = $(@).attr('data-userid')
+
+ $.post('/player/acceptinvite', {userid, teamid})
+ .success (data) ->
+ window.location.href = window.location.href
+ .error (res, status) ->
+
+
+ $('.todo-invite a.btn-primary').on 'click', accceptinviteclick
View
18 coffee/public/js/todoteam.coffee
@@ -0,0 +1,18 @@
+jQuery ($) ->
+
+ oncreateteamclick = ->
+ profileid = $(@).attr 'data-profileid'
+ values =
+ profileid: profileid
+ form = $('form#form-teamcreate')
+ $.each form.serializeArray(), (i, field) ->
+ values[field.name] = field.value
+
+ $.post("/team/#{profileid}", values)
+ .success (data) ->
+ $(@).closest('modal').modal 'hide'
+ $('.todo-noteam.alert').hide()
+ window.location.href = window.location.href
+
+
+ $('#todo-noteam-create a.btn.btn-primary').on 'click', oncreateteamclick
View
11 coffee/services/match.coffee
@@ -1,5 +1,16 @@
matchRepo = require('../repository/matches2')
+
+exports.getById = (matchid, callback = ->) ->
+ console.assert matchid, 'matchid cannot be null or 0'
+ throw 'matchid cannot be null or 0' unless matchid
+
+ try
+ matchRepo.getById matchid, callback
+ catch e
+ console.trace e
+ throw e
+
exports.createMatch = (am, callback = ->) ->
console.assert am, 'Match object cannot be null'
throw 'Match object cannot be null' unless am?
View
247 coffee/services/post.coffee
@@ -0,0 +1,247 @@
+teamsvc = require './team'
+usersvc = require './user'
+matchsvc = require './match'
+utils = require './utils'
+jade = require 'jade'
+fs = require 'fs'
+templates = {}
+
+
+bootTemplate = (file) ->
+ path = "#{__dirname}/../views/post/#{file}"
+ name = file.replace '.jade', '' # template name
+ str = fs.readFileSync(path, 'utf8')
+ fn = jade.compile str,
+ filename: path
+ pretty: true
+ templates[name] = fn
+
+
+# Load all post templates from folder view/post
+bootTemplates = () ->
+ fs.readdir "#{__dirname}/../views/post/", (err, files) ->
+ throw err if err
+ bootTemplate file for file in files when file.indexOf('.jade') >= 0
+
+
+bootTemplates()
+
+
+exports.init = ->
+
+
+exports.loadComment = loadComment = (comment, callback = ->) ->
+ usersvc.getById comment?.posterid, (err, user) ->
+ comment?.pictureurl = user?.pictureurl
+ comment?.postername = user?.nickname
+ callback null, comment
+
+
+exports.makePostGen = (user) ->
+ (post, callback = ->) ->
+ return callback(null, post) unless post?
+
+ setPictureUrl = (pictureurl) ->
+ post.pictureurl = pictureurl
+
+ setDesc = (desc) ->
+ post.desc = desc
+
+ returnback = (err) ->
+ if err
+ callback err, post
+ else
+ if post?.comments?.length
+ utils.mapAsync post?.comments, loadComment, (commentErr, comments) ->
+ post?.comments = comments
+ callback commentErr, post
+ else
+ callback null, post
+
+ data =
+ playerid: user?._id
+ playername: user?.nickname
+
+ genDesc = () ->
+ if templates[post?.type]?
+ setDesc templates[post?.type](data)
+
+ switch post.type
+ when 'jointeam'
+ setPictureUrl user.pictureurl
+ teamsvc.getById post?.data?.teamid, (err, team) ->
+ data.teamid = team?._id
+ data.teamname = team?.teamname
+ try
+ genDesc()
+ returnback null
+ catch e
+ console.trace e
+ returnback e
+ when 'invite'
+ utils.execute( usersvc.getById, post?.data?.playerid)
+ .then (err, otherplayer, cb = ->) ->
+ return returnback(err) if err
+
+ setPictureUrl otherplayer?.pictureurl
+
+ data.otherplayerid = otherplayer?._id
+ data.otherplayername = otherplayer?.nickname
+
+ teamsvc.getById post?.data?.teamid, cb
+
+ .then (err, team, cb = ->) ->
+ return returnback(err) if err
+ data.teamid = team?._id
+ data.teamname = team?.teamname
+
+ try
+ genDesc()
+ returnback null
+ catch e
+ console.trace e
+ returnback e
+
+ when 'teamjoin'
+ teamsvc.getById post?.data?.teamid, (err, team) ->
+ return returnback(err) if err
+
+ setPictureUrl team?.pictureurl
+ data.teamid = team?._id
+ data.teamname = team?.teamname
+
+ try
+ genDesc()
+ returnback null
+ catch e
+ console.trace e
+ returnback e
+
+ when 'recruit'
+ setPictureUrl user?.pictureurl
+ usersvc.getById post?.data?.playerid, (err, otherplayer) ->
+ return returnback(err) if err
+
+ data.otherplayerid = otherplayer?._id
+ data.otherplayername = otherplayer?.nickname
+
+ try
+ genDesc()
+ returnback null
+ catch e
+ console.trace e
+ returnback e
+
+ when 'newteam'
+ setPictureUrl user?.pictureurl
+
+ teamsvc.getById post?.data?.teamid, (err, team) ->
+ return returnback(err) if err
+
+ data.teamid = team?._id
+ data.teamname = team?.teamname
+
+ try
+ genDesc()
+ returnback null
+ catch e
+ console.trace e
+ returnback e
+
+ when 'teamchallenging', 'challengedeclined', 'challengedeclining', 'challengecancelled', 'challengeremoved'
+ setPictureUrl user?.pictureurl
+
+ data.matchtype = post?.data?.matchtype
+ data.matchmsg = post?.data?.msg
+
+ teamsvc.getById post?.data?.teamid, (err, team) ->
+ return returnback(err) if err
+
+ data.teamid = team?._id
+ data.teamname = team?.teamname
+
+ try
+ genDesc()
+ returnback null
+ catch e
+ console.trace e
+ returnback e
+
+ when 'teamchallenged'
+ data.matchtype = post?.data?.matchtype
+ data.matchmsg = post?.data?.msg
+
+ teamsvc.getById post?.data?.teamid, (err, team) ->
+ return returnback(err) if err
+
+ setPictureUrl team?.pictureurl
+ data.teamid = team?._id
+ data.teamname = team?.teamname
+
+ try
+ genDesc()
+ returnback null
+ catch e
+ console.trace e
+ returnback e
+
+ when 'newmatch'
+ setPictureUrl '/images/match.jpg'
+
+ matchsvc.getById post.data.matchid, (err, am) ->
+ return returnback(err) if err
+
+ data.teamid = am?.teams[0]?._id
+ data.teamname = am?.teams[0]?.teamname
+ data.otherteamid = am?.teams[1]?._id
+ data.otherteamname = am?.teams[1]?.teamname
+ data.expirationdt = am?.end
+
+ try
+ genDesc()
+ returnback null
+ catch e
+ console.trace e
+ returnback e
+
+ when 'post'
+ data.postbody = post?.data?.msg
+
+ usersvc.getById post?.data?.posterid, (err, poster) ->
+ return returnback(err) if err
+
+ setPictureUrl poster?.pictureurl
+ data.playerid = poster?._id
+ data.playername = poster?.nickname
+
+ try
+ genDesc()
+ returnback null
+ catch e
+ console.trace e
+ returnback e
+
+ when 'matchresult'
+ setPictureUrl user?.pictureurl
+ data.result = post?.data?.result
+
+ teamsvc.getById post?.data?.opponentid, (err, team) ->
+ return returnback(err) if err
+
+ setPictureUrl team?.pictureurl
+ data.teamid = team?._id
+ data.teamname = team?.teamname
+
+ try
+ genDesc()
+ returnback null
+ catch e
+ console.trace e
+ returnback e
+
+ else
+ setPictureUrl user?.pictureurl
+ setDesc 'N/A'
+ returnback null
+
+
View
13 coffee/services/team.coffee
@@ -96,14 +96,12 @@ exports.createTeamChallenge = (params, callback = ->) ->
userSvc = require './user'
{teamid, msg, matchtype} = params
- console.log params
teamid = new newTeamRepo.ObjectId(teamid) if typeof teamid is 'string'
opponentid = null
try
utils.execute( userSvc.getById, params.opponentplayerid ) # get the opponent player obj
.then (err, opponentplayer, cb = ->) =>
- console.log 'get the existing challenge'
# get the existing challenge
return callback(err) if err
params.opponentid = opponentid = opponentplayer.team._id
@@ -114,14 +112,12 @@ exports.createTeamChallenge = (params, callback = ->) ->
console.trace e
throw e
.then (err, challenges, cb = ->) ->
- console.log 'Already challenged', challenges
if challenges? && challenges.length
# already challenged
callback 'Already challenged'
else
cb()
.then (args..., cb = ->) =>
- console.log 'Step 3'
# create challenge for challenged team
challenge =
message: params.msg
@@ -141,14 +137,12 @@ exports.createTeamChallenge = (params, callback = ->) ->
$set:
updatedat: new Date()
- console.log findObj, updateObj
try
newTeamRepo.update findObj, updateObj, {}, cb
catch e
console.trace e
throw e
.then (err, args..., cb = ->) ->
- console.log 'Step 4', err, args
# get challenged team
try
newTeamRepo.getById teamid, cb
@@ -156,7 +150,6 @@ exports.createTeamChallenge = (params, callback = ->) ->
console.trace e
throw e
.then (err, challengedTeam, cb = ->) =>
- console.log 'Step 5', err
# create challenge post for members of challenged team
for memberid in challengedTeam?.members
do (memberid) ->
@@ -172,7 +165,6 @@ exports.createTeamChallenge = (params, callback = ->) ->
throw e
cb()
.then (args..., cb = ->) ->
- console.log 'Step 6'
# create challenge for challenging team
challenge =
message: msg
@@ -197,7 +189,6 @@ exports.createTeamChallenge = (params, callback = ->) ->
console.trace e
throw e
.then (err, args..., cb = ->) ->
- console.log 'Step 7', err
# get challenging team
try
newTeamRepo.getById opponentid, cb
@@ -205,7 +196,6 @@ exports.createTeamChallenge = (params, callback = ->) ->
console.trace e
throw e
.then (err, challengingTeam, cb = ->) ->
- console.log 'Step 8', err
for memberid in challengingTeam?.members
do (memberid) ->
post =
@@ -220,7 +210,6 @@ exports.createTeamChallenge = (params, callback = ->) ->
throw e
cb()
.then ->
- console.log 'Step 9'
callback()
catch e
console.trace e
@@ -515,7 +504,7 @@ exports.getAll = (availableOnly, callback = ->) ->
callback()
catch e
- console.log e
+ console.trace e
throw e
View
139 coffee/services/user.coffee
@@ -1,6 +1,6 @@
crypto = require 'crypto'
newUserRepo = require '../repository/users2'
-teamRepo = require '../repository/teams'
+teamRepo = require '../repository/teams2'
utils = require './utils'
hash = (msg, key) ->
@@ -361,15 +361,54 @@ exports.addComment = (userid, postid, data, callback = ->) ->
try
newUserRepo.getById userid, (getErr, user) ->
return callback( getErr ) if getErr?
- for post in user?.posts
- if post?.id?.equals( postid )
+ for post in user?.posts when post?.id?.equals( postid )
+ do (post) ->
post.comments or= []
- post.comments.push data
- newUserRepo.save user, callback
+ post.comments.push data
+ updateObj =
+ $set:
+ posts: user?.posts
+ updatedat: new Date()
+ newUserRepo.update findObj, updateObj, {}, callback
catch e
console.trace e
callback e
+
+
+###
+Remove a comment
+###
+exports.removeComment = (userid, postid, commentid, callback = ->) ->
+ console.assert userid, 'userid cannot be null or 0'
+ throw 'userid is null or empty' unless userid?
+ console.assert postid, 'postid cannot be null or 0'
+ throw 'postid is null or empty' unless postid?
+ console.assert commentid, 'commentid cannot be null or 0'
+ throw 'commentid is null or empty' unless commentid?
+
+ userid = new newUserRepo.ObjectId( userid ) if typeof userid is 'string'
+ postid = new newUserRepo.ObjectId( postid ) if typeof postid is 'string'
+ commentid = new newUserRepo.ObjectId( commentid ) if typeof commentid is 'string'
+
+ findObj = _id : userid
+ try
+ newUserRepo.getById userid, (getErr, user) ->
+ return callback( getErr ) if getErr?
+ for post in user?.posts when post?.id?.equals( postid )
+ do (post) ->
+ for comment, index in post?.comments
+ do (comment, index) ->
+ if comment?.id?.equals(commentid)
+ post?.comments.splice index, 1
+ updateObj =
+ $set:
+ posts: user?.posts
+ updatedat: new Date()
+ newUserRepo.update findObj, updateObj, {}, callback
+ catch e
+ console.trace e
+ callback e
###
Add a vote record into player's record
@@ -550,7 +589,97 @@ exports.assignTeam = (userid, team, callback = ->) ->
console.trace e
callback e
+
+
+###
+take in a brief invite obj and return a full Invite object
+###
+loadFullInvite = (invite, callback = ->) ->
+ teamid = invite?.teamid
+ userid = invite?.invitor
+
+ try
+ utils.execute( teamRepo.getById, teamid )
+ .then (err, team, cb = ->) ->
+ invite.team = team
+
+ try
+ newUserRepo.getById userid, cb
+ catch e
+ console.trace e
+ callback e
+ .then (err, user, cb = ->) ->
+ invite.invitor = user
+ callback null, invite
+ catch e
+ console.trace e
+ callback e
+
+###
+GET user object with all full properties
+###
+exports.getFullUser = (userid, callback = ->) ->
+ console.assert userid, 'userid cannot be null or 0'
+ throw 'userid cannot be null or 0' unless userid
+
+ utils.execute( newUserRepo.getById, userid ) # load user
+ .then (err, @user, cb = ->) =>
+ # load team
+ return callback( err ) if err
+
+ if @user?.team?
+ try
+ teamRepo.getById @user?.team?._id, cb
+ catch e
+ console.trace e
+ cb e
+ else
+ cb()
+ .then (err, @team, cb = ->) =>
+ # Load posts
+ return callback( err ) if err
+ @user?.team = @team
+
+ if @user?.posts? and @user?.posts?.length
+ try
+ postGen = require './post'
+ postGen.init()
+ utils.mapAsync @user?.posts, postGen.makePostGen(@user), cb
+ catch e
+ console.trace e
+ cb e
+ else
+ cb null, null
+
+ .then (err, fullposts, cb = ->) =>
+
+ if fullposts?
+ posts = (post for post in fullposts when post?.desc?)
+ else
+ posts = fullposts
+
+ if posts?
+ posts.sort (p1, p2) ->
+ p2?.createdat - p1?.createdat
+
+ @user?.posts = posts
+ # Load invites
+ try
+ if @user?.invites and @user?.invites?.length
+ utils.mapAsync @user?.invites, loadFullInvite, cb
+ else
+ cb()
+ catch e
+ console.trace e
+ cb e
+ .then (err, invites, cb = ->) =>
+ return callback( err ) if err
+ @user?.invites = invites
+
+ callback null, @user
+
+
View
39 coffee/services/utils.coffee
@@ -1,35 +1,22 @@
-
-exports.map = (array = [], asyncMapFn, callback = ->) ->
- counter = array.length
- new_array = []
- runit = (item, index) ->
- asyncMapFn item, (err, result) ->
- if err
- callback err
- else
- new_array[index] = result
- counter--
- if counter is 0
- callback null, new_array
-
- runit item, index for item, index in array
-
-
-exports.mapAsync = (array = [], asyncMapFn, callback = ->) ->
+_mapAsync = (array = [], asyncMapFn, callback = ->) ->
counter = array.length
new_array = []
+ errors = []
runit = (item, index) ->
asyncMapFn item, (err, result) ->
if err
- callback err
- else
- new_array[index] = result
- counter--
- if counter is 0
- callback null, new_array
+ errors.push err
+
+ new_array[index] = result
+ counter--
+ if counter is 0
+ callback errors.join(','), new_array
runit item, index for item, index in array
-
+
+
+exports.map = exports.mapAsync = _mapAsync
+
exports.parallel = ( fnArray = [], callback = ->) ->
counter = fnArray.length
@@ -65,7 +52,6 @@ exports.throwIfNull = () ->
nullArgs = arg for arg in arguments when not arg?
throw 'Null argument' if nullArgs? and nullArgs.length
-
taskWrapper = (@task) ->
@next = null
@@ -87,7 +73,6 @@ taskWrapper::then = (@next) ->
return @wrapper
-
exports.execute = (task, args...) ->
wrapper = new taskWrapper task
args.push wrapper.callback.bind(wrapper)
View
3  controllers/player.js
@@ -127,7 +127,8 @@ exports.index = function (req, res, next) {
if (availableOnly) {
res.send(players);
} else {
- players.sort( sortingPlayer );
+ userSvc = require( '../services/user' )
+ players.sort( userSvc.sortingPlayers );
res.render(players, {
layout: true
, title: 'Wheels Foosball League (WFL) - Players'
View
958 controllers/profile.js
@@ -1,783 +1,239 @@
-/*
- GET
- URL /profile
- Redirect to /profile/show with current user id
-*/
-exports.index = function(req, res) {
- var user = req.session.user
- , userId = user._id || '';
-
- // redirect to show with current user id
- res.redirect('/profile/' + userId);
-}
-exports.index.methods = ['GET'];
-exports.index.authenticated = true;
-
-
-/*
- GET
- URL /profile/show
-*/
-exports.show = function(req, res, next) {
- var userId = req.params.id || null;
-
- console.log('showing user ', userId);
-
- if (userId === 'undefined') {
- res.send(userId);
- return;
- }
-
- if (!userId) {
- req.flash('error', 'player id is empty...playa');
- next();
- //res.render(null, {
- // layout: true
- // , title: 'Wheels Foosball League (WFL) - Profile'
- //});
- return;
- }
-
- getUser(userId, function(error, user) {
- if (error) {
- req.flash('error', error);
- next();
- } else {
- res.render( user, {
- layout: true
- , title: 'Wheels Foosball League (WFL) - Profile'
- , user: req.session.user
+(function() {
+ var userSvc;
+
+ userSvc = require('../services/user');
+
+ /*
+ POST
+ URL /profile/:id/removecomment
+ */
+
+ exports.removecomment = function(req, res, next) {
+ var commentid, postid, userid;
+ userid = req.params.id;
+ postid = req.param('postid', '');
+ commentid = req.param('commentid', '');
+ if (!userid) return res.send();
+ try {
+ return userSvc.removeComment(userid, postid, commentid, function(error, comment) {
+ var result;
+ result = {
+ success: true
+ };
+ if (error) {
+ result.success = false;
+ result.error = error;
+ } else {
+ result.comment = comment;
+ }
+ return res.send(result);
});
+ } catch (e) {
+ console.trace(e);
+ req.flash('error', e);
+ return next(e);
}
- });
-}
-exports.show.methods = ['GET'];
-exports.show.authenticated = true;
-
-
-/*
- POST
- URL /profile/:id/addpost
-*/
-exports.addPost = function(req, res, next) {
- var userid = req.params.id
- , posterid = req.param('posterid')
- , msg = req.param('msg')
- , post = {
- type: 'post'
- , data: {
- posterid: posterid
- , msg: msg
- }
- , createdat: new Date()
- };
-
- if (!userid) {
- res.send();
- return false;
- }
-
- addUserPost(userid, post, function(error, fullPost) {
- var result = {
- success: true
- };
-
- if (error) {
- result.success = false;
- result.error = error;
- } else {
- result.post = fullPost;
- }
-
- res.send(result);
-
- return true;
- });
-
- return true;
-}
-exports.addPost.authenticated = true;
-exports.addPost.action = ':id/addpost';
-exports.addPost.methods = ['POST'];
-
+ };
+ exports.removecomment.authenticated = true;
-/*
- POST
- URL /profile/:id/removepost
-*/
-exports.removePost = function(req, res, next) {
- var userid = req.params.id
- , postid = req.param('postid');
-
- if (!userid) {
- res.send();
- return false;
- }
+ exports.removecomment.methods = ['POST'];
- removeUserPost(userid, postid, function(error, post) {
- var result = {
- success: true
- };
-
- if (error) {
- result.success = false;
- result.error = error;
- } else {
- result.post = post;
- }
-
- res.send(result);
-
- return true;
- });
-
- return true;
-}
-exports.removePost.authenticated = true;
-exports.removePost.methods = ['POST'];
-exports.removePost.action = ':id/removepost';
+ exports.removecomment.action = ':id/removecomment';
+ /*
+ POST
+ URL /profile/:id/addcomment
+ */
-/*
- POST
- URL /profile/:id/addcomment
-*/
-exports.addcomment = function(req, res, next) {
- var userid = req.params.id
- , postid = req.param('postid')
- , posterid = req.param('posterid')
- , msg = req.param('msg');
-
- addPostComment(userid, postid, posterid, msg, function(error, comment) {
- var result = {
- success: true
+ exports.addcomment = function(req, res, next) {
+ var comment, msg, posterid, postid, userid;
+ userid = req.params.id;
+ postid = req.param('postid', '');
+ posterid = req.param('posterid', '');
+ msg = req.param('msg', '');
+ comment = {
+ posterid: posterid,
+ msg: msg
};
-
- if (error) {
- result.success = false;
- result.error = error;
- res.send(result);
- } else {
- loadFullComment(comment, function(error, fullComment) {
+ try {
+ return userSvc.addComment(userid, postid, comment, function(error, addedcomment) {
+ var postSvc, result;
+ result = {
+ success: true
+ };
if (error) {
- result.comment = comment;
+ result.success = false;
+ result.error = error;
+ return res.send(result);
} else {
- result.comment = fullComment;
+ postSvc = require('../services/post');
+ try {
+ return postSvc.loadComment(comment, function(error, fullComment) {
+ if (error) {
+ result.comment = comment;
+ } else {
+ result.comment = fullComment;
+ }
+ return res.send(result);
+ });
+ } catch (e) {
+ console.trace(e);
+ req.flash('error', e);
+ return next();
+ }
}
- res.send(result);
- });
- }
-
-
- return true;
- });
-
- return true;
-}
-exports.addcomment.authenticated = true;
-exports.addcomment.methods = ['POST'];
-exports.addcomment.action = ':id/addcomment';
-
-
-
-function addPostComment(userid, postid, posterid, msg, callback) {
- var userRepo = require('../repository/users');
-
- callback = callback || function() {};
-
- userRepo.addComment(userid, postid, {posterid: posterid, msg: msg}, callback);
-}
-
-
-
-function removeUserPost(userid, postid, callback) {
- var userRepo = require('../repository/users');
-
- callback = callback || function() {};
-
- userRepo.removePost(userid, postid, callback);
-
- return true;
-}
-
-
-
-
-function addUserPost(userid, post, callback) {
- var userRepo = require('../repository/users');
-
- callback = callback || function() {};
-
- userRepo.addPost( userid, post, function(error, user) {
- if (error) {
- callback(error);
+ });
+ } catch (e) {
+ console.trace(e);
+ req.flash('error', e);
+ return next(e);
}
-
- if (user) {
- loadFullPost( user, post, callback );
- } else {
-
- userRepo.getFullUser(userid, function(error, fullUser) {
- if (error || !fullUser) {
- callback(error);
- return false;
+ };
+
+ exports.addcomment.authenticated = true;
+
+ exports.addcomment.methods = ['POST'];
+
+ exports.addcomment.action = ':id/addcomment';
+
+ /*
+ POST
+ URL /profile/:id/removepost
+ */
+
+ exports.removePost = function(req, res, next) {
+ var postid, userid;
+ userid = req.params.id;
+ postid = req.param('postid', '');
+ if (!userid) return res.send();
+ try {
+ return userSvc.removePost(userid, postid, function(error, post) {
+ var result;
+ result = {
+ success: true
+ };
+ if (error) {
+ result.success = false;
+ result.error = error;
+ } else {
+ result.post = post;
}
-
- loadFullPost(fullUser, post, callback);
+ return res.send(result);
});
-
- }
-
- return true;
- });
-
- return true;
-}
-
-
-
-/*
- get a full tree user object
-*/
-function getUser(userId, callback) {
- var repo = require('../repository/users')
- , utils = require('utils')
- , fullUser = null
- , loadTeamFn = function(loadTeamFnCallback) {
- loadTeamFnCallback = loadTeamFnCallback || function() {};
- loadTeamForUser(fullUser, loadTeamFnCallback);
- }
- , loadInvites = function(loadInvitesCallback) {
- loadInvitesCallback = loadInvitesCallback || function() {};
-
- if (fullUser && fullUser.invites && fullUser.invites.length) {
- utils.map(fullUser.invites, loadFullInvite, function(error, fullInvites) {
-
- if(!error) {
- fullUser.invites = fullInvites;
- }
-
- loadInvitesCallback(null, fullUser);
- });
- } else {
- loadInvitesCallback(null, fullUser);
- }
+ } catch (e) {
+ console.trace(e);
+ req.flash('error', e);
+ return next(e);
}
- , loadPosts = function(loadPostsCallback) {
- loadPostsCallback = loadPostsCallback || function() {};
-
- if (fullUser && fullUser.posts && fullUser.posts.length) {
- utils.map(fullUser.posts
- , function(post, cb) {
- loadFullPost(fullUser, post, cb);
- }
- , function(error, fullPosts) {
-
- if (!error) {
- fullPosts.sort( function(a, b) {
- return b.createdat - a.createdat;
- });
- fullUser.posts = fullPosts;
- }
-
- loadPostsCallback(null, fullUser);
- }
- );
- } else {
- loadPostsCallback(null, fullUser);
- }
+ };
+
+ exports.removePost.authenticated = true;
+
+ exports.removePost.methods = ['POST'];
+
+ exports.removePost.action = ':id/removepost';
+
+ /*
+ POST
+ URL /profile/:id/addpost
+ */
+
+ exports.addPost = function(req, res, next) {
+ var msg, post, posterid, userid;
+ userid = req.params.id;
+ posterid = req.param('posterid', '');
+ msg = req.param('msg', '');
+ post = {
+ type: 'post',
+ data: {
+ posterid: posterid,
+ msg: msg
+ },
+ createdat: new Date()
};
-
- repo.getFullUser(userId, function(error, user) {
- if (error) {
- console.log(error);
- callback(error);
- } else {
- fullUser = user;
-
- utils.parallel([loadTeamFn, loadInvites, loadPosts], function(error) {
-
- callback(error, fullUser);
+ if (!userid) return res.send();
+ try {
+ return userSvc.addPost(userid, post, function(error, fullPost) {
+ var postSvc, result;
+ result = {
+ success: true
+ };
+ if (error) {
+ result.success = false;
+ return result.error = error;
+ } else {
+ postSvc = require('../services/post');
+ postSvc.init();
+ return postSvc.makePostGen(req.user)(post, function(err, fullpost) {
+ if (fullpost != null) {
+ result.post = fullpost;
+ } else {
+ result.post = post;
+ }
+ return res.send(result);
+ });
+ }
});
-
- //loadTeamForUser(user, function(userwTeam) {
- // console.log(userwTeam);
- // callback(null, userwTeam);
- //});
- //callback(null, user);
+ } catch (e) {
+ console.trace(e);
+ req.flash('error', e);
+ return next(e);
}
- });
-
- return true;
-};
+ };
+ exports.addPost.authenticated = true;
-/*
- Load team object for user
-*/
-function loadTeamForUser(user, callback) {
- callback = callback || function() {};
-
- if (user && user.team && user.team._id) {
- var repo = require('../repository/teams');
-
- repo.getFullTeam(String(user.team._id), function(error, team) {
- if (team) {
- user.team = team;
- }
- callback(error, user);
- });
- } else {
- callback(null, user);
- }
-};
+ exports.addPost.action = ':id/addpost';
+ exports.addPost.methods = ['POST'];
-// take in a brief invite obj and return a full Invite object
-function loadFullInvite(invite, callback) {
- var teamid = invite ? invite.teamid : null
- , userid = invite ? invite.invitor : null
- , utils = require('utils')
- , loadTeamFn = function(loadTeamCallback) {
- loadTeam(teamid, loadTeamCallback);
- }
- , loadUserFn = function(loadUserCallback) {
- loadUser(userid, loadUserCallback);
- };
-
- if (invite && teamid && userid) {
- utils.parallel([loadTeamFn, loadUserFn], function(error, results) {
- if (!error) {
- invite.team = results[0];
- invite.invitor = results[1];
- }
-
- callback(error, invite);
- });
- } else {
- callback(null, invite);
- }
-}
+ /*
+ GET
+ URL /profile
+ Redirect to /profile/show with current user id
+ */
+ exports.index = function(req, res, next) {
+ var userId, _ref, _ref2;
+ userId = (_ref = req != null ? (_ref2 = req.user) != null ? _ref2._id : void 0 : void 0) != null ? _ref : '';
+ return res.redirect('/profile/' + userId);
+ };
-// take in a brief post object and return a full post object
-function loadFullPost(user, post, callback) {
- if (!post) {
- callback(null, post);
- return;
- }
+ exports.index.methods = ['GET'];
- var desc = ''
- , pictureurl = ''
- , utils = require('utils')
- , returnFn = function(error) {
- post.pictureurl = pictureurl;
- post.desc = desc;
-
- if (post.comments) {
- loadPostComments(post, function(error, fullComments) {
- post.comments = fullComments;
- callback(error, post);
- });
- } else {
- callback(error, post);
- }
- };
+ exports.index.authenticated = true;
- // Populate post picture url, post description (embedded HTML)
- switch (post.type) {
- case 'jointeam': // added into a team
- pictureurl = user.pictureurl || '';
- desc = '<a href="/profile/{0}">{1}</a> joined team <a href="/team/{3}">{2}</a>';
- desc = desc.replace('{0}', String(user._id))
- .replace('{1}', user.nickname);
-
- if (post.data && post.data.teamid) { // teamid exists, load team
- loadTeam(post.data.teamid, function(error, team) {
- if (team) {
- desc = desc.replace('{2}', team.teamname)
- .replace('{3}', String(team._id));
- }
- returnFn(error);
- });
- } else {
- returnFn();
- }
- break;
-
- case 'invite': // get a team invite
- desc = '<a href="/profile/{0}">{1}</a> invited <a href="/profile/{2}">{3}</a> to join team <a href="/team/{4}">{5}</a>';
- desc = desc.replace('{2}', String(user._id))
- .replace('{3}', user.nickname);
-
- if ( post.data && post.data.teamid && post.data.playerid ) {
- utils.parallel(
- [
- function(cb) {
- loadTeam(post.data.teamid, cb);
- }
- , function(cb) {
- loadUser(post.data.playerid, cb);
- }
- ]
- , function(error, results) {
- if (!error && results && results.length) {
- var team = results[0]
- , invitor = results[1];
-
- desc = desc.replace('{0}', String(invitor._id))
- .replace('{1}', invitor.nickname)
- .replace('{4}', String(team._id))
- .replace('{5}', team.teamname);
- pictureurl = invitor.pictureurl || '';
- returnFn();
- } else {
- returnFn(error);
- }
- }
- );
- }
- break;
-
- case 'teamjoin': // team joining request
- desc = '<a href="/profile/{0}">{1}</a> asked to join team <a href="/team/{3}">{2}</a>';
- desc = desc.replace('{0}', String(user._id))
- .replace('{1}', user.nickname);
-
- if (post.data && post.data.teamid) { // teamid exists, load team
- loadTeam(post.data.teamid, function(error, team) {
- if (team) {
- pictureurl = team.pictureurl || '';
- desc = desc.replace('{2}', team.teamname)
- .replace('{3}', String(team._id));
- }
- returnFn(error);
- });
- } else {
- returnFn();
- }
- break;
- case 'recruit': // recruit a player
- pictureurl = user.pictureurl || '';
- desc = '<a href="/profile/{0}">{1}</a> asked <a href="/profile/{2}">{3}</a> to make a team';
- desc = desc.replace('{0}', String(user._id))
- .replace('{1}', user.nickname);
-
- if (post.data && post.data.playerid) {
- loadUser(post.data.playerid, function(error, invitee) {
- if (invitee) {
- desc = desc.replace('{2}', String(invitee._id))
- .replace('{3}', invitee.nickname);
- }
- returnFn(error);
- });
- } else {
- returnFn();
- }
- break;
-
- case 'newteam':
- pictureurl = user.pictureurl || '';
- desc = '<a href="/profile/{0}">{1}</a> created team <a href="/team/{2}">{3}</a>';
- desc = desc.replace('{0}', String(user._id))
- .replace('{1}', user.nickname);
-
- if (post.data && post.data.teamid) { // teamid exists, load team
- loadTeam(post.data.teamid, function(error, team) {
-
- if (team) {
- desc = desc.replace('{3}', team.teamname)
- .replace('{2}', String(team._id));
- }
- returnFn(error);
- });
- } else {
- returnFn();
- }
- break;
-
- case 'teamchallenging':
- pictureurl = user.pictureurl || '';
- desc = '<a href="/profile/{0}">{1}</a> challenged team <a href="/team/{2}">{3}</a>';
- desc = desc.replace('{0}', String(user._id))
- .replace('{1}', user.nickname);
+ /*
+ GET
+ URL /profile/show
+ */
- if (post.data && post.data.matchtype) {
- desc += ' in ' + matchtypetext(post.data.matchtype);
- }
- if (post.data && post.data.msg) {
- desc += ' with message: "' + post.data.msg + '"';
- }
-
- if (post.data && post.data.teamid) { // teamid exists, load team
- loadTeam(post.data.teamid, function(error, team) {
-
- if (team) {
- desc = desc.replace('{3}', team.teamname)
- .replace('{2}', String(team._id));
-
- }
- returnFn(error);
- });
- } else {
- returnFn();
- }
- break;
-
- case 'teamchallenged':
- pictureurl = user.pictureurl || '';
- desc = 'Team <a href="/team/{2}">{3}</a> challenged <a href="/profile/{0}">{1}</a>';
- desc = desc.replace('{0}', String(user._id))
- .replace('{1}', user.nickname);
-
- if (post.data && post.data.matchtype) {
- desc += ' in ' + matchtypetext(post.data.matchtype);
- }
- if (post.data && post.data.msg) {
- desc += ' with message: "' + post.data.msg + '"';
- }
-
- if (post.data && post.data.teamid) { // teamid exists, load team
- loadTeam(post.data.teamid, function(error, team) {
- if (team) {
- pictureurl = team.pictureurl || '';
- desc = desc.replace('{3}', team.teamname)
- .replace('{2}', String(team._id));
- }
- returnFn(error);
- });
- } else {
- returnFn();
- }
- break;
-
- case 'newmatch':
- pictureurl = '/images/match.jpg';
- desc = 'A match between <a href="{0}">{1}</a> and <a href="{2}">{3}</a> was set! Match will expire on {4}. Game on!';
-
- if (post.data && post.data.matchid) { // matchid exists, load match
- loadMatch(post.data.matchid, function(error, m) {
-
- console.log('matchid = ', post.data.matchid, error, m);
- if (m && m.teams) {
-
- var team1 = m.teams[0]
- , team2 = m.teams[1]
- , expire = (m.end.getMonth()+1) + '/' + m.end.getDate() + '/' + m.end.getFullYear() + ' ' + m.end.getHours() + ':' + m.end.getMinutes();
-
- desc = desc.replace('{1}', team1.teamname)
- .replace('{0}', String(team1._id))
- .replace('{3}', team2.teamname)
- .replace('{2}', String(team2._id))
- .replace('{4}', expire);
- }
- returnFn(error);
- });
- } else {
- returnFn();
- }
- break;
-
- case 'challengedeclined':
- pictureurl = user.pictureurl || '';
- desc = 'Team <a href="/team/{2}">{3}</a> declined a challenge from <a href="/profile/{0}">{1}</a>. They\'re too scared, maybe?';
- desc = desc.replace('{0}', String(user._id))
- .replace('{1}', user.nickname);
-
- if (post.data && post.data.teamid) { // teamid exists, load team
- loadTeam(post.data.teamid, function(error, team) {
- if (team) {
- pictureurl = team.pictureurl || '';
- desc = desc.replace('{3}', team.teamname)
- .replace('{2}', String(team._id));
- }
- returnFn(error);
- });
- } else {
- returnFn();
- }
- break;
-
- case 'challengedeclining':
- pictureurl = user.pictureurl || '';
- desc = '<a href="/profile/{0}">{1}</a> declined a challenge from team <a href="/team/{2}">{3}</a>. Chicken much?';
- desc = desc.replace('{0}', String(user._id))
- .replace('{1}', user.nickname);
-
- if (post.data && post.data.teamid) { // teamid exists, load team
- loadTeam(post.data.teamid, function(error, team) {
- if (team) {
- desc = desc.replace('{3}', team.teamname)
- .replace('{2}', String(team._id));
- }
- returnFn(error);
- });
- } else {
- returnFn();
- }
- break;
-
- case 'challengecancelled':
- pictureurl = user.pictureurl || '';
- desc = '<a href="/profile/{0}">{1}</a> cancelled a challenge to team <a href="/team/{2}">{3}</a>. Regret much?';
- desc = desc.replace('{0}', String(user._id))
- .replace('{1}', user.nickname);
-
- if (post.data && post.data.teamid) { // teamid exists, load team
- loadTeam(post.data.teamid, function(error, team) {
- if (team) {
- desc = desc.replace('{3}', team.teamname)
- .replace('{2}', String(team._id));
- }
- returnFn(error);
- });
- } else {
- returnFn();
- }
- break;
-
- case 'challengeremoved':
- pictureurl = user.pictureurl || '';
- desc = 'Team <a href="/team/{2}">{3}</a> withdrew a challenge to <a href="/profile/{0}">{1}</a>. Maybe they think it\'s not a wise thing to do?';
- desc = desc.replace('{0}', String(user._id))
- .replace('{1}', user.nickname);
-
- if (post.data && post.data.teamid) { // teamid exists, load team
- loadTeam(post.data.teamid, function(error, team) {
- if (team) {
- desc = desc.replace('{3}', team.teamname)
- .replace('{2}', String(team._id));
- }
- returnFn(error);
- });
- } else {
- returnFn();
- }
- break;
-
- case 'post':
- desc = '<a href="/profile/{0}">{1}</a> wrote: <div>{2}</div>';
- desc = desc.replace('{2}', post.data ? post.data.msg || '' : '');
-
- if (post.data && post.data.posterid) {
- loadUser( post.data.posterid, function(error, poster) {
- if(poster) {
- pictureurl = poster.pictureurl || '';
- desc = desc.replace('{0}', String(poster._id))
- .replace('{1}', poster.nickname);
- }
-
- returnFn( error );
- } );
- } else {
- returnFn();
- }
-
- break;
-
- case 'matchresult':
- pictureurl = user.pictureurl || '';
-
- if (post.data) {
- if ((post.data.result || 'win') === 'win') {
- desc = '<a href="/profile/{0}">{1}</a> won a match against team <a href="/team/{2}">{3}</a>. Rub it on them!';
+ exports.show = function(req, res, next) {
+ var playerid, _ref;
+ playerid = (_ref = req.params) != null ? _ref.id : void 0;
+ if (!(playerid && playerid !== 'undefined')) return next();
+ try {
+ return userSvc.getFullUser(playerid, function(err, fullplayer) {
+ if (err) {
+ req.flash('error', err);
+ return next(err);
} else {
- desc = '<a href="/profile/{0}">{1}</a> lost a match to team <a href="/team/{2}">{3}</a>. That has got to hurt!';
+ return res.render(fullplayer, {
+ layout: true,
+ title: 'WFL - Profile'
+ });
}
- } else {
- desc = '<a href="/profile/{0}">{1}</a> played a match against team <a href="/team/{2}">{3}</a> with unknown result';
- }
-
- desc = desc.replace('{0}', String(user._id))
- .replace('{1}', user.nickname);
-
- if (post.data && post.data.opponentid) { // teamid exists, load team
-
- loadTeam(post.data.opponentid, function(error, team) {
- if (team) {
- desc = desc.replace('{3}', team.teamname)
- .replace('{2}', String(team._id));
- }
- returnFn(error);
- });
- } else {
- returnFn();
- }
-
- break;
-
- default:
- returnFn();
- break;
- }
-
- return true;
-}
-
-
-function loadPostComments(post, callback) {
- var utils = require('utils');
-
- if (post && post.comments) {
- utils.map(post.comments, loadFullComment, callback );
- } else {
- callback(null, post.comments);
- }
-}
-
-
-function loadFullComment(comment, callback) {
-
- if (comment && comment.posterid) {
- loadUser(comment.posterid, function(error, user) {
- if (user) {
- comment.pictureurl = user.pictureurl || '';
- var desc = '<a href="/profile/{0}">{1}</a> wrote: <div>{2}</div>';
-
- desc = desc.replace('{2}', comment.msg || '')
- .replace('{0}', String(user._id))
- .replace('{1}', user.nickname);
- comment.desc = desc;
- }
- callback(error, comment);
- });
- } else {
- callback(null, comment);
- }
-}
-
-
-function loadTeam(teamid, callback) {
- var repo = require('../repository/teams');
-
- repo.getFullTeam(teamid, callback);
-}
-
+ });
+ } catch (e) {
+ console.trace(e);
+ req.flash('error', e);
+ return next(e);
+ }
+ };
-function loadUser(userid, callback) {
- var repo = require('../repository/users');
-
- repo.getFullUser(userid, callback);
-}
+ exports.show.methods = ['GET'];
-function loadMatch(matchid, callback) {
- var repo = require('../repository/matches');
-
- repo.get(matchid, callback);
-}
+ exports.show.authenticated = true;
-function matchtypetext(type) {
- switch (type) {
- case '1':
- return 'one game match';
- case '3':
- return 'best of 3 games match';
- case '5':
- return 'best of 5 games match';
- case '99':
- return 'a death match';
- default:
- return type;
- }
-}
+}).call(this);
View
35 controllers/team.js