public
Created

  • Download Gist
gistfile1.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092
// Part of this code up to END OF (c) is:
/*
Copyright 2011 Martin Hawksey
 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
 
http://www.apache.org/licenses/LICENSE-2.0
 
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
 
var MINSIZE = 1; //minimum node size on autofill
var MAXSIZE = 10; //maximum node size on autofill
 
 
function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var menuEntries = [];
// When the user clicks on "addMenuExample" then "Menu Entry 1", the function function1 is executed.
menuEntries.push({name: "API Authentication", functionName: "configureAPI"});
menuEntries.push({name: "Test Collection", functionName: "testCollection"});
menuEntries.push({name: "Run Now!", functionName: "collectTweets"});
menuEntries.push(null); // line separator
ss.addMenu("TAGS", menuEntries);
var menuEntries = [];
menuEntries.push({name: "1. Get Friend Follower Relationships", functionName: "getCommunityGraph"});
menuEntries.push({name: "2. Replace User IDs with Names", functionName: "replaceIDsWithNames"});
menuEntries.push({name: "3. Fill Twitter User Information", functionName: "lookupTwitterID"});
menuEntries.push(null); // line separator
menuEntries.push({name: "Calculate Degree", functionName: "calcDegree"});
menuEntries.push(null); // line separator
menuEntries.push({name: "Fill Node Size (Degree)", functionName: "fillNodeUsingDegree"});
menuEntries.push({name: "Fill Node Size (In-Degree)", functionName: "fillNodeUsingInDegree"});
menuEntries.push({name: "Fill Node Size (Out-Degree)", functionName: "fillNodeUsingOutDegree"});
ss.addMenu("TAGS - Advanced", menuEntries);
}
 
function doPost(e){
// PART OF SCRIPT WHICH HANDLES DATA POSTED FROM R
// To use complete steps 1 -3 from TAGS - Advanced menu and File > Publish to the web..
// From this window select Share > Publish as service.. allowing anyone to invloke annonymously
// Download the R script from https://gist.github.com/1682306 and modify variables for the key, sheet, urls and common secret set below
// Run the R script and values will be entered into the spreadsheet
var secret ="FzWGlpUkt1Tmc"; //must match secret in R script
if (e.parameter.secret == secret){
var ss = SpreadsheetApp.openById(ScriptProperties.getProperty('active'));
var sheet = ss.getSheetByName("Vertices"); // read the existing data from Vertices sheet
var data = {}
var datagrid = Utilities.jsonParse(e.parameter.datagrid); // handling datagrid object made in R
var datagridlabels = Utilities.jsonParse(e.parameter.datagridlabels); // list of screen_names that match datagrid made in R
for (i in datagrid){
datagrid[i].screen_name = datagridlabels[i];
data[datagridlabels[i]]=datagrid[i]; // index objects with screennames
}
var toptens = Utilities.jsonParse(e.parameter.toptens); // collect toptens list made in R
var labels = Utilities.jsonParse(e.parameter.toptenslabels); //list of names of things calculated in R
var exdata = getRowsData(sheet); // read the existing data from Vertices sheet
for (i in exdata){ // add new data to existing data
if (data[exdata[i].screen_name] != undefined){
for (j in labels){
exdata[i][labels[j]] = data[exdata[i].screen_name][labels[j]];
}
}
}
setRowsData(sheet,exdata); // write individuals stats back to sheet
 
var sheet = ss.getSheetByName("SNA Metrics"); // add the top ten's to SNA Metrics sheet
var topsData = chunk(toptens,10);
// probably could have found better way of writting
sheet.getRange("A4:C13").setValues(topsData[0]);
sheet.getRange("A17:C26").setValues(topsData[1]);
sheet.getRange("A30:C39").setValues(topsData[2]);
sheet.getRange("A43:C52").setValues(topsData[3]);
sheet.getRange("A56:C65").setValues(topsData[4]);
sheet.getRange("A69:C78").setValues(topsData[5]);
}
}
 
 
function cron(){
collectTweets();
getStats();
}
 
function copyData(){
var doc = SpreadsheetApp.getActiveSpreadsheet();
var sSheet = doc.getSheetByName("Copy of Archive");
var dSheet = doc.getSheetByName("Archive");
var col = 2;
dSheet.getRange(1,col,sSheet.getLastRow(),1).setValues(sSheet.getRange(1,col,sSheet.getLastRow(),1).getValues());
//setRowsData(dSheet);
}
 
function setup(){
ScriptProperties.setProperty('active', SpreadsheetApp.getActiveSpreadsheet().getId());
}
 
function authenticate(){
//ScriptProperties.setProperty('active', SpreadsheetApp.getActiveSpreadsheet().getId());
authorize();
}
function configureAPI() {
renderAPIConfigurationDialog();
}
 
function renderAPIConfigurationDialog() {
// modified from Twitter Approval Manager
// http://code.google.com/googleapps/appsscript/articles/twitter_tutorial.html
var doc = SpreadsheetApp.getActiveSpreadsheet();
var app = UiApp.createApplication().setTitle(
"Twitter API Authentication Configuration").setHeight(400).setWidth(420);
app.setStyleAttribute("padding", "10px");
 
//var dialog = app.loadComponent("GUIComponent");
var dialogPanel = app.createFlowPanel().setWidth("400px");
var label1 = app.createLabel("1. Register for an API key with Twitter at http://dev.twitter.com/apps/new (if you've already registered a Google Spreadsheet/Twitter mashup you can reuse your existing Consumer Key/Consumer Secret). In the form these are the important bits: ").setStyleAttribute("paddingBottom", "10px");
var label2 = app.createLabel(" - Application Website = anything you like").setStyleAttribute("textIndent", "30px");
var label3 = app.createLabel(" - Application Type = Browser").setStyleAttribute("textIndent", "30px");
var label4 = app.createLabel(" - Callback URL = https://spreadsheets.google.com/macros").setStyleAttribute("textIndent", "30px");
var label5 = app.createLabel(" - Default Access type = Read-only ").setStyleAttribute("textIndent", "30px").setStyleAttribute("paddingBottom", "10px");
var label6 = app.createLabel("2. Once finished filling in the form and accepting Twitter's terms and conditions you'll see a summary page which includes a Consumer Key and Consumer Secret which you need to enter below").setStyleAttribute("paddingBottom", "10px");
var label7 = app.createLabel("3. When your Key and Secret are saved you need to open Tools > Script Editor ... and run the 'authenticate' function").setStyleAttribute("paddingBottom", "10px");
//("<strong>hello</strong><ul><li>one</li></ul>");
dialogPanel.add(label1);
dialogPanel.add(label2);
dialogPanel.add(label3);
dialogPanel.add(label4);
dialogPanel.add(label5);
dialogPanel.add(label6);
dialogPanel.add(label7);
 
var consumerKeyLabel = app.createLabel(
"Twitter OAuth Consumer Key:");
var consumerKey = app.createTextBox();
consumerKey.setName("consumerKey");
consumerKey.setWidth("90%");
consumerKey.setText(getConsumerKey());
var consumerSecretLabel = app.createLabel(
"Twitter OAuth Consumer Secret:");
var consumerSecret = app.createTextBox();
consumerSecret.setName("consumerSecret");
consumerSecret.setWidth("90%");
consumerSecret.setText(getConsumerSecret());
var saveHandler = app.createServerClickHandler("saveConfiguration");
var saveButton = app.createButton("Save Configuration", saveHandler);
var listPanel = app.createGrid(2, 2);
listPanel.setStyleAttribute("margin-top", "10px")
listPanel.setWidth("100%");
 
listPanel.setWidget(0, 0, consumerKeyLabel);
listPanel.setWidget(0, 1, consumerKey);
listPanel.setWidget(1, 0, consumerSecretLabel);
listPanel.setWidget(1, 1, consumerSecret);
 
 
// Ensure that all form fields get sent along to the handler
saveHandler.addCallbackElement(listPanel);
//var dialogPanel = app.createFlowPanel();
//dialogPanel.add(helpLabel);
dialogPanel.add(listPanel);
dialogPanel.add(saveButton);
app.add(dialogPanel);
doc.show(app);
}
 
function collectTweets() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sumSheet = ss.getSheetByName("Readme/Settings");
var SEARCH_TERM = sumSheet.getRange("B10").getValue();
var NUMBER_OF_TWEETS = sumSheet.getRange("B12").getValue();
var RESULT_TYPE = sumSheet.getRange("B13").getValue();
// if continuous sheetname = archive else make a name
if (RESULT_TYPE == "continuous"){
var sheetName = "Archive";
} else {
var sheetName = Utilities.formatDate(new Date(), "GMT", "dd-MMM-yy hh:mm"); //make a new sheet name based on todays date
}
// if sheetname doesn't exisit make it
if (!ss.getSheetByName(sheetName)){
var temp = ss.getSheetByName("TMP");
var sheet = ss.insertSheet(sheetName, {template:temp});
} else {
var sheet = ss.getSheetByName(sheetName);
}
var sinceid = false;
 
sinceid = alltrim(sumSheet.getRange("B14").getValue());
//if no since id grab search results
if (sinceid){
var data = getTweets(SEARCH_TERM, NUMBER_OF_TWEETS, sinceid); // get results from twitter sinceid
} else {
var data = getTweets(SEARCH_TERM, NUMBER_OF_TWEETS); // get results from twitter
}
// if some data insert rows
if (data.length>0){
sheet.insertRowsAfter(1, data.length);
setRowsData(sheet, data);
}
}
 
function testCollection(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sumSheet = ss.getSheetByName("Readme/Settings");
var SEARCH_TERM = sumSheet.getRange("B10").getValue();
var data = getTweets(SEARCH_TERM, 5); // get results from twitter
if (data.length>0){
Browser.msgBox("Found some tweets. Here's an example one from "+data[0]["from_user"]+" which says: "+data[0]["text"]);
} else {
Browser.msgBox("Twitter said: "+ScriptProperties.getProperty("errormsg"));
}
}
 
function getTweets(searchTerm, maxResults, sinceid, languageCode) {
//Based on Mikael Thuneberg getTweets - mod by mhawksey to convert to json
// if you include setRowsData this can be used to output chosen entries
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sumSheet = ss.getSheetByName("Readme/Settings");
if (isConfigured()){
var oauthConfig = UrlFetchApp.addOAuthService("twitter");
oauthConfig.setAccessTokenUrl(
"https://api.twitter.com/oauth/access_token");
oauthConfig.setRequestTokenUrl(
"https://api.twitter.com/oauth/request_token");
oauthConfig.setAuthorizationUrl(
"https://api.twitter.com/oauth/authorize");
oauthConfig.setConsumerKey(getConsumerKey());
oauthConfig.setConsumerSecret(getConsumerSecret());
var requestData = {
"oAuthServiceName": "twitter",
"oAuthUseToken": "always"
};
} else {
var REFERER = sumSheet.getRange("B9").getValue();
var requestData = {"method":"GET", "headers": { "User-Agent": REFERER}}
}
try {
var pagenum = 1;
var data =[];
var idx = 0;
var sinceurl ="";
var period = 0;
var SEARCH_DURATION = sumSheet.getRange("B11").getValue();
// prepare search term
 
if (SEARCH_DURATION != "default"){
switch (SEARCH_DURATION){
case "yesterday":
period = 0;
break;
case "-2 days":
period = 1;
break;
case "-3 days":
period = 2;
break;
case "-4 days":
period = 3;
break;
case "-5 days":
period = 4;
break;
case "-6 days":
period = 5;
break;
case "-7 days":
period = 6;
break;
}
var until=new Date();
until.setDate(until.getDate()-period);
var since = new Date(until);
since.setDate(since.getDate()-1-period);
}
if (typeof maxResults == "undefined") {
maxResults = 100;
}
if (maxResults > 1500) {
maxResults = 1500;
}
if (maxResults > 100) {
resultsPerPage = 100;
maxPageNum = maxResults / 100;
} else {
resultsPerPage = maxResults;
maxPageNum = 1;
}
if (sinceid != null && sinceid.length > 0) {
sinceurl = "&since_id=" + sinceid;
}
//Logger.log(twDate(since)+" "+twDate(until));
searchTerm = encodeURIComponent(searchTerm);
var baseURL = "http://search.twitter.com/search.json";
for (pagenum = 1; pagenum <= maxPageNum; pagenum++) {
var URL = "";
if (typeof nextPage != "undefined"){
URL = nextPage+sinceurl;
} else if (pagenum == 1) {
URL = URL + "?q=" + searchTerm;
if (typeof since != "undefined") URL = URL + "&since=" + twDate(since);
if (typeof until != "undefined") URL = URL + "&until=" + twDate(until);
URL = URL + "&rpp=" + resultsPerPage;
URL = URL + "&page=" + pagenum;
URL = URL + "&result_type=recent";
URL = URL + "&include_entities=true";
URL = URL + "&with_twitter_user_id=true";
URL = URL + sinceurl;
/*
if (typeof languageCode != "undefined") {
if (languageCode.length > 0) {
URL = URL + "&lang=" + languageCode;
}
}
*/
}
if (URL != ""){
Logger.log(URL);
var response = UrlFetchApp.fetch(baseURL+URL, requestData);
var contentHeader = response.getHeaders();
if (response.getResponseCode() == 200) {
var responseData = Utilities.jsonParse(response.getContentText());
var nextPage = responseData.next_page;
var currentPage = responseData.page;
var objects = responseData.results;
for (i in objects){ // not pretty but I wanted to extract geo data
if (objects[i].geo != null){
objects[i]["geo_coordinates"] = "loc: "+objects[i].geo.coordinates[0]+","+objects[i].geo.coordinates[1];
}
objects[i]["status_url"] = "http://twitter.com/"+objects[i].from_user+"/statuses/"+objects[i].id_str;
objects[i].id_str = objects[i].id_str+" ";//used to force save to string
//objects[i].in_reply_to_status_id_str = objects[i].in_reply_to_status_id_str+" ";
objects[i]["time"] = (objects[i]["created_at"]).substring(5,25);
objects[i]["entities_str"] = Utilities.jsonStringify(objects[i]["entities"]);
var str = objects[i]["text"];
if (str.indexOf('? ')!=-1 || str.charAt(str.length-1)=="?"){
objects[i]["possible_question"]=true;
}
data[idx]=objects[i];
idx ++;
}
}
}
}
return data;
} catch (e) {
Logger.log("Line "+e.lineNumber+" "+e.message+e.name);
Browser.msgBox("Line "+e.lineNumber+" "+e.message+e.name);
ScriptProperties.setProperty("errormsg","Line "+e.lineNumber+" "+e.message+e.name);
return data;
}
}
 
function twDate(aDate){
var dateString = Utilities.formatDate(aDate, "GMT", "yyyy-MM-dd");
return dateString;
}
 
function testRate(){
var api_request = "account/rate_limit_status.json";
var data = tw_request("GET", api_request);
Logger.log(data.toString());
return data;
}
 
function tw_request(method, api_request){
var oauthConfig = UrlFetchApp.addOAuthService("twitter");
oauthConfig.setAccessTokenUrl(
"https://api.twitter.com/oauth/access_token");
oauthConfig.setRequestTokenUrl(
"https://api.twitter.com/oauth/request_token");
oauthConfig.setAuthorizationUrl(
"https://api.twitter.com/oauth/authorize");
oauthConfig.setConsumerKey(getConsumerKey());
oauthConfig.setConsumerSecret(getConsumerSecret());
var requestData = {
"method": method,
"oAuthServiceName": "twitter",
"oAuthUseToken": "always"
};
try {
var result = UrlFetchApp.fetch(
"https://api.twitter.com/1/"+api_request,
requestData);
var o = Utilities.jsonParse(result.getContentText());
Logger.log(o);
} catch (e) {
Logger.log(e);
}
return o;
}
 
function makeListOfTwitterIDUsernamesFromSearch(){
 
var doc = SpreadsheetApp.getActiveSpreadsheet();
var sumSheet = doc.getSheetByName("Readme/Settings");
var SEARCH_TERM = sumSheet.getRange("B10").getValue();
var NUMBER_OF_TWEETS = sumSheet.getRange("B12").getValue();
doc.toast("Starting data collection");
var data = getTweets(SEARCH_TERM, NUMBER_OF_TWEETS);
var nodeList = [];
var nodes = [];
var nodeSheetName = "data";
if (!doc.getSheetByName(nodeSheetName)){
var sheetV = doc.insertSheet(nodeSheetName);
} else {
var sheetV = doc.getSheetByName(nodeSheetName);
sheetV.clearContents();
}
for (u in data){
if (!(data[u].from_user_id_str in oc(nodeList))){
nodeList.push(data[u].from_user_id_str);
nodes.push([data[u].from_user_id_str , data[u].from_user]);
}
}
sheetV.getRange(1,2).setValue(new Date());
sheetV.getRange(3,1,nodes.length,2).setValues(nodes);
getCommunityGraph("data")
replaceIDsWithNames();
doc.toast("All done! Refresh browser to see results");
}
 
function getCommunityGraph(optSource){
var source = optSource || "Summary";
var doc = SpreadsheetApp.getActiveSpreadsheet();
var sheet = doc.getSheetByName(source);
var edgeSheetName = "Edges";
var verticesSheetName = "Vertices";
// get/make edges and Vertices sheet
if (!doc.getSheetByName(edgeSheetName)){
var sheetE = doc.insertSheet(edgeSheetName);
} else {
var sheetE = doc.getSheetByName(edgeSheetName);
if (sheetE.getLastRow()>0){
sheetE.getRange(1, 1, sheetE.getLastRow(), sheetE.getMaxColumns()).clear({contentsOnly:true});
}
}
if (!doc.getSheetByName(verticesSheetName)){
var temp = doc.getSheetByName("TMP_NODES");
var sheetV = doc.insertSheet(verticesSheetName, {template:temp});
} else {
var sheetV = doc.getSheetByName(verticesSheetName);
var test = sheetV.getLastRow();
if (sheetV.getLastRow()>1){
sheetV.getRange(2, 1, sheetV.getLastRow(), sheetV.getMaxColumns()).clear({contentsOnly:true});
}
}
// get the user_id_str from summary sheet
if (sheet.getLastRow()>253){
var maxRow = 250;
doc.toast("This function currently only collects friend/follower relationships for the top 250 twitter users appearing in this search archive","Important!");
} else {
var maxRow = sheet.getLastRow();
}
var user_ids = sheet.getRange(3,4,maxRow,2).getValues();
var users = {};
var links = [];
var nodes = [];
// get user friends
 
if (isConfigured()){
var oauthConfig = UrlFetchApp.addOAuthService("twitter");
oauthConfig.setAccessTokenUrl("https://api.twitter.com/oauth/access_token");
oauthConfig.setRequestTokenUrl("https://api.twitter.com/oauth/request_token");
oauthConfig.setAuthorizationUrl("https://api.twitter.com/oauth/authorize");
oauthConfig.setConsumerKey(getConsumerKey());
oauthConfig.setConsumerSecret(getConsumerSecret());
var requestData = {
"oAuthServiceName": "twitter",
"oAuthUseToken": "always",
"method": "GET"
};
} else {
var REFERER = doc.getSheetByName("Readme/Settings").sumSheet.getRange("B9").getValue();
var requestData = {"method":"GET", "headers": { "User-Agent": REFERER}};
Browser.msgBox("Warning: Results may be limited because you aren't using API Authenticated access");
}
for (var u = 0; u < user_ids.length; u++){
if (user_ids[u][0] != ""){
nodes.push(user_ids[u]);
try {
var next_cursor = -1; // only getting last 5000 friends
var url = "https://api.twitter.com/1/friends/ids.json?cursor="+next_cursor+"&stringify_ids=true&user_id="+user_ids[u][0];
var response = UrlFetchApp.fetch(url, requestData);
if (response.getResponseCode() == 200) {
var o = response.getContentText();
for (var t = 0; t < user_ids.length; t++){
if (user_ids[t][0] != ""){
var searchKey = new RegExp(user_ids[t][0],"gi");
if (o.search(searchKey) != -1){
links.push([user_ids[u][0],user_ids[t][0]]);
}
}
}
}
} catch(e) {
Logger.log(e);
//Browser.msgBox(e);
sheetE.getRange(1,1,links.length,2).setValues(links);
sheetV.getRange(2,1,nodes.length,2).setValues(nodes);
}
}
}
sheetE.getRange(1,1,links.length,2).setValues(links);
sheetV.getRange(2,1,nodes.length,2).setValues(nodes);
}
 
function replaceIDsWithNames(){
var doc = SpreadsheetApp.getActiveSpreadsheet();
var edgeSheetName = "Edges";
var verticesSheetName = "Vertices";
var sheetE = doc.getSheetByName(edgeSheetName);
var sheetV = doc.getSheetByName(verticesSheetName);
var user_ids = sheetV.getRange(2,1,sheetV.getLastRow(),2).getValues();
var edge_ids = sheetE.getRange(1,1,sheetE.getLastRow(),2).getValues();
for (var u=0; u<user_ids.length; u++){
for (var e=0; e<edge_ids.length; e++){
if (edge_ids[e][0] == user_ids[u][0]) edge_ids[e][0] = user_ids[u][1];
if (edge_ids[e][1] == user_ids[u][0]) edge_ids[e][1] = user_ids[u][1];
}
}
sheetE.getRange(1,1,sheetE.getLastRow(),2).setValues(edge_ids);
}
 
function lookupTwitterID(){
// lookup ids from twitter
var result = [];
var doc = SpreadsheetApp.getActiveSpreadsheet();
var sheet = doc.getSheetByName("Vertices")
var users = sheet.getRange(2,1,sheet.getLastRow(),1).getValues();
var data = [];
if (isConfigured()){
var oauthConfig = UrlFetchApp.addOAuthService("twitter");
oauthConfig.setAccessTokenUrl(
"https://api.twitter.com/oauth/access_token");
oauthConfig.setRequestTokenUrl(
"https://api.twitter.com/oauth/request_token");
oauthConfig.setAuthorizationUrl(
"https://api.twitter.com/oauth/authorize");
oauthConfig.setConsumerKey(getConsumerKey());
oauthConfig.setConsumerSecret(getConsumerSecret());
var requestData = {
"method": "GET",
"oAuthServiceName": "twitter",
"oAuthUseToken": "always"
};
} else {
var REFERER = doc.getSheetByName("Readme/Settings").sumSheet.getRange("B9").getValue();
var requestData = {"method":"GET", "headers": { "User-Agent": REFERER}};
Browser.msgBox("Warning: Results may be limited because you aren't using API Authenticated access");
}
var chunks = chunk(users,100);
for (i in chunks){
var idurl ="http://api.twitter.com/1/users/lookup.json?user_id="+chunks[i].join();
try {
var response = UrlFetchApp.fetch(idurl, requestData);
if (response.getResponseCode() == 200) {
var objects = Utilities.jsonParse(response.getContentText());
for (j in objects){
data.push(objects[j]);
}
}
} catch(e) {
Browser.msgBox(e);
Logger.log(e);
}
}
if (data.length>0){
setRowsData(sheet, data);
}
}
function fillNodeUsingDegree(){
autofillSize(ScriptProperties.getProperty("Degree"),3,MINSIZE,MAXSIZE);
}
function fillNodeUsingInDegree(){
autofillSize(ScriptProperties.getProperty("In-Degree"),4,MINSIZE,MAXSIZE);
}
function fillNodeUsingOutDegree(){
autofillSize(ScriptProperties.getProperty("Out-Degree"),5,MINSIZE,MAXSIZE);
}
function fillNodeUsingBetweenness(){
autofillSize(ScriptProperties.getProperty("Betweenness"),6,MINSIZE,MAXSIZE);
}
 
function autofillSize(topLimit,col,min,max){
var doc = SpreadsheetApp.getActiveSpreadsheet();
var verticesSheetName = "Vertices";
var sheetV = doc.getSheetByName(verticesSheetName);
var user_ids = sheetV.getRange(2,col,sheetV.getLastRow()-1,1).getValues();
var output = [];
for (i=0;i<user_ids.length;i++){
var size = user_ids[i][0];
user_ids[i][0] = new Number(size*(max-min)/topLimit+min).toFixed(1);
}
sheetV.getRange(2,6,sheetV.getLastRow()-1,1).setValues(user_ids);
}
 
function calcDegree(){
var doc = SpreadsheetApp.getActiveSpreadsheet();
var edgeSheetName = "Edges";
var verticesSheetName = "Vertices";
var dMax = 0,
inDMax = 0,
outDMax = 0;
var sheetE = doc.getSheetByName(edgeSheetName);
var sheetV = doc.getSheetByName(verticesSheetName);
var user_ids = sheetV.getRange(2,2,sheetV.getLastRow()-1,1).getValues();
var edge_ids = sheetE.getRange(2,1,sheetE.getLastRow()-1,2).getValues();
var matrix = new Array(user_ids.length);
for (i=0; i <user_ids.length; i++) matrix[i]=replicate(3,0);
for (var i=0; i<user_ids.length; i++){
for (var k=0; k<edge_ids.length; k++){
if (user_ids[i][0]==edge_ids[k][0]){
matrix[i][0] = matrix[i][0] + 1;
matrix[i][2] = matrix[i][2] + 1;
if (matrix[i][0] > dMax) dMax = matrix[i][0];
if (matrix[i][2] > outDMax) outDMax = matrix[i][2];
}
if (user_ids[i][0]==edge_ids[k][1]){
matrix[i][0] = matrix[i][0] + 1;
matrix[i][1] = matrix[i][1] + 1;
if (matrix[i][0] > dMax) dMax = matrix[i][0];
if (matrix[i][1] > inDMax) inDMax = matrix[i][1];
}
}
}
ScriptProperties.setProperty("Degree",dMax);
ScriptProperties.setProperty("In-Degree",inDMax);
ScriptProperties.setProperty("Out-Degree",outDMax);
sheetV.getRange(2,3,matrix.length,3).setValues(matrix);
}
 
function calcBetweenness(){
var doc = SpreadsheetApp.getActiveSpreadsheet();
var edgeSheetName = "Edges";
var verticesSheetName = "Vertices";
var sheetE = doc.getSheetByName(edgeSheetName);
var sheetV = doc.getSheetByName(verticesSheetName);
var test = sheetV.getLastRow();
var user_ids = sheetV.getRange(2,2,sheetV.getLastRow()-1,1).getValues();
var edge_ids = sheetE.getRange(2,1,sheetE.getLastRow()-1,2).getValues();
Logger.log(new Date()+":make matrix ...");
var matrix = new Array(user_ids.length);
for (i=0; i <user_ids.length; i++) matrix[i]=replicate(user_ids.length,0);
 
for (var i=0; i<user_ids.length; i++){
Logger.log(new Date()+":user ..."+(i+1));
for (var j=0; j<user_ids.length; j++){
for (var k=0; k<edge_ids.length; k++){
if (user_ids[i][0]==edge_ids[k][0] && user_ids[j][0]==edge_ids[k][1]){
matrix[i][j] = 1;
break;
} else {
matrix[i][j] = 0;
}
}
}
}
Logger.log(new Date()+":... matrix made");
Logger.log(new Date()+":compute_betweenness");
var betweenness = compute_betweenness(matrix,user_ids.length);
var user_ids = sheetV.getRange(2,6,betweenness.length,1).setValues(betweenness);
}
// compute betweenness of each node in a network
// using the Brandes algorithm
// modified from NetVis Module 2.0
// by Jonathon N. Cummings
function compute_betweenness(matrix,ncols){
var betweenness = [];
var bMax = 0;
Logger.log(new Date()+":make betweenness matrix ...");
for(var i=0; i<ncols; i++){
betweenness[i]=0;
}
for(var s=0; s<ncols; s++){
var stack=[],
P=[],
sigma=[],
dist=[];
for(i=0;i<ncols;i++){
P[i]=[];
if(i==s){
sigma[i]=1;
dist[i]=0;
}else{
sigma[i]=0;
dist[i]=-1;
}
}
var queue=[];
queue.push(s);
while(queue.length > 0){
Logger.log(new Date()+":queue length: "+queue.length);
var v=queue.shift();
stack.push(v);
for(var w=0; w<ncols; w++){
if(matrix[v][w]==1){
if(dist[w] < 0){
//queue[]=w;
queue.push(w);
dist[w]=dist[v] + 1;
}
if(dist[w]==dist[v] + 1){
sigma[w]=sigma[w] +sigma[v];
//P[w][]=v;
P[w][P[w].length] = v;
}
}
}
}
var delta=[];
for(var i=0; i<ncols; i++){
delta[i]=0;
}
while(stack.length>0){
Logger.log(new Date()+":stack length: "+stack.length);
w=stack.pop();
for(var i=0; i<P[w].length; i++){
v=P[w][i];
delta[v] +=(sigma[v] /sigma[w]) * (1 +delta[w]);
}
if(w != s){
betweenness[w] +=delta[w];
}
}
}
for (var i=0; i<ncols; i++){
betweenness[i]=[(betweenness[i]/(2))];
if (betweenness[i] > bMax) bMax = betweenness[i][0];
}
ScriptProperties.setProperty("Betweenness",bMax);
return betweenness;
}
function alltrim(str) {
return str.replace(/^\s+|\s+$/g, '');
}
// END OF (c)
 
function replicate (n, x) {
var xs = [];
for (var i = 0; i < n; ++i) {
xs.push(x);
}
return xs;
}
 
// http://jsfromhell.com/array/chunk
function chunk(a, s){
for(var x, i = 0, c = -1, l = a.length, n = []; i < l; i++)
(x = i % s) ? n[c][x] = a[i] : n[++c] = [a[i]];
return n;
}
// http://snook.ca/archives/javascript/testing_for_a_v
function oc(a)
{
var o = {};
for(var i=0;i<a.length;i++)
{
o[a[i]]='';
}
return o;
}
// Given a JavaScript 2d Array, this function returns the transposed table.
// Arguments:
// - data: JavaScript 2d Array
// Returns a JavaScript 2d Array
// Example: arrayTranspose([[1,2,3],[4,5,6]]) returns [[1,4],[2,5],[3,6]].
function arrayTranspose(data) {
if (data.length == 0 || data[0].length == 0) {
return null;
}
 
var ret = [];
for (var i = 0; i < data[0].length; ++i) {
ret.push([]);
}
 
for (var i = 0; i < data.length; ++i) {
for (var j = 0; j < data[i].length; ++j) {
ret[j][i] = data[i][j];
}
}
 
return ret;
}
 
// getColumnsData iterates column by column in the input range and returns an array of objects.
// Each object contains all the data for a given column, indexed by its normalized row name.
// [Modified by mhawksey]
// Arguments:
// - sheet: the sheet object that contains the data to be processed
// - range: the exact range of cells where the data is stored
// This argument is optional and it defaults to all the cells except those in the first column
// or all the cells below rowHeadersIndex (if defined).
// - columnHeadersIndex: specifies the row number where the column names are stored.
// This argument is optional and it defaults to the row immediately above range;
// Returns an Array of objects.
function getColumnsData(sheet, range, columnHeadersIndex) {
var headersIndex = columnHeadersIndex || range ? range.getColumnIndex() - 1 : 1;
var dataRange = range ||
sheet.getRange(1, headersIndex + 1, sheet.getMaxRows(), sheet.getMaxColumns()- headersIndex);
var numRows = dataRange.getLastRow() - dataRange.getRow() + 1;
var headersRange = sheet.getRange(dataRange.getRow(),headersIndex,numRows,1);
var headers = arrayTranspose(headersRange.getValues())[0];
return getObjects(arrayTranspose(dataRange.getValues()), normalizeHeaders(headers));
}
 
// setRowsData fills in one row of data per object defined in the objects Array.
// For every Column, it checks if data objects define a value for it.
// Arguments:
// - sheet: the Sheet Object where the data will be written
// - objects: an Array of Objects, each of which contains data for a row
// - optHeadersRange: a Range of cells where the column headers are defined. This
// defaults to the entire first row in sheet.
// - optFirstDataRowIndex: index of the first row where data should be written. This
// defaults to the row immediately below the headers.
function setRowsData(sheet, objects, optHeadersRange, optFirstDataRowIndex) {
var headersRange = optHeadersRange || sheet.getRange(1, 1, 1, sheet.getMaxColumns());
var firstDataRowIndex = optFirstDataRowIndex || headersRange.getRowIndex() + 1;
var headers = normalizeHeaders(headersRange.getValues()[0]);
 
var data = [];
for (var i = 0; i < objects.length; ++i) {
var values = []
for (j = 0; j < headers.length; ++j) {
var header = headers[j];
values.push(header.length > 0 && objects[i][header] ? objects[i][header] : "");
}
data.push(values);
}
 
var destinationRange = sheet.getRange(firstDataRowIndex, headersRange.getColumnIndex(),
objects.length, headers.length);
destinationRange.setValues(data);
}
// getRowsData iterates row by row in the input range and returns an array of objects.
// Each object contains all the data for a given row, indexed by its normalized column name.
// Arguments:
// - sheet: the sheet object that contains the data to be processed
// - range: the exact range of cells where the data is stored
// This argument is optional and it defaults to all the cells except those in the first row
// or all the cells below columnHeadersRowIndex (if defined).
// - columnHeadersRowIndex: specifies the row number where the column names are stored.
// This argument is optional and it defaults to the row immediately above range;
// Returns an Array of objects.
function getRowsData(sheet, range, columnHeadersRowIndex) {
var headersIndex = columnHeadersRowIndex || range ? range.getRowIndex() - 1 : 1;
var dataRange = range ||
sheet.getRange(headersIndex + 1, 1, sheet.getMaxRows() - headersIndex, sheet.getMaxColumns());
var numColumns = dataRange.getEndColumn() - dataRange.getColumn() + 1;
var headersRange = sheet.getRange(headersIndex, dataRange.getColumn(), 1, numColumns);
var headers = headersRange.getValues()[0];
return getObjects(dataRange.getValues(), normalizeHeaders(headers));
}
 
// For every row of data in data, generates an object that contains the data. Names of
// object fields are defined in keys.
// Arguments:
// - data: JavaScript 2d array
// - keys: Array of Strings that define the property names for the objects to create
function getObjects(data, keys) {
var objects = [];
for (var i = 0; i < data.length; ++i) {
var object = {};
var hasData = false;
for (var j = 0; j < data[i].length; ++j) {
var cellData = data[i][j];
if (isCellEmpty(cellData)) {
continue;
}
object[keys[j]] = cellData;
hasData = true;
}
if (hasData) {
objects.push(object);
}
}
return objects;
}
 
// Returns an Array of normalized Strings.
// Empty Strings are returned for all Strings that could not be successfully normalized.
// Arguments:
// - headers: Array of Strings to normalize
function normalizeHeaders(headers) {
var keys = [];
for (var i = 0; i < headers.length; ++i) {
keys.push(normalizeHeader(headers[i]));
}
return keys;
}
 
// Normalizes a string, by removing all alphanumeric characters and using mixed case
// to separate words. The output will always start with a lower case letter.
// This function is designed to produce JavaScript object property names.
// Arguments:
// - header: string to normalize
// Examples:
// "First Name" -> "firstName"
// "Market Cap (millions) -> "marketCapMillions
// "1 number at the beginning is ignored" -> "numberAtTheBeginningIsIgnored"
function normalizeHeader(header) {
var key = "";
var upperCase = false;
for (var i = 0; i < header.length; ++i) {
var letter = header[i];
if (letter == " " && key.length > 0) {
upperCase = true;
continue;
}
//if (!isAlnum(letter)) { // I removed this because result identifiers have '_' in name
// continue;
//}
if (key.length == 0 && isDigit(letter)) {
continue; // first character must be a letter
}
if (upperCase) {
upperCase = false;
key += letter.toUpperCase();
} else {
key += letter.toLowerCase();
}
}
return key;
}
 
// Returns true if the cell where cellData was read from is empty.
// Arguments:
// - cellData: string
function isCellEmpty(cellData) {
return typeof(cellData) == "string" && cellData == "";
}
 
// Returns true if the character char is alphabetical, false otherwise.
function isAlnum(char) {
return char >= 'A' && char <= 'Z' ||
char >= 'a' && char <= 'z' ||
isDigit(char);
}
 
// Returns true if the character char is a digit, false otherwise.
function isDigit(char) {
return char >= '0' && char <= '9';
}
 
// The first part of this code was developed by google and has a copyright statement.
// Everything after // Archive Twitter Status Updates is by mhawksey and released under CC
 
 
// Copyright 2010 Google Inc. All Rights Reserved.
 
 
/**
* @fileoverview Google Apps Script demo application to illustrate usage of:
* MailApp
* OAuthConfig
* ScriptProperties
* Twitter Integration
* UiApp
* UrlFetchApp
*
* @author vicfryzel@google.com (Vic Fryzel)
*/
 
/**
* Key of ScriptProperty for Twitter consumer key.
* @type {String}
* @const
*/
var CONSUMER_KEY_PROPERTY_NAME = "twitterConsumerKey";
 
/**
* Key of ScriptProperty for Twitter consumer secret.
* @type {String}
* @const
*/
var CONSUMER_SECRET_PROPERTY_NAME = "twitterConsumerSecret";
 
/**
* Key of ScriptProperty for tweets and all approvers.
* @type {String}
* @const
*/
var TWEETS_APPROVERS_PROPERTY_NAME = "twitterTweetsWithApprovers";
 
/**
* @param String Approver email address required to give approval
* prior to a tweet going live. Comma-delimited.
*/
function setApprovers(approvers) {
ScriptProperties.setProperty(APPROVERS_PROPERTY_NAME, approvers);
}
 
/**
* @return String OAuth consumer key to use when tweeting.
*/
function getConsumerKey() {
var key = ScriptProperties.getProperty(CONSUMER_KEY_PROPERTY_NAME);
if (key == null) {
key = "";
}
return key;
}
 
/**
* @param String OAuth consumer key to use when tweeting.
*/
function setConsumerKey(key) {
ScriptProperties.setProperty(CONSUMER_KEY_PROPERTY_NAME, key);
}
 
/**
* @return String OAuth consumer secret to use when tweeting.
*/
function getConsumerSecret() {
var secret = ScriptProperties.getProperty(CONSUMER_SECRET_PROPERTY_NAME);
if (secret == null) {
secret = "";
}
return secret;
}
 
/**
* @param String OAuth consumer secret to use when tweeting.
*/
function setConsumerSecret(secret) {
ScriptProperties.setProperty(CONSUMER_SECRET_PROPERTY_NAME, secret);
}
 
 
/**
* @return bool True if all of the configuration properties are set,
* false if otherwise.
*/
function isConfigured() {
return getConsumerKey() != "" && getConsumerSecret != "" ;
}
 
 
/** Retrieve config params from the UI and store them. */
function saveConfiguration(e) {
setConsumerKey(e.parameter.consumerKey);
setConsumerSecret(e.parameter.consumerSecret);
var app = UiApp.getActiveApplication();
app.close();
return app;
}
 
/**
* Authorize against Twitter. This method must be run prior to
* clicking any link in a script email. If you click a link in an
* email, you will get a message stating:
* "Authorization is required to perform that action."
*/
function authorize() {
var oauthConfig = UrlFetchApp.addOAuthService("twitter");
oauthConfig.setAccessTokenUrl(
"https://api.twitter.com/oauth/access_token");
oauthConfig.setRequestTokenUrl(
"https://api.twitter.com/oauth/request_token");
oauthConfig.setAuthorizationUrl(
"https://api.twitter.com/oauth/authorize");
oauthConfig.setConsumerKey(getConsumerKey());
oauthConfig.setConsumerSecret(getConsumerSecret());
var requestData = {
"method": "GET",
"oAuthServiceName": "twitter",
"oAuthUseToken": "always"
};
var result = UrlFetchApp.fetch(
"http://api.twitter.com/1/account/verify_credentials.json",
requestData);
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.