SyntaxERROR

Silveress's Gw2 Script

Mar 7th, 2015
880
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Varibles
  2.     $sheetname    = "Data";
  3.     $logsheetname = "Log";
  4.     $startRow     = 3;
  5.  
  6. // refresh
  7.     function refresh(){
  8.       expireCache();
  9.       updateAll();
  10.       updategems();
  11.     }
  12.     function refreshdata(){
  13.       $cache = CacheService.getPublicCache();
  14.     }
  15. // Updating Function
  16.    function updateAll() {    
  17.  
  18.     $url = [];
  19.     var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName($sheetname);
  20.     var noIDs = 100;
  21.     var IDListLength = sheet.getLastRow();
  22.     var repeatRough = IDListLength / noIDs;
  23.     var repeat = Math.ceil(repeatRough);
  24.    
  25.      for (var i = 0; i < repeat;){
  26.         var selection = i * noIDs;
  27.         var row = $startRow + selection;
  28.         var idlist0 = sheet.getRange(row, 1, noIDs, 1).getValues();
  29.         var idlist1 = "http://www.gw2spidy.com/api/v0.9/json/items/all/?filter_ids="  // Base
  30.         var idlist2 = idlist0.join(",");
  31.         var idlist3 = idlist1 +" "+ idlist2;
  32.         $url.push(idlist3)
  33.         i++
  34.         }
  35.     updateRawData($url, $sheetname, $logsheetname);  
  36.     }
  37.  
  38.    
  39. // expire the cache by setting the cache status to null
  40.  
  41.   function expireCache() {
  42.     $cache = CacheService.getPublicCache();
  43.     $cache.remove("Cache Status");
  44.   };
  45.  
  46. // Clear the Log
  47. function clearLog() {
  48.      $shee = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Log");
  49.      $shee.getRange(2, 1, $shee.getLastRow(), 6).clearContent();
  50.   };
  51.        
  52. // Menu
  53.                 function onOpen() {
  54.         var ui = SpreadsheetApp.getUi();
  55.         // Or DocumentApp or FormApp.
  56.         ui.createMenu('Investment Tools')
  57.         .addItem('Refresh', 'refresh')
  58.         .addSeparator()
  59.         .addItem('Clear Log', 'clearLog')
  60.         .addToUi();
  61. }
  62. // removes characters that could crash a JSON parse
  63.  
  64.   function makeJSONsafe($unsafe) {
  65.     $safe = $unsafe.replace(/(\u000A)+|(\n)+|\u000A|(\u000D)+|\u000D|\u000A\u000D|\n\r/g, ' ');
  66.     return $safe;
  67.   };
  68.  
  69. // retrives JSON from Spidy and adds item data to the cache
  70.  
  71.   function add2CacheFromSpidy($JSONURL) {
  72.     var $options = { "muteHttpExceptions" : true };        // muting HTTP exceptions prevents script from crashing with HTTP error
  73.  
  74.     var $cache = CacheService.getPublicCache();            // open the cache using Google's CacheService
  75.     var $message = "";
  76.     $cache.put("Cache Status", "Cache update in progress when data refresh called.");
  77.     var i = 0
  78.    
  79.     while (i < $JSONURL.length) {
  80.         var $jsonData = UrlFetchApp.fetch($JSONURL[i], $options); // fetch the HTTPResponse Object using Google's URLFetchApp
  81.         if ($jsonData.getResponseCode() == 200) {                      // successful connection
  82.           var $jsonString = $jsonData.getContentText();                // retrive JSON string from HTTPResponse Object
  83.           var $spidyObject = JSON.parse(makeJSONsafe($jsonString));    // convert JSON string into a JSON Object
  84.           var $itemsList = $spidyObject.results;                       // retrive array of item objects from Spidy JSON Object results parameter  
  85.           var $numItems = $spidyObject.count;                          // retrive number of items from Spidy JSON Object count paramter
  86.           for (var $j = 0; $j < $numItems; $j++) {                                    // caching loop - each item is stored as an object within the
  87.             $cache.put("" + $itemsList[$j].data_id, JSON.stringify($itemsList[$j]));  // items list array which is indexed from 0 - $count
  88.           }                                                                           // this loop takes those objects converts them into a JSON string and
  89.                                                                                       // stores them in the cache indexed by the spidy item id
  90.    
  91.           $message = "" + $numItems + " items retrived from GW2Spidy and cached.";
  92.           $cache.put("Cache Status", $message, 900);  // this is used as a flag to determine if the cache data is fresh (900 seconds)
  93.           $message = "";
  94.           $cache.put("Connection Error", $message);   // reset error message as it is a flag for if there is an error
  95.         } else {                                      // unsuccessful connection
  96.           $message = "HTTP Error " + $jsonData.getResponseCode() + " during connection attempt";
  97.           $cache.put("Connection Error", $message);   // set error message    
  98.         }
  99.     i++
  100.     }
  101.   };
  102.  
  103.   function writeToLog($message, $date, $sheet, $flag) {
  104.     if ($flag) {
  105.       var $row = $sheet.getLastRow()+1;
  106.       $sheet.getRange($row, 2).setValue($date);
  107.       $sheet.getRange($row, 3).setValue($message);
  108.     }
  109.   };
  110.  
  111. // work horse function, pulls everything together
  112.   function updateRawData($url, $sheetName, $logsheetName) {
  113.     var $cache = CacheService.getPublicCache();                                     // open the cache
  114.     var $sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName($sheetName);  // get sheet to write data too
  115.     var $logFlag = 0;
  116.     if ($logsheetName != "") {
  117.       var $logsheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName($logsheetName);
  118.       $logFlag = 1;                                                                 // only log is a logsheet is specified
  119.     }
  120.    if ($cache.get("Cache Status") == null)    // if Cache Status is null data is old
  121.     { writeToLog("Cache update started.", new Date(), $logsheet, $logFlag);
  122.       add2CacheFromSpidy($url);                // update the cache from URL
  123.       $cache = CacheService.getPublicCache();  // refresh cache variable (is this a pointer? can i get rid of this line?
  124.       //writeToLog($cache.get("Cache Status"), new Date(), $logsheet, $logFlag);
  125.     }
  126.      
  127.     if ($cache.get("Connection Error") == "" || $cache.get("Connection Error") == null) {  
  128.       var $IDList = $sheet.getRange(3, 1, $sheet.getLastRow() - 2, 1).getValues();  // returns 2-D array [row][column] with id stored, [[id1], [id2], etc.]
  129.       $itemList = fetchCachedData($IDList, $cache);                                 // fetches the cached data and returns 2D Array [row][column]
  130.       $sheet.getRange(3, 2, $IDList.length, 5).setValues($itemList);               // write data to spreadsheet
  131.  
  132.       writeToLog("Detected " + $IDList.length + " ID(s) in sheet " + $sheetName + ". Data refreshed successfully.", new Date(), $logsheet, $logFlag);
  133.     } else {
  134.       writeToLog($cache.get("Connection Error"), new Date(), $logsheet, $logFlag);
  135.     }
  136.   };
  137.  
  138.  
  139. // take range contained IDs and return 2D array of data from the cache
  140.   function fetchCachedData($IDList, $cache) {
  141.     var $itemObject = null;
  142.     var $id = 0;
  143.     var $itemList = new Array($IDList.length);    
  144.     for (var $i = 0; $i < $IDList.length; $i++) {    
  145.       $id = $IDList[$i][0]; // due to the way the getRange function works, the IDs are in a 2D array [[id1], [id2], [id3], ... [idn]]
  146.       $itemObject = JSON.parse($cache.get($id));  // convert JSON text in cache into an object
  147.       $itemList[$i] = new Array(5);
  148.       if (($id > 0) && ($itemObject != null)) {   // convert object into an array
  149.         $itemList[$i][0] = $itemObject.name;        
  150.         $itemList[$i][1] = $itemObject.max_offer_unit_price;
  151.         $itemList[$i][2] = $itemObject.min_sale_unit_price;
  152.         $itemList[$i][3] = $itemObject.price_last_changed;
  153.         $itemList[$i][4] = "=(OFFSET(INDIRECT(ADDRESS(ROW(), COLUMN())),-1,0)+1)";        
  154.         }
  155.       else {
  156.         $itemList[$i][0] = "Error: ID not in cache";
  157.         $itemList[$i][4] = "=(OFFSET(INDIRECT(ADDRESS(ROW(), COLUMN())),-1,0)+1)";
  158.       }
  159.     }    
  160.     return $itemList;
  161.   };
  162.  
  163.  
  164. // Gems
  165.  
  166.   function updategems(){
  167.   var gems = "http://www.gw2spidy.com/api/v0.9/json/gem-price";
  168.   var jsonData = UrlFetchApp.fetch(gems);
  169.   var jsonString = jsonData.getContentText();
  170.   var jsonObject = JSON.parse(jsonString).result; // create object and remove "result" wrapper
  171.   var buyValuea = (jsonObject.gold_to_gem);
  172.   var sellValuea = (jsonObject.gem_to_gold);
  173.   var buyValue = buyValuea/100;
  174.   var sellValue = sellValuea/100;
  175.   return [buyValue, sellValue];
  176. }
Advertisement
Add Comment
Please, Sign In to add comment