This was a triumph.
I'm making a note here: HUGE SUCCESS.

Search This Blog

Wednesday, March 5, 2014

Live notifications from new items in lists/libraries to which current user is subscribed, using JavaScript in SharePoint 2013

Warning! Long post! 
Screenshots can be found at the end of the post. Take your time to read everything.
----------------

So the past six days I've been working on a notification script for our SharePoint intranet.
At first I didn't even know where to start, so I asked a question on Stack Exchange. After getting some inspiration from the answers I received (thanks you guys!) I decided I should just give it a try.

I wanted a script that would show a notification in the top right corner of the page whenever a new item was added to a certain list or library.
I also wanted to give users the ability to "subscribe" to a list or library, and hence let them see only notifications whenever a new item was added to a list or library to which they were subscribed, so I also made a script to handle the subscribing.

These are the two scripts I've written: notification.js and subscribe-to-list-or-library.js.
Both scripts are working in the latest versions of Google Chrome, Mozilla Firefox and Internet Explorer.

Since I don't want to put too much comments in the code, I just decided to explain both scripts first and then provide you with the code. So please take some time to read how these scripts work and what steps they contain, and then take a look at the code. It will be a lot easier to understand the code when you read the explanation about it first.

Script: subscribe-to-list-or-library.js

This script has the following features:
  • subscribe to a list or library by clicking a button named "subscribe"
  • unsubscribe from a list or library by clicking a button named "unsubscribe"
  • be subscribed to multiple lists or libraries
  • receive live notifications whenever a new item was added to one or more lists or libraries to which a user is subscribed
Do note that it's possible to subscribe to a list or library from any sub site. So for example, you can subscribe to list X on sub site A, and library Y on sub site B, and receive notifications from list X and library Y while browsing content on sub site C. I tried explaining this as easy as I could, so there you have it.
Also, regarding the buttons: there is no such thing as a button to subscribe and another button to unsubscribe. They are one and the same button. Actually it's not even a button. It's a div element disguised as a button. I just change the text inside the div based on whether or not a user is subscribed. If a user is, then the text in the div will be "unsubscribe". If a user is not, then it will be "subscribe". Simple as that.

Steps on how this script works

First of all, you need to provide a button (a div, actually, but I'll call it a button) on a page that has a web part of a list or library.  The button contains two other elements, one div that will hold either the text "subscribe" or "unsubscribe", and one hidden div that will hold the name of the list or library a user should be able to subscribe to. This name has to be correct and is case sensitive.
And now for the steps. Keep in mind that part of the script runs as soon as the page has loaded, and certain functions only run on the click of a button.

On page load:
  • Find all elements that have a class named "subscrButton" (these are the subscribe buttons), and for each element, store the name of the list/library in a variable, as well as the text from the first div (which contains either "subscribe" or "unsubsribe").
  • Still in the "for each" statement: get all list items from a list named "Subscribed users", and for each row in that list, check if the current user is in that row and if he/she is subscribed to a list/library with the same name as the one stored in a variable.
    • If true, set a boolean named "inList" to true.
    • If false, set a boolean named "inList" to false.
  • If the boolean named "inList" is false, then set the innerHTML of the first div to "subscribe".
  • If the boolean named "inList" is true, then set the innerHTML of the first div to "unsubscribe".
So that part of the code is only to check whether or not a user is already subscribed to a list or library, and set the correct text to the button.Next comes the actual subscribe/unsubscribe functionality.

On button click:
  • Store the name of the list or library linked to that button, in a variable.
  • Store the name of the page on which the user clicked the button, in a variable.
  • Store the path to the sub site in which the page with the button that the user clicked on is located, in a variable.
  • Store the text of the button ("subscribe" or "unsubscribe") in a variable.
  • If the text of that variable equals "unsubscribe":
    • Set the innerHTML of the button that was clicked to "subscribe".
    • Check the "Subscribed users" list and look for the row that contains both the name of the user and the name of the list/library from which the users wants to unsubscribe.
      • If the row has been found, set another variable named "listIDDel" to the ID of the current row that matches the name of the user and the name of the list/library.
    •  Update the "Subscribed users" list by deleting the row that has the id matching "listIDDel" (and thus, removing the user from the "Subscribed users" list).
    • After the user has successfully been deleted from the "Subscribed users" list, run some functions named "runInOtherFile" and "runDeleteInOtherFile" which are both located in notification.js. I'll explain the use of these later.
  • If the text of that variable equals "subscribe":
    • Set the innerHTML of the button that was clicked to "unsubscribe".
    • Update the "Subscribed users" list by making a new item with the following values: the name of the user, name of the list/library, url of the page, path to the sub site.
    • After the user has successfully been added to the "Subscribed users" list, run a function named "runInOtherFile" which is located in notification.js. I'll explain the use of this one later.

Script: notification.js

This script has the following features:
  • Send a notification whenever a new item was added to a list or library to which a user is subscribed

A minor down side: the script does not keep track of which items were added to certain lists or library since the last time a user logged on. So it's not possible to store notifications somewhere about new items and greet a user with a list of all the new items that were added since the last time he/she logged in. This script is for live notifications, nothing else.

It also won't show a globe with a number on top of it saying "you have x new notifications" like on Facebook, I'm not keeping track of that. While I might be able to add such functionality to this script, this will be for another time.

Steps on how this script works

The script will contain two types of code. One that will run only on page load, and one that will run every five seconds.

On page load:
  • Check the "Subscribed users" list and look for rows that contain both the name of the user and the name of any list/library to which a user is subscribed.
    • For each row in that list: check if the user is in the row. If he/she is, raise the value of a counter by 1 and push the current row to an array. We then push the content of that array to another array, which will act as a container array (multidimensional array, actually).
  • If the counter equals 0, meaning no rows matching the current user were found, nothing will happen and the notification script will stop.
  • If the counter is not 0, meaning one or more occurences of the current user were found in the "Subscribed users" list, we will do a loop. For each item in the multidimensional array:
    • Store a unique session in the session.
    • Set an interval of five seconds for a function named "repeatEvery5Seconds".
Every five seconds:
  • The function "repeatEvery5Seconds" will run for each item in the multidimensional array, storing the following values in variables: the name of the user, name of the list/library, url of the page, path to the sub site, name of the session item. 
  • The function "repeatEvery5Seconds" will trigger another function named "fetchCurrentListStatus". 
    • The function "fetchCurrentListStatus" will check each list or library to which a user is subscribed to, and push each row to an array.
      • If the length of the array is null or 0, the list will be considered empty and an empty session variable will be set.
      • If the length of the array is not null or not 0:
        • If there is a session item present for the current list and if that session item is not empty, then reset that session item to a new value matching the array and run a function named "itemChange".
        • Else if there is a session item present for the current list and if that session item is null or 0, then reset the session item to a new value matching the array and run a function named "itemChange". 
        • If the length of the array matches the length of the session item, then that indicates no changes were made.
    • The function "itemChange" will run when called.
      • If the length of the array is smaller than the length of the session item, then this means that an item was deleted from the list/library. The session item will then be updated, and will contain the same value as the array.
      • Else if the length of the array is larger than the length of the session item, then this means that a new item was added to the list/library.
        • We will then compare all elements in the array with all elements in the session item, and if we find the one that is not present in the session storage, we will search for that item in the list/library and fetch its name. 
          • We then create a div that will be our notification, and we will give it a text containing the name of the new item and a link to the page on where the user can find it. After five seconds, the notification will be removed.
        • We then check if the session item matches the array. If not, set the session item to match the value of the array. 
Only when called by "subscribe-to-list-or-library.js": 
  • The function "runInOtherFile":
    • Will run with a timeout of one second, and will replace the array that was made on page load and that holds the list of all the lists/libraries to which a user is subscribed. Since the user decided to unsubscribe from a list/library, this array needs to be updated. This function will do so be checking the "Subscribed users" list again.
  • Yhe function "runDeleteInOtherFile":
    • For each item (array) in the multidimensional array, check if there is an item that matches the name of the list from which the user wanted to subscribe. If there is, then find the corresponding session item and set its value to nothing. And then we will remove the item from the multidimensional array (by using the split function).

There you have it. That was just the explanation about the scripts. I tried to write it as short as possible. Nest step: setting up the necessary lists and buttons.

Prerequisites 

Before you can actually use the scripts, you'll need to set up some things first. Like a list where you will store your subscribed users, and buttons for each list/library you want to have your users subscribe to.

Create a list for your subscribers

You need to make a simple list at the top site level named "Subscribed users". If you want my code to work straight away, then I suggest you use that name.

Your will then need to make three new columns for your list: ListLibID, PageURL and SubsiteURL. I originally used to store the GUID of a list/library in the ListLibID column, but after several problems with that in different browsers I decided to just use the name of a list or library instead of the GUID. That was also the main reason on why I also needed a column to save the subsite in (required to call the list across sub sites).

Make sure your list named "Subscribed users" is allowed to be edited by everyone, meaning everyone should have edit permissions. You can change the settings of the view of the list so that it is only visible to you or not visible at all (use the filter for this, set some impossible filter so no item will ever be shown but will still be present in the list).That way you can avoid users sneaking around and trying to meddle with the list. I just used CSS to hide that particular list and the list itself from the site content, so nobody ever finds it.

Create buttons for your lists/libraries

Now that you have your list ready, it is time to make some buttons. You'll only need to make these for list or libraries of which you want users to be able to subscribe to.

On the page that holds the web part of the list/library of which users should be able to subscribe to, place the following code directly above the code from the web part:
<div class="buttonContainer">
   <div class="subscrButton">
      <div class="subscrButtonTitle"></div>
      <div class="innerSubscr" style="display: none;">
         List or library name here​​
      </div>
   </div>
</div>

In case you want it, here's the CSS of the button above (note: not identical to the style as seen in screenshots!):
.buttonContainer {
 position: relative;
}
.subscrButton {
 background-color: white;  
 border: 1px solid rgb(185, 184, 184);
 font-family: "Segoe UI Semilight","Segoe UI","Segoe", Tahoma,
               Helvetica,Arial,sans-serif;
 color: #0066CC;
 text-align: center;
 z-index: 100;
 position: absolute;
 right: 0;
 padding: 3px 10px 5px 10px;
 -webkit-border-radius: 5px;
 -moz-border-radius: 5px;
 border-radius: 5px;
 opacity: 0.8;
}

Add references to the scripts

I suggest you just put a reference to the scripts in your master page. For example:
<!--SPM:<sharepoint:scriptlink id="scriptLink12" language="javascript" 
 localizable="false"  ondemand="false" runat="server"
 name="~sitecollection/Style Library/Scripts/subscribe-to-list-or-library.js">
-->
<!--SPM:<sharepoint:scriptlink id="scriptLink13" language="javascript" 
 localizable="false" ondemand="false" runat="server"
 name="~sitecollection/Style Library/Scripts/notification.js">
-->

Make sure your master page and your scripts are checked in.

Now, for the most interesting part, the actual code.

The code

subscribe-to-list-or-library.js

SP.SOD.executeOrDelayUntilScriptLoaded( 'SP.UserProfiles.js', 
   "~sitecollection/Style%20Library/Scripts/jquery.SPServices-2013.01.min.js");
SP.SOD.executeFunc('SP.js', 'SP.ClientContext');

var firstDiv;
var inList = new Boolean(); 
inList = false;
var listIDDel;
var SURL = $().SPServices.SPGetCurrentSite();
var PURL = window.location.pathname;
var LLID;
var USER = $().SPServices.SPGetCurrentUser({ 
 webURL: "", 
 fieldName: "Title", 
 fieldNames: {}, 
 debug: false
});

$("#content").find($("div.subscrButton")).each(function(){
 LLID = this.childNodes[1].innerHTML.replace(/[\u200B]/g, ''); 
 firstDiv = this.childNodes[0].innerHTML.replace(/[\u200B]/g, '');
 $().SPServices({
  operation: "GetListItems",
  async: false,     
  webURL: 'https://your-site-here.com/',
     listName: 'Subscribed users',
  completefunc: function (xData, Status) {
   $(xData.responseXML).find("z\\:row, row").each(function() {
    if (($(this).attr("ows_Title") == USER) 
        && ($(this).attr("ows_ListLibID") == LLID)) {
     inList = true;
    }
   });
  }
 });

 if (inList == false) {
  this.childNodes[0].innerHTML = 'SUBSCRIBE';
 }
 else if (inList == true) {
  this.childNodes[0].innerHTML = 'UNSUBSCRIBE';
  inList = false;
 }
});

$("div.subscrButton").click(function(){ 
 LLID = this.childNodes[1].innerHTML.replace(/[\u200B]/g, ''); 
 firstDiv = this.childNodes[0].innerHTML.replace(/[\u200B]/g, '');
 console.log(firstDiv);
 if (firstDiv == "UNSUBSCRIBE") {
  this.childNodes[0].innerHTML = 'SUBSCRIBE';
  console.log('User "' + USER + '" wants to unsubscribe. ');
  
  $().SPServices({
   operation: "GetListItems",
   async: false,     
   webURL: 'https://your-site-here.com/',
      listName: 'Subscribed users',
   completefunc: function (xData, Status) {
    $(xData.responseXML).find("z\\:row, row").each(function() {
     if (($(this).attr("ows_Title") == USER) 
         && ($(this).attr("ows_ListLibID") == LLID)) {
      listIDDel = $(this).attr("ows_ID");
     }
    });
   }
  });
         
  $().SPServices({
   operation: 'UpdateListItems',
   webURL: 'https://your-site-here.com/',
   listName: 'Subscribed users',
   updates: '<batch onerror="Continue" precalc="True">' + 
              '<method cmd="Delete" id="1">' +
              '<field name="ID">'+ listIDDel +'</field>' +
              '<field name="Title">'+ USER +'</field>' +
              '<field name="ListLibID">'+ LLID +'</field>' +
              '<field name="PageURL">'+ PURL +'</field>' +
              '<field name="SubsiteURL">'+ SURL +'</field>' +
              '</method>' +
           '</Batch>',
   completefunc: function(xData, Status) {
      console.log('User "'+USER+'" is now removed from the subscribers list.'); 
   }
  });

  runInOtherFile();
  runDeleteInOtherFile(LLID);

 }
 else if (firstDiv == "SUBSCRIBE") {
  this.childNodes[0].innerHTML = 'UNSUBSCRIBE';
  console.log('User "'+USER+'" wants to subscribe. ' + 
              'Adding user to subscribers list now.');
  
  $().SPServices({
   operation: 'UpdateListItems',
   webURL: 'https://your-site-here.com/',
   listName: 'Subscribed users',
   updates: '<batch onerror="Continue" precalc="True">' + 
              '<method cmd="New" id="1">' +
              '<field name="Title">'+ USER +'</field>' +
              '<field name="ListLibID">'+ LLID +'</field>' +
              '<field name="PageURL">'+ PURL +'</field>' +
              '<field name="SubsiteURL">'+ SURL +'</field>' +
              '</method>' +
           '</batch>',
   completefunc: function(xData, Status) {
    console.log('User "'+USER+'" has been added to the subscribers list.');  
      }
  }); 
  runInOtherFile();
 }
});

notification.js

var USER = $().SPServices.SPGetCurrentUser({ 
 webURL: "", 
 fieldName: "Title", 
 fieldNames: {}, 
 debug: false
});

var currentViewUser;
var currentViewLLIB;
var currentViewPURL;
var currentViewSURL;
var currentViewCOUNT;
var counter = 0;
var tempArr;
var itemArray = new Array();
var itemArrayContainer = new Array();
var itemArrayReplaced = new Array();
var itemArrayContainerReplaced = new Array();


console.log('Notification script has been loaded! Starting script now...'
          + '\n--------------------------------------------------------');
runOnLoad();

function runOnLoad() {
 $().SPServices({
  operation: "GetListItems",
  async: false,        
  webURL: 'https://your-site-here.com/',
     listName: 'Subscribed users',
  completefunc: function (xData, Status) {
   $(xData.responseXML).SPFilterNode("z:row").each(function() {
    if ($(this).attr("ows_Title") == USER) {
     counter++;
     itemArray[counter] = new Array($(this).attr("ows_Title"), 
                          unescape($(this).attr("ows_ListLibID")), 
                          $(this).attr("ows_PageURL"), 
                          $(this).attr("ows_SubsiteURL"), counter);
     itemArrayContainer.push(itemArray[counter]);
    }
   });
  }
 });
}

if (counter != 0) {   
 for (var j = 0; j < itemArrayContainer.length; j++) {
  sessionItem = "sessionItem" + (j + 1);
  sessionStorage.setItem(sessionItem, "");
 }
 function repeatEvery5Seconds() {
  for (var i = 0; i < itemArrayContainer.length; i++) {
   currentViewUser = itemArrayContainer[i][0];
   currentViewLLIB = itemArrayContainer[i][1]; 
   currentViewPURL = itemArrayContainer[i][2];
   currentViewSURL = itemArrayContainer[i][3];
   currentViewCOUNT = "sessionItem" + itemArrayContainer[i][4];
   fetchCurrentListStatus(currentViewLLIB, currentViewCOUNT);
  }
 }
 var t = setInterval(repeatEvery5Seconds,5000);
}
else {
 console.log('User "'+currentViewUser+'" is not in the subscribers list. '
             + 'Notifications will not be shown.');
}

function fetchCurrentListStatus(currentViewLLIB, currentViewCOUNT) {
 var listItemArray = new Array();
 var listItemArrayBackup = new Array();

 $().SPServices({
  operation: "GetListItems",
  async: false,     
  crossDomain: true,
  webURL: currentViewSURL,
     listName: currentViewLLIB,
  completefunc: function (xData, Status) {
   $(xData.responseXML).find("z\\:row, row").each(function() {
    var rowData = $(this).attr("ows_ID");
    listItemArray.push(rowData);
    listItemArrayBackup.push(rowData); 
   });
  }
 });
        
 if (listItemArray.length == null || listItemArray.length == 0) {
  console.log('List is empty.');
  sessionStorage.setItem(currentViewCOUNT, listItemArray);
 }
 else if (listItemArray.length != null || listItemArray.length != 0) {
  console.log('Server list: \t\t"' + listItemArray + '"');
  if ( sessionStorage.getItem(currentViewCOUNT).length != 0 
    || sessionStorage.getItem(currentViewCOUNT) != 0 
    || sessionStorage.getItem(currentViewCOUNT) != "" ) {
   tempArr = sessionStorage.getItem(currentViewCOUNT).split(",");
   console.log('Session list: \t\t"' + tempArr + '"');
   itemChange();
  }
  else if (sessionStorage.getItem(currentViewCOUNT).length == 0 
        || sessionStorage.getItem(currentViewCOUNT) == 0 
        || sessionStorage.getItem(currentViewCOUNT) == "" ) {
   sessionStorage.setItem(currentViewCOUNT, listItemArray);
   tempArr = sessionStorage.getItem(currentViewCOUNT).split(",");
   console.log('Session list: \t\t"' + tempArr + '"');
   itemChange();
  }
  if (tempArr.length == listItemArray.length) {
   console.log('No new item was added in the past 5 seconds.'
             + '\n--------------------------------------------------------'); 
  }
 }

 function itemChange() {
  if (listItemArray.length == tempArr.length) {}
  else if (listItemArray.length < tempArr.length) {
   console.log('An item was deleted. Now updating session storage.');
   sessionStorage.setItem(currentViewCOUNT, listItemArray);  
  }
  else if (listItemArray.length > tempArr.length) {
   console.log('An item has been added. Now updating session storage.'); 
   var array1 = listItemArray;
   var array2 = tempArr;
   var index;
   for (var i=0; i<array2 .length="" i="" if="" index=""> -1) {
           array1.splice(index, 1);
       }
   }
   var currentItemName;
   var newListItemArray = new Array(); 

   for (var i = 0; i < array1.length; i++) {
       var currentItem = array1[i];
     $().SPServices({
        operation: "GetListItems",
        ID: currentItem,
        async: false,
     crossDomain: true,
     webURL: currentViewSURL,
        listName: currentViewLLIB,
        completefunc: function (xData, Status) {
          $(xData.responseXML).SPFilterNode("z:row").each(function() {
             if ($(this).attr("ows_ID") == currentItem) {
                currentItemName = $(this).attr("ows_LinkFilename"); 
             }
          newListItemArray.push(currentItemName);
          });
       }
    });
   }

   var div = document.createElement("div");
   div.style.width = "auto";
   div.style.height = "21px";
   div.style.background = "#F7F7F7";
   div.style.color = "#3C82C7";
   div.style.border = "1px solid #d7d6d8";
   div.style.float = "right";
   div.style.padding = "5px";
   div.style.borderBottomLeftRadius = "4px";
   div.innerHTML = 'A document named "' + currentItemName 
                  + '" was added to <a href="' + currentViewPURL + '">' 
                  + currentViewLLIB + '</a>.';
   div.className = "notification";
   document.getElementById("notificationArea").appendChild(div);
   $(document.getElementsByClassName("notification")).hide();
   $(document.getElementsByClassName("notification")).fadeIn(1500);
   setTimeout(function() { 
    $(document.getElementsByClassName("notification")).fadeOut(1500);
    document.getElementById("notificationArea").removeChild(div);
   }, 5000);
   
   if (tempArr != listItemArray) {
    sessionStorage.setItem(currentViewCOUNT, listItemArrayBackup);
   }
  }
 }
}

function runInOtherFile() {
 console.log('Now running "runInOtherFile()". ');
 counter = 0;
 setTimeout(function() { 
 itemArrayContainerReplaced.length = 0;
  $().SPServices({
   operation: "GetListItems",
   async: false,        
   webURL: 'https://your-site-here.com/',
      listName: 'Subscribed users',
   completefunc: function (xData, Status) {
    $(xData.responseXML).SPFilterNode("z:row").each(function() {
     if ($(this).attr("ows_Title") == USER) {
      counter++;
      itemArrayReplaced[counter] = new Array($(this).attr("ows_Title"), 
                                   unescape($(this).attr("ows_ListLibID")), 
                                   $(this).attr("ows_PageURL"), 
                                   $(this).attr("ows_SubsiteURL"), counter);
      itemArrayContainerReplaced.push(itemArrayReplaced[counter]);
     }
    });
   }
  });
  console.log('List of subscribed users has been updated.'
            + '\n--------------------------------------------------------'); 
  itemArrayContainer = itemArrayContainerReplaced;
 }, 1000);
} 

function runDeleteInOtherFile() {
 for (var k = 0; k < itemArrayContainer.length; k++) {
  if (itemArrayContainer[k][1] == LLID) {
   var tempCurrentViewCOUNT = "sessionItem" + itemArrayContainer[k][4];
   sessionStorage.setItem(tempCurrentViewCOUNT, "");  // 0);
   itemArrayContainer.splice(k, 1);
  } 
 }
 console.log('Session corresponding to the list/library from which user ' 
            +'has unsubscribed is now empty.');
}

That's all the code. All of it. Everything you need to get fancy notifications. You can always change the style of the notification, it may be in the script but you can just personalize it in whatever way you want to.

Some screenshots

Console - when subscribed to two lists/libraries, first five seconds:

Console - when subscribed to two lists/libraries, after more than fifteen seconds:

Console - when a new item has been added to a list/library to which the current user is subscribed to:

Browser - notification the current user sees when a new item was added to a list/library to which the current user is subscribed to (translation: "A document named 'mouse-pointer.jpg' was added to TESTER."):

Console - when an item gets deleted from a list/library to which the current user is subscribed to:

Console - when the current user unsubscribes from a list/library (it's the one with the long array of ID's):

Console - when the current user subscribes to a list/library (again, the one with the long array of ID's):

Browser - the buttons; there is only one button per list but I used an image editor to place these next to each other, just to demonstrate:

The end

That was it, the whole blog post. My longest one so far I believe. I hope I explained things clear enough, I did my best to tell you every bit of information I have about these scripts. I hope that one day I'll be able to rewrite this functionality in C#, to make it server-side. But until that day, I'm happy with this and I hope you are happy with it too. :)

Do let me know if you are having trouble or problems with one of the scripts and I'll do my best to help you out.

As an extra tip, I suggest you minify the scripts and get rid of all console logs. Just to make it less
heavy.

Enjoy!

No comments:

Post a Comment