Example #1
0
 return new Promise((resolve, reject) =>{
     for(var i=0; i < currentPayload.data.total; i++){
         if(currentPayload.data.event_data[i].isLive){
             var flag = false;
             if(currentPayload.data.activities){
                 currentPayload.data.activities.forEach((val,index) =>{
                     if(val.event_id === currentPayload.data.event_data[i].id){
                         flag = true;
                     }
                 })
             }
             
             if(!flag && currentPayload.data.webhook_URI){
                 let requestOptions = {
                     'url' : currentPayload.data.webhook_URI,
                     'method' : 'POST',
                     'postBody' : currentPayload.data.event_data[i],
                     'headers' : null,
                     'options' : null
                 }
                 let resolveOption = {
                     'activity' : null,
                     'event_id' : currentPayload.data.event_data[i].id
                 }
                 sendRequest(requestOptions, resolve, reject, resolveOption);
             } else{
                 jive.logger.debug("Activity already created or no webhook url");
                 resolve();
             }
         } else{
             jive.logger.info('No live video streams available');
             resolve();
         }
     }
 })
Example #2
0
 }, function(err, resp, body) {
     if (err) {
         jive.logger.error("error proxying request:" + req.query.url + JSON.stringify(err));
         jive.logger.error(body);
     }
     else {
         jive.logger.debug("returning" + body);
         res.send(body,200);
     }
 });
Example #3
0
var updateDeployLog = function(place, installationUrl, type) {
    var credentials = getCredentialsFor(installationUrl);

    if (credentials == null) {
        jive.logger.error('Could not find credentials for installation: '+installationUrl);
        return;
    }

    jive.logger.info('Querying JCA for '+installationUrl);

    var parsedUrl = url.parse(installationUrl, true);

    var apiUrl = credentials.baseUrl + '/api/cloud/v1/users/deployrequests?rows=25&page=0&filter='+JSON.stringify({
        "customerInstallationId": parsedUrl.query.customerInstallationId,
        "onlyShowCompleted":"true"
    });

    jive.util.buildRequest(apiUrl, "GET", null, {
        'Authorization': "Basic " + new Buffer(credentials.username+':'+credentials.password).toString('base64')
    }).then(function(response) {

        var rows = _.filter(response.entity.rows, function(row) {
            return row.description.indexOf('Update Installation') !== -1;
        });

        _.each(rows, function(row) {
            var files = _.map(row.deployFiles, function(file) {
                return file.fileName;
            });

            var entry = {
                tenantID: place.tenantID,
                type: type,
                placeURI: place.id,
                username: row.userName,
                id: row.requestID,
                timestamp: moment.tz(row.requestDate, 'MM/DD/YYYY hh:mm A', "America/Los_Angeles").valueOf(), // We know the TZ for the timestamp is PST
                message: row.deployNotes,
                files: files
            };

            log.addEntry(entry).fail(function() {
                jive.logger.error('Error saving: '+row.requestID, arguments);
            });

        });

    }).fail(function(response) {
        console.log('Error getting deploy for for '+installationUrl, arguments);
    }).done();
};
myOauth.oauth2SuccessCallback = function( state, originServerAccessTokenResponse, callback ) {
    jive.logger.debug("************************* OAUTH CALLBACK");
    jive.logger.debug('************************* State', state);
    jive.logger.debug('************************* originServerAccessTokenResponse', originServerAccessTokenResponse);

    var placeRef = state.context.place;

    var toStore = {};
    toStore.jive = originServerAccessTokenResponse.entity;
    toStore.jive.userID =  state['viewerID'];
    placeStore.save(placeRef, toStore).then( function() {
        callback({'ticket': state['viewerID'] });
    });
};
Example #5
0
  'route': function(req, res) {
    var jiveExtensionHeaders = jive.util.request.parseJiveExtensionHeaders(req);
//     if (!jiveExtensionHeaders ) {
//         res.writeHead(403, {'Content-Type': 'application/json'})
//         res.end( JSON.stringify( { } ) );
//         return;
//     } // end if
    
    var placeURI = req.body.placeURI;
    var userID = 4567; //TODO: INIT FROM HEADERS

    jive.logger.debug('Jive Extension Headers:',jiveExtensionHeaders);
    jive.logger.debug('Place ID:',req.params.placeID);

  } // end req,res function
Example #6
0
            instances.forEach( function( instance ) {
                var config = instance['config'];
                if ( config && config['posting'] === 'off' ) {
                    return;
                }

                jive.logger.debug('running pusher for ', instance.name, 'instance', instance.id );

                var store = jive.service.persistence();
                return store.find('exampleStore', {
                    'key':'count'
                }).then(function(count) {
                    count = count.length > 0 ? count[0].count : parseInt(instance.config.startSequence, 10);
                    store.save('exampleStore', 'count', {
                        'key':'count',
                        'count':count+1
                    }).then(function() {
                        jive.extstreams.pushActivity(instance, getFormattedData(count));
                    });
                }, function(err) {
                    //some error
                    jive.logger.debug('Error encountered, push failed', err);
                });

            });
Example #7
0
function addToRegisteredHash(id, repo, token, event){
    jive.logger.info("Successfully registered: " + repo + "-"+event+":"+token);
    if(!registeredTiles[id]){
        registeredTiles[id] = {};
    }
    registeredTiles[id][event] = token;
}
Example #8
0
                instances.forEach( function( instance ) {

                    var config = instance['config'];
                    if ( config && config['posting'] === 'off' ) {
                        return;
                    }

                    jive.logger.debug('running pusher for ', instance.name, 'instance', instance.id );

                    count++;

                    var dataToPush = {
                        "activity":
                        {
                            "action":{
                                "name":"posted",
                                "description":"Activity " + count
                            },
                            "actor":{
                                "name":"Actor Name",
                                "email":"*****@*****.**"
                            },
                            "object":{
                                "type":"website",
                                "url":"http://www.google.com",
                                "image":"http://placehold.it/102x102",
                                "title":"Activity " + count,
                                "description":"Activity " + count
                            },
                            "externalID": '' + new Date().getTime()
                        }
                    };
                    //if (count < 3)
                      //jive.extstreams.pushActivity(instance, dataToPush);
                });
Example #9
0
function processTileInstance(instance) {
    jive.logger.debug('running pusher for ', instance.name, 'instance', instance.id);

    count++;

    var dataToPush = {
        data: {
            "title": "Featured Email",
            "contents": [
                {
                    "text": JSON.stringify(instance['config']['data']),
                    "icon": "https://community.jivesoftware.com/servlet/JiveServlet/showImage/102-99994-1-1023036/j.png",
                    "linkDescription": "Current counter."
                }
            ],
            "config": {
                "listStyle": "contentList"
            },
            "action": {
                "text": "Add a Todo",
                "context": {
                    "mode": "add"
                }
            }
        }
    };

    jive.tiles.pushData(instance, dataToPush).then(function(e){
        console.log('*success*');
    }, function(e) {
        console.log('*err*');
    });
}
Example #10
0
exports.route = function(req, res){

	/*
	 * { "G":"0101",
	 *   "V":0,
	 *   "D":31,
	 *   "DA":28.9,
	 *   "timestamp":1379624575501,
	 *   "node":"2113BB000699",
	 *   "GUID":"2113BB000699_0101_0_31",
	 *   "id":"bf170bac-fe48-11e2-bfe5-22000a9d2c4c"
	 *  }
	 */
	var temperature = req.body.DA;
	var timestamp = new Date();
	
	jive.logger.debug('POST /ninjablocks-beer/configure => [ temperature : '+temperature+', timestamp='+timestamp+' ]');	
	
	if (temperature) {		
		
        services.pushData(temperature,timestamp);
        
    	res.send(200, '[ temperature : '+temperature+', timestamp='+timestamp+' ]');
	} else {
		console.log('Invalid Temperature ['+temperature+']');		
		res.send(400, "Invalid Temperature: "+temperature);
	} // end if
};
Example #11
0
exports.handleGitHubQuery = function(req, res ) {
    var url_parts = url.parse(req.url, true);
    var queryPart = url_parts.query;

    var query = queryPart["query"];
    var ticketID = queryPart["ticketID"];
    var returnType = queryPart["id"] ;

    var uri = encodeURIComponent(query);

    jive.logger.debug("query='" + query +"' ticketID='" + ticketID + "'" + " URI="+uri);

    github_helpers.queryGitHubV3(ticketID, sampleOauth, query).then(function (response) {
        res.writeHead(200, { 'Content-Type': 'application/json' });

        if (returnType != "all") {
            // this is a hack. If returnType isn't 'all', then this is our original one and only
            // use of this function - to get the repositories for a user after authentication
            // return just a list of the repositories the user has access to
            var body = response['entity'];
            var repos=[];
            body.forEach(function(repo)   {
                repos.push({ name : repo.name, full_name : repo.full_name})  ;
            } );

            res.end(JSON.stringify(repos) );
        } else {
            res.end(JSON.stringify(response['entity']));
        }
    }).catch(function (err) {
        res.writeHead(502, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify(err));
    });
};
Example #12
0
/**
 * Handles actually pushing data to the tile instance
 * @param instance
 */
//************************************************************************
// 1) Gets the events associated with the Live Stream account
// 2) Processes the payload and the existing config to create a updated config
// 3) Checks to see if updated event is the same
//      (a)If it's the same, it will NOT update the tile — this is so the tile
//          window doesn't refresh
// 4) If a video has a 'isLive' = true & there's a SSI listener URL, it will generate
//      an activity stream entry
// 5) Sends the updated config to the tile instance
//************************************************************************
function processTileInstance(instance) {
    jive.logger.debug('Running data pusher for ', instance.name, 'instance', instance.id);
    var configData = instance.config;

    getLiveStreamEvents(configData)
    .then((eventsPayload) =>{
        return processPayload(eventsPayload, configData);
    }).then((val) =>{
        if(_.isEqual(lastLSPayload.data.event_data, val.data.event_data)){
            jive.logger.debug("LiveStream events unchanged");
            return val;
        }
        return Promise.all([val, generateActivities(val)]);
    }).then((results) =>{
        if(Array.isArray(results) && results[1]){      // If the results is not an array we know that the json hasn't 
            results[0].data.activities.push(results[1]);
            lastLSPayload = results[0];         
            return jive.tiles.pushData(instance, lastLSPayload);
        } else{
            lastLSPayload = results[0] || results;
        }
    })
    .catch((err) =>{
        jive.logger.error(err)
    });
}
Example #13
0
function processTileInstance(instance) {
    jive.logger.debug('running pusher for ', instance.name, 'instance', instance.id);

    count++;

    var dataToPush = {
        data: {
            "title": "Simple Counter",
            "contents": [
                {
                    "text": "Selected: " + instance['config']['opportunityID'],
                    "icon": "http://farm4.staticflickr.com/3136/5870956230_2d272d31fd_z.jpg",
                    "linkDescription": "Current counter."
                }
            ],
            "config": {
                "listStyle": "contentList"
            },
            "action": {
                "text": "Add a Todo",
                "context": {
                    "mode": "add"
                }
            }
        }
    };

    jive.tiles.pushData(instance, dataToPush).then(function(e){
        console.log('*success*');
    }, function(e) {
        console.log('*err*');
    });
}
Example #14
0
 }).then((val) =>{
     if(_.isEqual(lastLSPayload.data.event_data, val.data.event_data)){
         jive.logger.debug("LiveStream events unchanged");
         return val;
     }
     return Promise.all([val, generateActivities(val)]);
 }).then((results) =>{
Example #15
0
  'route': function(req, res) {
      
    var jiveExtensionHeaders = jive.util.request.parseJiveExtensionHeaders(req);
//     if (!jiveExtensionHeaders ) {
//         res.writeHead(403, {'Content-Type': 'application/json'})
//         res.end( JSON.stringify( { } ) );
//         return;
//     } // end if
    
    var placeURI = req.body.placeURI;
    var userID = 4567; //TODO: INIT FROM HEADERS
          
    jive.logger.debug('Jive Extension Headers:',jiveExtensionHeaders);
    jive.logger.debug('Place URI:',placeURI);
    
    //TODO: VALIDATE EXTENSION HEADER & GLEAN USER ID

    //TODO: LOOKUP UP TILES IN PERSISTENCE AND THE SERIALIZE DETAILS TO STREAM
    if (!placeURI) {
      jive.logger.error('Invalid API Call: Requires Place Place URI in Body');
      res.writeHead(403, {'Content-Type': 'application/json'})
      res.end( JSON.stringify( { } ) );
    } else {    
      tileServices.verifyPlaceUser(placeURI,userID).then(
        function(authorized) {
          jive.logger.debug('Authorization Confirmed');
          tileServices.findTilesByPlaceID(placeURI).then(
            function(results) {
              res.writeHead(200, { 'Content-Type': 'application/json' });          
              res.end( JSON.stringify( results ) );    
            },
            function(error) {
              jive.logger.error('Error: ',error);
              res.writeHead(500, { 'Content-Type': 'application/json' });          
              res.end( JSON.stringify( { "error" : error } ) );                
            }
          );            
        },
        function (notAuthorized) {
          jive.logger.debug('Failed to Confirm Authorization!!!!');
          jive.logger.error('Error: ',error);
          res.writeHead(401, { 'Content-Type': 'application/json' });          
          res.end( JSON.stringify( { "error" : "Failed to Confirm Authorization!!!!" } ) );                
        }
      );
    } // end if
  } // end req,res function
exports.gitHubWebHookPortal = function (req, res) {
    var event = req.headers["x-github-event"];
    var data = req.body;
    jive.logger.info("Received GitHub data: " + event);
    gitHubFacade.handleIncomingWebhookEvent(event, data);
    res.writeHead(202);
    res.end();
};
Example #17
0
function pushTileInstance(instance, userName, fullName, url, msg1, msg2) {
    var config = instance['config'];

    if (config == undefined ) {
        return; // don't even bother ...
    }

    if (config['posting'] === 'off' ) {
        return;
    }

    // in early dev version, organization actually holds the full repository name
    if (config['organization'] != fullName) {
        // this POST doesn't match the repository for this instance
        return;
    }

    jive.logger.debug('running pusher for ', instance.name, 'instance', instance.id );
    jive.logger.debug('running pusher for ' + instance.name + ' instance ' + instance.id );
    count++;

    var dataToPush = {
        "activity":
        {
            "action":{
                "name":"posted",
                "description":"GitHub repository activity"
            },
            "actor":{
                "name": userName,
                "email":""
            },
            "object":{
                "type":"website",
                "url": url,
                "image":"http://png-3.vector.me/files/images/7/3/737157/github_thumb.png",
                "title": msg1,
                "description": msg2 /*+ " @ " + new Date().getTime()*/
            },
            "externalID": '' + new Date().getTime()
        }
    };

    jive.logger.debug( "pushing data ....");
    jive.extstreams.pushActivity(instance, dataToPush);
}
Example #18
0
 _.each(places, function(place) {
     try {
         updateDeployLog(place, place.prodUrl, 'prod');
         updateDeployLog(place, place.uatUrl, 'uat');
     } catch (ex) {
         jive.logger.error('Error updating log for place: '+place.id, ex);
     }
 });
Example #19
0
 jive.extstreams.findByDefinitionName( 'github-issues-active' ).then( function(instances) {
     if ( instances ) {
         instances.forEach( function( instance ) {
             pushTileInstance(instance, userName, fullName, url, msg1, msg2);
         });
     } else {
         jive.logger.debug( "gitHubHookRouteHandler: no instances")
     }
 });
Example #20
0
function processTileInstance(instance) {
    jive.logger.debug('running pusher for ', instance.name, 'instance', instance.id);
    if (doRefreshToken && refreshToken.length)     {
        console.log( 'refreshing token in PodioTaskList ...')
        oauth.refreshToken( refreshToken, instance['config']['ticketID'] );
        doRefreshToken = false;
    }
    else
         doDataPush(instance);
}
Example #21
0
/**
 * Handles actually pushing data to the tile instance
 * @param instance
 */
function processTileInstance(instance) {
    jive.logger.debug('running pusher for ', instance.name, 'instance', instance.id);

    // creates a data update structure
    function getFormattedData(count) {
        return {
            data: {
                 "title": "{{{TILE_NAME}}} :"+count,
                 "contents": [
                 {
                    "titleText": "Jive Software - Carousel 1",
                    "titleLink": "http://developer.jivesoftware.com",
                    "image": "http://www.easternct.edu/ctreview/connections/stories/images/carousel_1.jpg",
                    "imageURI": "http://www.easternct.edu/ctreview/connections/stories/images/carousel_1.jpg",
                    "description": "Carousel Horse"
                 },
                 {
                     "titleText": "Jive Software - Carousel 2",
                     "titleLink": "https://community.jivesoftware.com/community/developer",
                     "image": "http://thispublicaddress.com/tPA4/images/06_06/carousel.jpg",
                     "imageURI": "http://thispublicaddress.com/tPA4/images/06_06/carousel.jpg",
                     "description": "Old School Carousel"
                 },
                 {
                     "titleText": "Jive Software - Carousel 3",
                     "titleLink": "https://community.jivesoftware.com/community/developer",
                     "image": "http://upload.wikimedia.org/wikipedia/en/9/9e/Carousel_1945_Bdwy.jpg",
                     "imageURI": "http://upload.wikimedia.org/wikipedia/en/9/9e/Carousel_1945_Bdwy.jpg",
                     "description": "On Broadway"
                 }
                 ],
                 "config": {
                    "autoplay": true,
                    "speed": "medium",
                    "previewPane": true,
                    "transition": "fade"
                 }
                }
        };
    }

    var store = jive.service.persistence();
    return store.find('exampleCarouselStore', { 'key': 'count' } ).then(function(found) {
        found = found.length > 0 ? found[0].count : parseInt(instance.config.startSequence, 10);

        store.save('exampleCarouselStore', 'count', {
            'key':'count',
            'count':found + 1
        }).then(function() {
            return jive.tiles.pushData(instance, getFormattedData(found));
        });
    }, function(err) {
        jive.logger.debug('Error encountered, push failed', err);
    });
}
 return jiveApi.replyToDiscussion(discussion.contentID , jiveReply).then(function (response) {
     if (!response.success) {
         jive.logger.error("Error creating comment on " + discussion.subject, response);
     } else {
         jiveApi.attachPropsToReply(response.entity.id, {fromGitHub: true} ).then(function (response) {
             if (!response.success) {
                 jive.logger.error("Error attaching props to comment", response);
             }
         })
     }
 })
Example #23
0
 jive.tiles.findByDefinitionName('{{{TILE_NAME}}}').then(function(instances) {
     if (instances) {
         q.all(instances.map(processTileInstance)).then(function() {
             deferred.resolve(); //success
         }, function() {
             deferred.reject(); //failure
         });
     } else {
         jive.logger.debug("No jive instances to push to");
         deferred.resolve();
     }
 });
Example #24
0
function processTileInstance(instance) {
    jive.logger.debug('running pusher for ', instance.name, 'instance', instance.id);

    var dataToPush = {
        data: {
            "title": "Opportunities",
            "contents": null,
            "config": {
                "listStyle": "contentList"
            },
            "action": {
                "url": conf.clientUrl + "/sugarcrm/#Opportunities/create",
                "text": "Create an Opportunity"
                // ,
                // "context": {
                //     "url": conf.clientUrl + "sugarcrm/#Opportunities/create",
                //     "mode": "add"
                // }
            }
        }
    };
    //TODO externalize credentials
    sugar.getAccessToken("jim", "jim", function(token){
        sugar.get("/Opportunities", token, function(data, response){
            if (typeof data.records  === 'undefined') return;
            var records = data.records;
            var items = [];
            if (records) {
                records.forEach(function(record){
                    items.push(
                    {
                        text: record.name,
                        icon: "https://si0.twimg.com/profile_images/2027721183/Sugar_cube_RGB_180x180_bigger.png",
                        linkDescription: record.description,
                        // action: sugar.getDisplayUrl(record._module, record.id),
                        url: sugar.getDisplayUrl(record._module, record.id),
                        action: {
                            url: sugar.getDisplayUrl(record._module, record.id)
                            // {
                            //     id: record.id, 
                            //     module: record._module
                            // }
                        }                        
                    });
                });
                dataToPush.data.contents = items;
            }
            jive.tiles.pushData(instance, dataToPush);
        }, 5);
    });

    
}
Example #25
0
 jive.tiles.findByDefinitionName(GITHUB_PROJECT_INFO_TILE).then(function(instances) {
     if (instances) {
         q.all(instances.map(tileInstanceProcessor.processTileInstance)).then(function() {
             deferred.resolve(); //success
         }, function() {
             deferred.reject(); //failure
         });
     } else {
         jive.logger.debug("No jive instances to push to");
         deferred.resolve();
     }
 });
            instances.forEach( function( instance ) {
                jive.logger.debug('setting temperature and timestamp for ', instance.name, 'instance', instance.id );

                jive.tiles.pushData( instance, data ).then(
                    function(success) {
                    	console.log('Succesfully Updated Tile [ temperature : '+temperature+', timestamp='+timestamp+' ]');	
                    },
                    function(error) {
                    	console.log('Error Updating Config [ temperature : '+temperature+', timestamp='+timestamp+' ]');	                    	
                    }
                );	
            });
Example #27
0
 }).then(function(found) {
     if (found.length > 0) {
         var user = found[0].user;
         var pass = found[0].pass;
         fetchData(filter, user, pass, sort, function(data, filterName) {
             prepareData(tile, data, function(prepared) {
                 jive.tiles.pushData(tile, { data: prepared });
             }, filterName);
         });
     } else {
         jive.logger.warn("could not find auth creds");
     }
 });
Example #28
0
function processTileInstance(instance) {
    jive.logger.debug('running pusher for ', instance.name, 'instance', instance.id);

    var config = tile.config;

    github.getData( org, repo, types, config.ticketID, function(data) {

        //console.log("got data:", data)
        callback(data)
    });

    //jive.tiles.pushData(instance, dataToPush);
}
Example #29
0
exports.notifyNewGitHubHookInfo = function(eventType, eventData){
    if(eventType !== "ping"){
        //grab the webhookRecord for the repository
        var repo = repoHooks[eventData.repository.full_name];
        if(repo) {
            repo.events[eventType].handlers.forEach(function (handler) {
                //call each handler subscribed to the given event
                handler.handler(eventData);
            });
        }else{
            jive.logger.warn("Unregistered WebHook Handler for: " + eventData.repository.full_name + " is still configured on GitHub");
        }
    }
};
exports.notifyNewGitHubHookInfo = function(eventType, eventData){
    if(eventType == "ping"){

    }else{
        var repo = repoHooks[eventData.repository.full_name];
        if(repo) {
            repo.events[eventType].handlers.forEach(function (handler) {
                handler.handler(eventData);
            });
        }else{
            jive.logger.warn("Unregistered WebHook Handler for: " + eventData.repository.full_name);
        }
    }
};