Skip to content

Instantly share code, notes, and snippets.

@shawn-simon
Created June 9, 2015 03:21
Show Gist options
  • Save shawn-simon/8b5e6dc32db687528c7b to your computer and use it in GitHub Desktop.
Save shawn-simon/8b5e6dc32db687528c7b to your computer and use it in GitHub Desktop.
the worst code yet
var util = require('util');
var http = require('http');
var logger = require('../lib/logger');
var mongoose = require('mongoose');
var Broadcast = require('../models/broadcast');
var User = require('../models/user');
var yConfig = require('config');
//var _ = require('underscore');
function EVENT() {
_id = randomize.random(10393203 * 328320);
body = {};
}
// implements messaging (single consumer : listener( listener ( listener ))) )
function SOCIALEVENTS() {
this.consumers = {};
this.newConsumer = function() {
return {
queue: [],
handler: {},
ready: false,
timeoutMs: 20000,
}
};
this._defaultfunc = function() {
var _err = {
status: "ERROR",
message: "No such consumer/event supported"
};
if (typeof arguments[arguments.length - 1] === 'function')
arguments[arguments.length - 1](_err);
else
return _err;
}
this.getHandler = function(prevt) {
var split = prevt.split('.');
}
this.getHandler = function(pr, evt) {
if (this.consumers[pr] && this.consumers[pr].handler[evt])
return this.consumers[pr].handler[evt];
else
return this._defaultfunc;
}
this.register = function(pr, evt, handler) {
if (typeof this.consumers[pr] === "undefined")
this.consumers[pr] = this.newConsumer();
this.consumers[pr].handler[evt] = handler;
return this;
}
this.dispatchEvt = function(pr, evt, msg, cb) {
logger.mainLogger.info("Dispatching " + pr + " event: " + evt);
var self = this;
if (typeof self.consumers[pr] === "undefined") {
console.log("New consumer");
self.consumers[pr] = self.newConsumer();
}
if (self.consumers[pr].ready == false) {
logger.mainLogger.info("queueing event " + evt + " for " + pr);
self.consumers[pr].queue.push(function() {
// wait for handlers to emerge before firing next event.
process.nextTick(function() {
self.getHandler(pr, evt)(msg, cb);
});
});
// Times out on callback
setTimeout(function() {
if (self.consumers[pr].ready == false) cb({
status: "timeout"
})
}, self.consumers[pr].timeoutMs);
// QUEUEing events shouldnt block the program. just saying
// what about cancelled events ? ? oh shit dawg.
} else
self.getHandler(pr, evt)(msg, cb);
}
this.ready = function(pr) {
var self = this;
self.consumers[pr].ready = true;
logger.mainLogger.info("consumer " + pr + " is ready.");
var prQueue = self.consumers[pr].queue;
var nQ = [];
while (prQueue.length > 0) {
nQ.push(prQueue.pop());
}
nQ.forEach(function(e) {
return process.nextTick(function() {
e();
});
});
return self;
}
}
// handles a specific typeof social object per network
// so long as social.name is set.
// overwrite or push new a social profile into User.socialNetworks
var mergeSocialWithUser = function(mcUser, social, fn_e_o) {
var mcUID = mcUser._id;
var provider = social.name;
// if no socialnetworks, new empty list
if (!mcUser.socialNetworks)
mcUser.socialNetworks = [];
var pushNew = true;
// determine whether to update inplace or push new
mcUser.socialNetworks.forEach(function(e, i, a) {
if (e.name == provider && e.name !== null) {
a[i] = social; // overwrite
pushNew = false;
}
});
// tie this user to the socialNetwork profile
if (pushNew === true)
mcUser.socialNetworks.push(social);
logger.mainLogger.info("Merging " + mcUID + " for " + provider);
updateUserFields(mcUser, {
"socialNetworks": mcUser.socialNetworks
}, fn_e_o);
};
// gets names from user.socialNetworks
var getExistingSocialNetworks = function(mc_userId, fn_e_o) {
var retObj = [];
var err;
getUser(mc_userId, function(u_err, mcUser) {
if (!u_err) {
if (mcUser.socialNetworks) {
mcUser.socialNetworks.forEach(function(sNet, i, a) {
if ((typeof sNet.access == "undefined") || !sNet.access === false)
retObj.push(sNet.name);
});
}
} else
err = handleDBError(u_err);
fn_e_o(err, retObj)
});
}
// Disconnects a user from social networks
var disconnectUser = function(mc_userId, fromNet, fn_e) {
var mobcrushUser;
var scrubbed_fromNet = fromNet ? fromNet.toLowerCase().trim() : "";
if (isSupportedSocialNetwork(scrubbed_fromNet))
getUser(mc_userId, function(u_err, mcUser) {
if (!u_err) {
var sNet = getUserSocialNetworkByName(mcUser, scrubbed_fromNet);
if (sNet) {
// TODO: DO social logout here
var connectedSocialNetworks = [];
if (mcUser.socialNetworks) {
mcUser.socialNetworks.forEach(function(e, i, a) {
if (scrubbed_fromNet != e.name) {
connectedSocialNetworks.push(e);
}
});
}
updateUserFields(mcUser, {
"socialNetworks": connectedSocialNetworks
}, fn_e);
} else fn_e({
msg: "User not logged in",
code: "NOTLOGGEDIN"
});
} else
fn_e({
code: "NOTFOUND",
msg: "USER NOT FOUND"
});
})
else
fn_e({
code: "NOTSUPPORTED",
msg: "Unsupported Social Network"
});
}
var shareVideo = function(userId, bcastId, pushToSNets, fn_e) {
var resErr;
var userMessage = '';
var pushToSocialNet = pushToSNets[0];
if (pushToSNets && pushToSNets.length > 0)
getUser(userId, function(u_err, user) {
if (!u_err) {
getBroadcast(bcastId, function(bc_err, bcast) {
if (bcast && !bc_err) {
var uid = user.socialGUID
var context = "broadcast_share"
var sNet = getUserSocialNetworkByName(user, pushToSocialNet);
// are we attempting to push to a known (user known) network ?
if (sNet) {
} else // if not then Error!
{
fn_e({
msg: "User not logged in",
code: "NOTLOGGEDIN"
})
}
} else
fn_e(handleDBError(bc_err)); //resErr = bc_err;
});
} else
fn_e(handleDBError(u_err)); //resErr = u_err;
//completion
//fn_e(resErr);
});
else
fn_e({
code: "PARAMETERS",
msg: "no networks were specified for share."
});
};
// convenience method to fetch users.
function getUser(userId, fn_e_u) {
User
.findById(userId)
.select('_id username socialNetworks socialGUID profileLogo followerCount followingCount broadcastCount likeCount ')
.lean(true)
.exec(function(err, userObject) {
if (err)
fn_e_u(err);
if (userObject)
fn_e_u(null, userObject);
if (!err && !userObject)
fn_e_u({
message: "Object not found",
name: "notfound"
});
});
}
// convenience method to fetch broadcasts
function getBroadcast(bcastId, fn_e_u) {
Broadcast
.findById(bcastId)
.populate('game', '-_id name')
.populate('channel', 'name')
.populate('user', 'username socialNetworks')
.lean(true)
.select('_id user game channel totalViews currentViewers likes regionName startDate endDate title width height')
.exec(function(err, broadcastObject) {
if (err)
fn_e_u(err);
if (broadcastObject)
fn_e_u(null, broadcastObject);
if (!err && !broadcastObject)
fn_e_u({
message: "Object not found",
status: "NOTFOUND"
});
});
}
function updateUserFields(user, updateFields, fn_e) {
// merge in db
User.update({
"_id": mongoose.Types.ObjectId(user._id)
}, {
$set: updateFields
}, function(up_err, aff) {
if (up_err)
fn_e(up_err);
else
fn_e(null, user);
});
}
function isSupportedSocialNetwork(net) {
return yConfig.social.supported_networks.indexOf(net) > -1;
}
function generateUserActionForShare(bcast, user, message) {
var bcastId = bcast._id;
var action = {};
var _ycv = yConfig.uri.video;
if (bcast.isLive) {
if (bcast.game) // $un is playing $gn on @mobcrush $link
action.title = bcast.user.username + " is playing" + bcast.game.name + " on @mobcrush";
else
action.title = bcast.user.username + " is playing on @mobcrush";
} else {
// Check out this $gn video on @mobcrush by $un
if (bcast.game) // Check out this $gn @mobcrush video by $un $link
action.title = "Check out this " + bcast.game.name + " video on @mobcrush by " + bcast.user.username;
else
action.title = "Check out this video on @mobcrush by " + bcast.user.username;
}
action.vidUrl = util.format(bcast.isLive ? _ycv.live : _ycv.vod, bcastId);
action.flashUrl = util.format(yConfig.uri.video.flash, encodeURIComponent(action.vidUrl)); //pathToFlashls+"?url="+encodeURIComponent('http://vodcdn.mobcrush.com/u/video/' + bcastId + '/recording.mp4.m3u8')
action.imageUrl = util.format(yConfig.uri.asset.video_snapshot, bcastId); //'https://cdn.mobcrush.com/u/video/'+bcastId+'/snapshot.jpg' //var vodHLSUrl = encodeURIComponent('http://vodcdn.mobcrush.com/u/video/'+bcastId+'/recording.mp4.m3u8')
action.linkBack = util.format(yConfig.uri.asset.video_page_user, encodeURIComponent(user.username), bcastId);
if (yConfig.uri.asset.video_page_share)
action.videoshare = util.format(yConfig.uri.asset.video_page_share, bcastId);
if (message)
action.userMessage = message;
return action;
}
// function to share a broadcast socially ( facebook only muhahahahah )
function graphShare(gUID, bcastId, fn_e_o) {
}
function getUserSocialNetworkByName(user, n) {
var sNet; // detect that we have the one we are looking for .
if (user.socialNetworks) {
user.socialNetworks.forEach(function(e, i, a) {
if (e.name === n) sNet = e;
});
}
return sNet;
}
function handleDBError(err) {
logger.mainLogger.error("DBError (from MONGO): " + JSON.stringify(err));
return {
code: "DBERR",
msg: "Object not found"
};
}
module.exports = {
getBroadcast: getBroadcast,
getUser: getUser,
generateUserActionForShare: generateUserActionForShare,
getExistingSocialNetworks: getExistingSocialNetworks,
disconnectUser: disconnectUser,
shareVideo: shareVideo,
mergeSocialWithUser: mergeSocialWithUser,
isSupportedSocialNetwork: isSupportedSocialNetwork,
getUserSocialNetworkByName: getUserSocialNetworkByName,
socialEvents: new SOCIALEVENTS()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment