I want to create an application that allows a user to join multiple video call rooms in kurento.
I wrote the following code:
function joinRooms() {
var userId = document.getElementById('expertid').value;
console.log("UserID = " + userId);
var roomIds = document.getElementById('roomids').value.split(",");//Assume that we have 2 rooms r1 & r2
var userIdAlias = [];
for (var i = 0; i < roomIds.length; i++) {
userIdAlias[i] = userId + "(" + i + ")";
console.log("User alias = " + userIdAlias[i]);
}
var wsUri = 'wss://' + location.host + '/room';
kurento = KurentoRoom(wsUri, function(error, kurento) {
if (error)
return console.log(error);
for (let i = 0; i < roomIds.length; i++) {
//console.log("Start loop Roomid = " + roomId);
rooms[i] = kurento.Room({
room : roomIds[i],
user : userIdAlias[i],
subscribeToStreams : true
});
localStreams[i] = kurento.Stream(rooms[i], {
audio : true,
video : true,
data : true
});
localStreams[i].addEventListener("access-accepted", function() {
var playVideo = function(stream) {
var participantId = stream.getParticipant().getID();
var userId = document.getElementById('expertid').value;
console.log("userId = " + userId + ", participantId = " + participantId);
if (!userIdAlias.includes(participantId)) {
var elementId = "video-" + stream.getGlobalID();
var div = document.createElement('div');
div.setAttribute("id", elementId);
document.getElementById("participants").appendChild(div);
stream.playThumbnail(elementId);
// Check color
var videoTag = document.getElementById("native-" + elementId);
var userId = stream.getGlobalID();
var canvas = document.createElement('CANVAS');
checkColor(videoTag, canvas, userId);
}
}
rooms[i].addEventListener("room-connected", function(){
var j = i;
return function(roomEvent) {
document.getElementById('room-header').innerText = 'ROOM \"'
+ roomIds[j] + '\"';
//document.getElementById('join').style.display = 'none';
document.getElementById('room').style.display = 'block';
localStreams[j].publish();
var streams = roomEvent.streams;
for (var streamsIdx = 0; streamsIdx < streams.length; streamsIdx++) {
playVideo(streams[streamsIdx]);
}
}
});
rooms[i].addEventListener("stream-added", function(streamEvent) {
playVideo(streamEvent.stream);
});
rooms[i].addEventListener("stream-removed", function(streamEvent) {
var element = document.getElementById("video-"
+ streamEvent.stream.getGlobalID());
if (element !== undefined) {
element.parentNode.removeChild(element);
}
});
playVideo(localStreams[i]);
rooms[i].connect();
});
localStreams[i].init();
}
});
}
However, the code does not work. The log in server said that there is only one user request to join room r2 but not r1.
I think the reason is Javascript works with too many asynchronous task so it worked incorrectly.
Can you give some advice about the way to joining multiple rooms in kurento?
Related
I am working on a telegram bot with the node-telegram-bot-api library. I made 2 buttons using keyboard. But when you click on them a lot, the bot will spam and sooner or later it will freeze. Is it possible to somehow put a delay for the user on messages.
if (text === '/start') {
return bot.sendMessage(chatId, 'hello', keyboardMain);
}
export const keyboardMain = {
reply_markup: JSON.stringify({
keyboard: [
[{
text: '/start',
},
],
resize_keyboard: true
})
};
You can create a user throttler using Javascript Map
/*
* #param {number} waitTime Seconds to wait
*/
function throttler(waitTime) {
const users = new Map()
return (chatId) => {
const now = parseInt(Date.now()/1000)
const hitTime = users.get(chatId)
if (hitTime) {
const diff = now - hitTime
if (diff < waitTime) {
return false
}
users.set(chatId, now)
return true
}
users.set(chatId, now)
return true
}
}
How to use:
You'll get the user's chatId from telegram api. You can use that id as an identifier and stop the user for given specific time.
For instance I'm gonna stop the user for 10seconds once the user requests.
// global 10 second throttler
const throttle = throttler(10) // 10 seconds
// in your code
const allowReply = throttle(chatId) // chatId obtained from telegram
if (allowReply) {
// reply to user
} else {
// dont reply
}
I tried using this code, put the function code in my function file, connected everything to the required file, and I don’t understand what to do next and where to insert the last code and what to do with it. I'm new to JavaScript and just learning.
import {
bot
} from '../token.js';
import {
throttler
} from '../functions/functions.js';
import {
keyboardMain
} from '../keyboards/keyboardsMain.js';
export function commands() {
bot.on('message', msg => {
const text = msg.text;
const chatId = msg.chat.id;
const throttle = throttler(10);
if (text === '/start') {
const allowReply = throttle(chatId) // chatId obtained from telegram
if (allowReply) {
return bot.sendMessage(chatId, 'hello', keyboardMain);
} else {
// dont reply
}
}
return bot.sendMessage(chatId, 'error');
});
}
Get the time when he pressed the button
Get the time of the next click
Take away the difference and set the condition (if, for example, more than 3 seconds have passed between clicks, then the user will not be frozen).
var token = ""; // FILL IN YOUR OWN TOKEN
var telegramUrl = "https://api.telegram.org/bot" + token;
var webAppUrl = ""; // FILLINYOUR GOOGLEWEBAPPADDRESS
var ssId = ""; // FILL IN THE ID OF YOUR SPREADSHEET
function getMe() {
var url = telegramUrl + "/getMe";
var response = UrlFetchApp.fetch(url);
Logger.log(response.getContentText());
}
function setWebhook() {
var url = telegramUrl + "/setWebhook?url=" + webAppUrl;
var response = UrlFetchApp.fetch(url);
Logger.log(response.getContentText());
}
function sendText(id,text) {
var url = telegramUrl + "/sendMessage?chat_id=" + id + "&text=" + text;
var response = UrlFetchApp.fetch(url);
Logger.log(response.getContentText());
}
function doGet(e) {
return HtmlService.createHtmlOutput("Hi there");
}
function doPost(e){
var data = JSON.parse(e.postData.contents);
var text = data.message.text;
var id = data.message.chat.id;
var msgbegan = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A7").getValue();
var msginfo = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A9").getValue();
var answer = "%0A" + msgbegan + "%0A" ;
///////////////////////
/*
* #param {number} waitTime Seconds to wait
*/
function throttler(waitTime) {
const users = new Map()
return (chatId) => {
const now = parseInt(Date.now()/1000)
const hitTime = users.get(chatId)
if (hitTime) {
const diff = now - hitTime
if (diff < waitTime) {
return false
}
users.set(chatId, now)
return true
}
users.set(chatId, now)
return true
}
}
// global 10 second throttler
const throttle = throttler(500) // 10 seconds
// in your code
const allowReply = throttle(chatId) // chatId obtained from telegram
if (allowReply) {
// reply to user
} else {
// dont reply
}
///////////////////////////////////////
if(text == "/start"){
sendText(id, answer);
} else if (text == "/info"){
sendText(id, msginfo);
}else{
if (text.length == 10){
var found = false;
var total_rows = SpreadsheetApp.openById(ssId).getSheets()[0].getMaxRows();
for(i=1; i<=total_rows; i++){
var loop_id = SpreadsheetApp.openById(ssId).getSheets()[0].getRange(i,2).getValue();
if(text == loop_id){
found = true;
found_at = i; // employee row
break;
}
}
if(found){
sendText(id, work_message);
}else{
var msgerrror = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A6").getValue();
var not_found = "%0A" + msgerrror+ "%0A" ;
sendText(id, not_found);
}
} else {
sendText(id, "eroor");
}
}
/////////////
var emp_name = SpreadsheetApp.openById(ssId).getSheets()[0].getRange(found_at,1).getValue();
var emp_work = SpreadsheetApp.openById(ssId).getSheets()[0].getRange(found_at,3).getValue();
var homeloc = SpreadsheetApp.openById(ssId).getSheets()[0].getRange(found_at,4).getValue();
var emp_location = SpreadsheetApp.openById(ssId).getSheets()[0].getRange(found_at,8).getValue();
var emp_data = SpreadsheetApp.openById(ssId).getSheets()[0].getRange(found_at,5).getValue();
var emp_day = SpreadsheetApp.openById(ssId).getSheets()[0].getRange(found_at,6).getValue();
var emp_clock = SpreadsheetApp.openById(ssId).getSheets()[0].getRange(found_at,7).getValue();
var emp_location = SpreadsheetApp.openById(ssId).getSheets()[0].getRange(found_at,8).getValue();
var welcome = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A2").getValue();
var msgemp = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A3").getValue();
var msgloc = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A4").getValue();
var msgbay = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A5").getValue();
var msghome = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A8").getValue();
var msmobil = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A11").getValue();
var mstoday = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A13").getValue();
var msdata = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A14").getValue();
var msclock = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A15").getValue();
var work_message = welcome + emp_name +
"%0A" + msgemp + emp_work +
"%0A" + mstoday + emp_day +
"%0A" + msdata + emp_data +
"%0A" + msclock + emp_clock +
"%0A" + msghome + homeloc +
"%0A" + msgloc+ emp_location +
"%0A" + msgbay +
"%0A" + msmobil ;
}
Excuse me . I am a beginner
Is this the correct way
i am currently trying to edit a pdf with hummus.js to replace certain placeholder characters in the pdf with others.
This works perfectly fine for almost every page, but for certain pages I get the following error:
TypeError:
pageObject.getDictionary(...).toJSObject(...).Contents.getObjectID is
not a function for:
const textObjectID = pageObject.getDictionary().toJSObject().Contents.getObjectID();
Whenever that error happens and it doesnt work,
pageObject.getDictionary().toJSObject().Contents returns a PDFArray {}, while, when it works, it returns an PDFIndirectObjectReference {}
Does anybody know how I could solve this issue or any other way to edit a pdf that way (replacing certain placeholder characters with others)
UPDATE 1: I can now differentiate between IndirectObjectReferences and arrays containing IndirectObjectReferences, but for some reason it removes all text but keeps the images from pdf pages which i access through these arrays, the rest of the pdf pages still work perfectly fine
async function replacetext(filePath, callback) {
var pageCount = 0;
const modPdfWriter = hummus.createWriterToModify(filePath+'.pdf', { modifiedFilePath: `${filePath}-modified.pdf`, compress: false })
const numPages = modPdfWriter.createPDFCopyingContextForModifiedFile().getSourceDocumentParser().getPagesCount()
var log="";
for (let page = 0; page < numPages; page++) {
const copyingContext = modPdfWriter.createPDFCopyingContextForModifiedFile()
const objectsContext = modPdfWriter.getObjectsContext()
const pageObject = copyingContext.getSourceDocumentParser().parsePage(page)
pageCount = pageCount + 1;
try
{
var replaceTextRight = " " + pageCount.toString();
if(pageCount > 9 && pageCount < 100)
{
replaceTextRight = " " + pageCount.toString();
}
else if(pageCount > 99)
{
replaceTextRight = " " + pageCount.toString();
}
const textStream = copyingContext.getSourceDocumentParser().queryDictionaryObject(pageObject.getDictionary(), 'Contents')
console.log(textStream);
if(textStream.toString() == 'Array')
{
let data = []
streamArray = textStream.toJSArray();
for(var i = 0; i<streamArray.length; i++)
{
var streamo = copyingContext.getSourceDocumentParser().queryArrayObject(textStream, i);
const readStream = copyingContext.getSourceDocumentParser().startReadingFromStream(streamo)
while (readStream.notEnded()) {
const readData = readStream.read(10000)
data = data.concat(readData)
}
var redactedPdfPageAsString = new Buffer.from(data).toString();
var replacedBuffer = replace(redactedPdfPageAsString, "12345", pageCount.toString());
log = log+" \n Replaced " +page +" with " + pageCount.toString();
var replacedBuffer = replace(replacedBuffer, "67890", replaceTextRight);
log = log+" \n Replaced " +page +" with " + replaceTextRight;
var textObjectID = streamArray[i].getObjectID();
objectsContext.startModifiedIndirectObject(textObjectID)
var stream = objectsContext.startUnfilteredPDFStream();
stream.getWriteStream().write(strToByteArray(replacedBuffer));
objectsContext.endPDFStream(stream);
objectsContext.endIndirectObject();
}
}
else
{
let data = []
const readStream = copyingContext.getSourceDocumentParser().startReadingFromStream(textStream)
while (readStream.notEnded()) {
const readData = readStream.read(10000)
data = data.concat(readData)
}
var redactedPdfPageAsString = new Buffer.from(data).toString();
var replacedBuffer = replace(redactedPdfPageAsString, "12345", pageCount.toString());
log = log+" \n Replaced " +page +" with " + pageCount.toString();
var replacedBuffer = replace(replacedBuffer, "67890", replaceTextRight);
log = log+" \n Replaced " +page +" with " + replaceTextRight;
const textObjectID = pageObject.getDictionary().toJSObject().Contents.getObjectID();
var content = pageObject.getDictionary().toJSObject().Contents;
objectsContext.startModifiedIndirectObject(textObjectID)
const stream = objectsContext.startUnfilteredPDFStream();
stream.getWriteStream().write(strToByteArray(replacedBuffer));
objectsContext.endPDFStream(stream);
objectsContext.endIndirectObject();
}
}
catch(e){
console.log(e);
}
}
fs.writeFile('C:\\Users\\Administrator\\Downloads\\PDFModifyDebugging\\PDFWRITELOG.txt', log, function (err) {
if (err) return console.log(err);
console.log('written in file');
});
modPdfWriter.end()
hummus.recrypt(`${filePath}-modified.pdf`, filePath)
callback();
}
Hey guys i am doing a message system all is working fine but now i want to add the thing that if the server crash and restart the message that have been send during this time will be send at the restart of the server. I am trying to save the information of the message in the client side and make a "waiting" system that will wait to a server response. So i wanted to know how can i do that "waiting" system because now i am doing like that :
while (socket.connected === false) {
}
But that make bug the client because the infinit loop is way too fast ... so is that possible to set a timer ? (i have already tried but i dind't find how to make a good timer in a loop).
Or maybe i am totaly wrong and i haven't to do a waiting system but an other thing so tell me if my technic will not work or if there is one better :)
So here is my code :
Client.js (startTchat is called when someone is connected)
(function($){
var socket = io.connect('http://localhost:1337');
var lastmsg = [];
var me_id = [];
var friend_ = [];
var conv_ = [];
var isPlace_ = [];
var isLocation_ = [];
var me_ = [];
var my_id;
startTchat = function(user_id, username, friend_id, conv_id, isPlace, isLocalisation) {
my_id = user_id;
socket.emit('login_chat', {
id : user_id,
username : username,
friend : friend_id,
conv : conv_id,
isPlace : isPlace,
isLocalisation : isLocalisation,
})
};
/**
* Error
*/
socket.on('error', function(err){
alert(err);
});
/**
* Messages
*/
$('#chat_form').submit(function(event){
var a = 0;
while (socket.connected === false) {
}
event.preventDefault();
console.log('ME', my_id, 'TAB', me_id);
socket.emit('new_msg', {message: $('#message').val() }, me_id[my_id], friend_[my_id], conv_[my_id], isPlace_[my_id], isLocation_[my_id], me_[my_id]);
if (a === 1) {
console.log('HEYYYYYYYYYY', my_id);
}
$('#message').val('');
$('#message').focus();
});
socket.on('new_msg', function(message, me, id_receiver, id_transmiter){
if (me.id === id_receiver || me.id === id_transmiter) {
if (lastmsg != message.user.id) {
$('#new_message').append('<span class="time_date"> ' + message.h + ' : ' + message.m + ' | ' + message.y + '-' + message.m + '-' + message.d + ' | ' + message.user.username + '</span>'
+ '<p>' + message.message + '</p>\n'
);
lastmsg = message.user.id;
} else {
$('#new_message').append('<p>' + message.message + '</p>'
);
}
}
});
/**
* Login
*/
socket.on('new_user', function(user, friend, conv, isPlace, isLocation){
me_id[user.id] = user.id;
friend_[user.id] = friend;
conv_[user.id] = conv;
isPlace_[user.id] = isPlace;
me_[user.id] = user;
isLocation_[user.id] = isLocation;
$('#new_user').append('<div class="chat_list active_chat" id="' + user.id + '">\n' +
' <div class="chat_people">\n' +
' <div class="chat_img"> <img src="https://ptetutorials.com/images/user-profile.png" alt="sunil"> </div>\n' +
' <div class="chat_ib">\n' +
' <h5>' + user.username + ' <span class="chat_date">Id : ' + user.id + '</span></h5>\n' +
' </div>\n' +
' </div>\n' +
' </div>');
});
/**
* Disconnect
*/
socket.on('disc_user', function(user){
$('#' + user.id).remove();
})
})(jQuery);
And server.js :
var http = require('http');
var MongoClient = require('mongodb').MongoClient;
// Connection URL
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = 'msg';
MongoClient.connect(url, function(err, client) {
if (err)
throw err;
console.log('MongoDB connected ...');
httpServer = http.createServer(function(req, res) {
console.log('This is a test');
res.end('Hello World');
});
httpServer.listen(1337);
var io = require('socket.io').listen(httpServer);
var users = {};
var messages = [];
io.sockets.on('connection', function (socket) {
const collection = client.db(dbName).collection('MessageUser');
var me = false;
var friend = false;
var conv = false;
var isPlace = false;
var room = false;
var isLocalisation = false;
for(var k in users) {
socket.emit('new_user', users[k]);
}
/**
* Login
*/
socket.on('login_chat', function (user) {
me = user;
friend = user.friend;
isPlace = user.isPlace;
conv = user.conv;
isLocalisation = user.isLocalisation;
if (isPlace === 0) {
room = user.conv;
} else {
room = user.conv + '-Place';
}
socket.join(room);
//console.log('New user : ', me.username, ' - id : ', me.id);
users[me.id] = me;
io.sockets.emit('new_user', me, friend, conv, isPlace, isLocalisation);
});
/**
* Disconnect
*/
socket.on('disconnect', function() {
if (!me) {
return false;
}
delete users[me.id];
io.sockets.emit('disc_user', me);
});
/**
* Message receive
*/
socket.on('new_msg', function(message, me_id, friend_, conv_, isPlace_, isLocalisation_, me_){
if (message.message !== '') {
message.user = me;
date = new Date();
message.h = date.getHours();
message.m = date.getMinutes();
message.y = date.getFullYear();
message.m = date.getMonth();
message.d = date.getDate();
console.log(message);
messages.push(message);
msg = {};
msg.content = message.message;
msg.sendAt = new Date();
msg.idTransmitter = me.id;
if (isPlace === 0) {
msg.idReceiver = friend;
} else {
msg.idReceiver = conv;
}
msg.idConversation = conv;
msg.isPlace = isPlace;
msg.isLocalisation = isLocalisation;
collection.insertOne(msg);
console.log('---1---', msg.idReceiver, '---2---', msg.idTransmitter, '---3---', me);
io.to(room).emit('new_msg', message, me, msg.idReceiver, msg.idTransmitter);
}
});
});
});
ps : Tell me if you need more info, sorry if i forget something that my first time using js, node and socket.io :)
while (socket.connected === false) {
}
Don't do that, it will block your page and hold your processor to 100%.
Instead, use setTimeout. It's the equivalent of sleep in javascript. You need to refactor your code to call setTimeout in a recursive fashion, and count the number of "retries" (if you want to stop at some point).
Code:
$('#chat_form').submit(function(event){
var retries = 0, max_retries = 10;
function tryNewMessage() {
if (socket.connected === false) {
if (retries >= max_retries) return; //handle max_retries properly in your code
//this is where you sleep for 1 second, waiting for the server to come online
setTimeout(tryNewMessage, 1000);
retries++;
}
else {
var a = 0;
event.preventDefault();
console.log('ME', my_id, 'TAB', me_id);
socket.emit('new_msg', {message: $('#message').val() }, me_id[my_id], friend_[my_id], conv_[my_id], isPlace_[my_id], isLocation_[my_id], me_[my_id]);
if (a === 1) {
console.log('HEYYYYYYYYYY', my_id);
}
$('#message').val('');
$('#message').focus();
}
}
tryNewMessage();
});
I have the following code which reads information from a sharepoint list and renders fine in google chrome, but when tested in IE 11 (Corporate Browser), then I get the following exception:
ReferenceError: 'Promise' is undefined
at getContentTypeOfCurrentItem (https://ourserver.com/sites/billing/Style%20Library/xxx/Angular/related-billing-documents-controller.js:209:5)
at addContentType (https://ourserver.com/sites/billing/Style.com/sites/billing/Style%20Library/xxx/Angular/related-billing-documents-controller.js:201:5)
at Anonymous function (https://ourserver.com/sites/billing/Style%20Library/xxx/Angular/related-billing-documents-controller.js:163:7)
at Anonymous function (https://ourserver.com/sites/billing/Style%20Library/xxx/Angular/angular.min.js:130:399)
at m.prototype.$eval (https://ourserver.com/sites/billing/Style%20Library/xxx/Angular/angular.min.js:145:96)
at m.prototype.$digest (https://ourserver.com/sites/billing/Style%20Library/xxx/Angular/angular.min.js:142:165)
at Anonymous function (https://ourserver.com/sites/billing/Style%20Library/xxx
(function () {
angular
.module('BillCycleApp')
.controller('relatedBillingDocumentsController', ['$scope', '$log', '$q', 'spService', 'BillingDocuments', 'General',
function ($scope, $log, $q, spService, config, generalConfig) {
var vm = this;
var tableSelector = "#related-billing-documents-table";
var componentSelector = ".related-billing-documents";
function GetContext() {
vm.Name = config.Name;
var dataTableColumns = spService.TransformFieldsToDataTableColumns(config.FieldsToShow);
$.fn.dataTable.moment( generalConfig.DateTimeFormat );
// Initialize with empty data
$(tableSelector).DataTable({
data : [],
columns : dataTableColumns,
order : config.SortOrder,
deferRender : true
}).on( 'draw.dt', function ( e, settings, processing ) {
// Make sure the UserPresence is added every time the DataTable's data changes (paging, sorting, search,..)
spService.UserPresenceComponent.AddPresence();
});
// Make component visible
$(componentSelector).css("visibility", "visible");
// SP.js function
// Get Bill Cycle list & id
var listItemId = GetUrlKeyValue('ID', true, window.location.search, true);
var listId = "{" + GetUrlKeyValue('List', true, window.location.search, true) + "}";
var propertiesToLoad = ["FileRef","PwC_ClientCode","PwC_JobCodesMulti","PwC_EngagementCode"];
spService.GetListItem(listId, listItemId, propertiesToLoad)
.then(function(billCycle) {
var listItemValues = [];
propertiesToLoad
.forEach(function(propertyName) {
var value = billCycle.get_item(propertyName);
listItemValues[propertyName] = value;
});
var billCyclePath = _spPageContextInfo.siteAbsoluteUrl;
billCyclePath += listItemValues["FileRef"];
var clientCode = listItemValues["PwC_ClientCode"]
var jobCodesLookups = listItemValues["PwC_JobCodesMulti"];
var engagementCode = listItemValues["PwC_EngagementCode"]
var jobCodes = [];
if(jobCodesLookups) {
jobCodesLookups.forEach(function(lookup) {
jobCodes.push(lookup.get_lookupValue());
});
}
// Get data with parameters
GetData(billCyclePath, clientCode, jobCodes, engagementCode);
});
}
function GetData(billCyclePath, clientCode, jobCodes, engagementCode) {
var enhanceFunctions = [
function(searchResultRow) {
return spService.AddHyperLinkOnFields(searchResultRow, config.HyperLinks);
},
function(searchResultRow) {
return spService.AddPresenceOnFields(searchResultRow, config.UserFields);
},
function(searchResultRow) {
return spService.FormatDateFields(searchResultRow, config.DateFields, generalConfig.DateTimeFormat);
},
function(searchResultRow) {
return spService.AddImageMapping(searchResultRow, config.ImageFields);
},
function(searchResultRow) {
return spService.FormatNumberFields(searchResultRow, config.NumberFields);
},
function(searchResultRow) {
// Put link to parent Bill Cycle with name = folder name
//var parentLink = searchResultRow["FileRef"];
//arrayofstrings = parentLink.split("/");
//var billCycleFolderName = arrayofstrings[arrayofstrings.length-2];
//arrayofstrings.pop();
//var hyperLink = '' + billCycleFolderName + '';
//searchResultRow["Bill Cycle"] = hyperLink;
}
];
// Get data from SP
var selectProperties = spService.TransformFieldsToSelectProperties(config.Fields); // copy array
var selectPropertiesToShow = spService.TransformFieldsToSelectProperties(config.FieldsToShow); // copy array
var extendedSelectProperties = selectProperties.slice();
var hyperLinkedProperties = spService.TransformFieldsToSelectProperties(config.HyperLinks)
extendedSelectProperties = extendedSelectProperties.concat(hyperLinkedProperties);
GetRelatedBillingDocumentsFromList(extendedSelectProperties, billCyclePath, clientCode, jobCodes, engagementCode, enhanceFunctions)
.then(function (data) {
var trimmedData = spService.SpSearchQuery.TrimSearchResultsToSelectProperties(data, selectPropertiesToShow);
// Add data to dataTable
var dataTable = $(tableSelector).DataTable();
dataTable.clear().rows.add(trimmedData).columns.adjust().draw(); // Resize columns based on new data sizes
vm.ValidDataLoaded = true;
})
.catch (function (message) {
vm.Name = "Error";
vm.ValidDataLoaded = true;
});
}
function GetRelatedBillingDocumentsFromList(selectProperties, currentBillCyclePath, clientCode, jobCodes, engagementCode, enhanceFunctions) {
$log.info("Retrieving related billing documents for bill cycle with name [" + currentBillCyclePath + "]");
var deferred = $q.defer();
var webUrl = _spPageContextInfo.webAbsoluteUrl;
selectProperties = selectProperties.concat("ContentTypeId");
var viewFields = spService.ConvertSelectPropertiesToViewFields(selectProperties);
// query must return the documents for the same client but in other bill cycles not the current one
var camlQuery = '<View Scope="RecursiveAll">' + viewFields +
'<Query>' +
'<Where>' +
'<And>' +
'<Eq>' +
'<FieldRef Name="PwC_ClientCode" />' +
'<Value Type="Text">'+ clientCode + '</Value>' +
'</Eq>' +
'<Neq>' +
'<FieldRef Name="ContentType" />' +
'<Value Type="Computed">Bill Cycle</Value>' +
'</Neq>' +
'</And>' +
'</Where>' +
'</Query>' +
'</View>';
var billCyclesListId = "{c23bbae4-34f7-494c-8f67-acece3ba60da}";
spService.GetListItems(billCyclesListId, camlQuery, selectProperties)
.then(function(listItems) {
var listItemsWithValues = [];
if(listItems) {
var enumerator = listItems.getEnumerator();
var promises = [];
while (enumerator.moveNext()) {
var listItem = enumerator.get_current();
var listItemValues = [];
selectProperties
.forEach(function(propertyName) {
var value = listItem.get_item(propertyName);
if(propertyName === "PwC_JobCodesMulti"){
jobvalue = "";
value.forEach(function(jobvalues){
jobvalue+= jobvalues.get_lookupValue() +";";
})
listItemValues[propertyName] = jobvalue;
}else{
listItemValues[propertyName] = value;
}
});
listItemsWithValues.push(listItemValues);
}
var promises = listItemsWithValues.map(addContentType);
Promise.all(promises).then(youCanUseTheData);
function youCanUseTheData(){
/*
At this point, each listItem holds the 'Document Type' info
*/
listItemsWithValues.forEach(function(listItem) {
var fileDirRef = listItem["FileRef"];
var id = listItem["ID"];
var title = listItem["Title"];
var serverUrl = _spPageContextInfo.webAbsoluteUrl.replace(_spPageContextInfo.webServerRelativeUrl,"");
var dispFormUrl = serverUrl + "/sites/billing/_layouts/15/DocSetHome.aspx?id="+fileDirRef;
var parentLink = listItem["FileRef"];
arrayofstrings = parentLink.split("/");
var billCycleFolderName = arrayofstrings[arrayofstrings.length-2];
arrayofstrings.pop();
var hyperLink = '' + billCycleFolderName + '';
listItem["Bill Cycle"] = hyperLink;
listItemsWithValues["Document Type"] = getContentTypeOfCurrentItem(listItem.ID.toString());
});
var enhancedListItemValues = spService.SpSearchQuery.EnhanceSearchResults(listItemsWithValues, enhanceFunctions);
deferred.resolve(listItemsWithValues);
}
}
})
.catch (function (message) {
deferred.reject();
});
return deferred.promise;
}
function addContentType(listItem){
//return getContentTypeOfCurrentItem(listItem.ID.toString());
return getContentTypeOfCurrentItem(listItem.ID.toString()).then(function(cname) {
listItem['Document Type'] = cname; //we add the doc type to each listItem, not only the last one
}).catch(function(error) {
$log.warn("Server error");
});
}
function getContentTypeOfCurrentItem(id) {
return new Promise(function (resolve, reject) {
var clientContext = new SP.ClientContext.get_current();
var oList = clientContext.get_web().get_lists().getByTitle("Bill Cycles");
var listItem2 = oList.getItemById(id);
listContentTypes = oList.get_contentTypes();
clientContext.load(listContentTypes);
clientContext.load(listItem2, 'ContentTypeId');
clientContext.executeQueryAsync(
function() {
$log.info("Successfully retrieved getContentTypeOfCurrentItemt");
var ctid = listItem2.get_item("ContentTypeId").toString();
var ct_enumerator = listContentTypes.getEnumerator();
while (ct_enumerator.moveNext()) {
var ct = ct_enumerator.get_current();
if (ct.get_id().toString() == ctid) {
var contentTypeName = ct.get_name();
}
}
return resolve(contentTypeName);
},
function(error, errorInfo) {
$log.warn("Retrieving getContentTypeOfCurrentItem failed");
return reject(errorInfo);
}
);
});
}
function GetRelatedBillingDocuments(selectProperties, currentBillCyclePath, clientCode, jobCodes, engagementCode, enhanceFunctions) {
$log.info("Retrieving related billing documents for bill cycle with path [" + currentBillCyclePath + "]");
var deferred = $q.defer();
var webUrl = _spPageContextInfo.webAbsoluteUrl;
// TODO: AND or OR?
var jobCodesFilter = spService.ExpandSearchFilterForEachValue("JobCodes", ":", jobCodes, false, false);
var engagementCodeFilter = "";
if (engagementCode != undefined && engagementCode != "") {
engagementCodeFilter = "EngagementCode:" + engagementCode;
}
if(jobCodesFilter && engagementCodeFilter) {
jobCodesFilter += " OR ";
}
// TODO: Add use of result source?
var queryText = "-Path:" + spService.AddQuotes(currentBillCyclePath) + ' AND -ContentType:"Bill Cycle" AND ClientCode:' + clientCode + " AND (" + jobCodesFilter + engagementCodeFilter + ")";
var searchQuery = new spService.SpSearchQuery(webUrl, queryText, selectProperties, config.ResultSourceName, config.ResultSourceLevel);
searchQuery
.ExecuteSearchQueryFetchAll() // returns deferred
.then(function (results) {
$log.info("Successfully retrieved search results");
var searchResults = spService.SpSearchQuery.EnhanceSearchResults(results, enhanceFunctions);
deferred.resolve(searchResults);
});
return deferred.promise;
}
ExecuteOrDelayUntilScriptLoaded(GetContext, 'sp.js');
}
]); // End Controller()
}()); // End IFFE
Promise is part of ES6 standard that is not fully supported by IE11, you can use babel-polyfill instead or use another librairy like q which is part of angularjs
I am trying to get and display Total Sent, Total Success and Total Error using AngularJs. So far, I have been able to retrieve the information Total Sent, Total Success and Total Error inside the code. However, I am not convinced that the approach (using global variables) I have taken to bind and display those status is correct.
Here are my controller and associated services.
var sent = 0;
var succ = 0;
var err = 0;
myApp.service('ParseMessageService', function() {
this.myFunc = function(message) {
var res = message.match(/Success/g);
if (res !== null) {
//console.log(res);
TSent = message.match(/Total Sent: (\d+)/);
if (TSent) {
sent = TSent[1];
//parsedMsg.push(TSent[1]);
//console.log(TSent[1]); //replace with $scope and display on Gui
}
TSucc = message.match(/Total Success: (\d+)/);
if (TSucc) {
succ = TSucc[1];
//parsedMsg.push(TSucc[1]);
// console.log(TSucc[1]); //replace with $scope and display on Gui
}
TErr = message.match(/Total Errors: (\d+)/);
if (TErr) {
err = TErr[1];
//parsedMsg.push(TErr[1]);
//console.log(TErr[1]); //replace with $scope and display on Gui
}
}
}
//}
});
myApp.factory('WebSocketService', function() {
var service = {};
service.connect = function() {
if (service.ws) {
return;
}
var ws = new WebSocket("ws://127.0.0.1:8000");
ws.onopen = function() {
service.callback("Succeeded to open a connection");
//display webSocket connected status
};
ws.onerror = function() {
service.callback("Failed to open a connection");
}
ws.onmessage = function(message) {
service.callback(message.data);
};
service.ws = ws;
}
service.send = function(message) {
service.ws.send(message);
}
service.subscribe = function(callback) {
service.callback = callback;
}
return service;
});
angular.module('myApp')
.controller('PingTestController', function($scope, WebSocketService, ParseMessageService) {
$scope.messages = [];
$scope.TSent = [];
$scope.TSucc = [];
$scope.TErr = [];
$scope.parsedSent = 0;
$scope.parsedSucc =0;
$scope.parsedErr =0;
$scope.pingStr = "Ping"
$scope.define = "Definitions";
$scope.url = "www.google.com"
$scope.size = "1";
$scope.TTL = "10"
$scope.pause = "3";
$scope.paraStr = "[,]";
$scope.cmdStartStr = "[;]";
($scope.trueStr) = "TRUE";
($scope.falseStr) = "FALSE";
($scope.PfalseStr) = "False";
($scope.cmdEndStr) = "[/]";
//($scope.newLineStr) = "\r\n";
($scope.startCmd) = "Start";
($scope.stopCmd) = "Stop";
($scope.clearCmd) = "Clear";
$scope.updatePing = function() {
$scope.pingCmd = ($scope.cmdStartStr) + ($scope.pingStr) +
($scope.cmdStartStr) + ($scope.define) + ($scope.cmdStartStr) +
($scope.url) + ($scope.paraStr) + ($scope.PfalseStr) + ($scope.paraStr) +
($scope.TTL) + ($scope.paraStr) +
($scope.size) + ($scope.paraStr) +
($scope.pause) + ($scope.cmdEndStr);
}
WebSocketService.subscribe(function(message) {
ParseMessageService.myFunc(message);
$scope.parsedSent = (sent);
$scope.parsedSucc = (succ);
$scope.parsedErr= (err);
$scope.messages.push(message);
$scope.$apply();
});
$scope.connect = function() {
WebSocketService.connect();
}
$scope.send = function() {
WebSocketService.send($scope.pingCmd);
$scope.text = "";
}
//[;]Ping[;]Stop[;]TRUE[/]
$scope.stopPing = function() {
$scope.pingStop = ($scope.cmdStartStr) + ($scope.pingStr) +
($scope.cmdStartStr) + ($scope.stopCmd) + ($scope.cmdStartStr) +
($scope.trueStr) + ($scope.cmdEndStr);
WebSocketService.send($scope.pingStop);
}
// [;]Ping[;]Start[;]TRUE[/]
$scope.startPing = function() {
$scope.pingStart = ($scope.cmdStartStr) + ($scope.pingStr) +
($scope.cmdStartStr) + ($scope.startCmd) + ($scope.cmdStartStr) +
($scope.trueStr) + ($scope.cmdEndStr);
WebSocketService.send($scope.pingStart);
}
// [;]Ping[;]Clear;]TRUE[/]
$scope.clearPing = function() {
$scope.pingClear = ($scope.cmdStartStr) + ($scope.pingStr) +
($scope.cmdStartStr) + ($scope.clearCmd) + ($scope.cmdStartStr) +
($scope.trueStr) + ($scope.cmdEndStr);
WebSocketService.send($scope.pingClear);
}
});
Here is relevant part of html code.
<br/>
<button ng-click="send()" class="btn"> Add new Ping</button>
<button ng-click="startPing()" class="btn"> StartPing</button>
<button ng-click="stopPing()" class="btn">Stop Ping</button>
<button ng-click="clearPing()" class="btn">Clear Ping</button>
<br />
<div ng-repeat = "message in messages track by $index">
{{parsedSent}} {{parsedSucc}} {{parsedErr}}
</div>
Eventually, I would like to have a clean way to get those statistics and display with on a webpage i.e. Total success with green background, Total Error with Red and Total Sent with Blue background.
You can move the global variables to the service an use them from there. You could also use this answer: Static javascript variable to be used as counter in Angularjs controller