Widget:CollectionTrackerStateJS

From Granblue Fantasy Wiki
Jump to navigation Jump to search
<script type="application/javascript">
// Widget:CollectionTrackerStateJS
;(function() {
  'use strict';
  
  let M = {};
  let collection = null;

  const Base64ToUint8Array = function(text) {
    let s = text.replace('_', '/'); // 63rd char of encoding
    s = s.replace('-', '+'); // 62nd char of encoding
    let pl = (s.length % 4);
    if (pl > 0)
      s += '='.repeat(4-pl); // Restore any trailing '='s

    let binary = window.atob(s);
    let len = binary.length;
    let result = new Uint8Array(len);
    for (let i = 0; i < len; i++)
      result[i] = binary.charCodeAt(i);
    return result;
  };
  const readCollection = function() {
    let hash = localStorage.collectionTrackerState;
    const separator = (hash.indexOf(";") > 0) ? ";" : ".";
    let parts = hash.split(separator);
    for (let i = 1; i <= 7; i++)
      if (typeof parts[i] !== 'string')
        parts[i] = '';
    let strings = {
      'c': {2: parts[3], 3: parts[2], 4: parts[1]},
      's': {2: parts[6], 3: parts[5], 4: parts[4]},
    };
    collection = {s: {}, c: {}};
    ['c', 's'].forEach(function(type) {
      for (let rarity = 2; rarity < 5; rarity++) {
        let str = strings[type][rarity];
        if(str.length < 1)
          continue;
        let buffer = Base64ToUint8Array(str);
        let len = buffer.length / 3;
        for (let i = 0; i < len; i++) {
          let evos = 0;
          evos |= (buffer[i*3  ] <<  0);
          evos |= (buffer[i*3+1] <<  8);
          evos |= (buffer[i*3+2] << 16);

          for (let j = 0; j < 8; j++) {
            let evo = (evos >> (j*3)) & 0x07;
            if (evo <= 0)
              continue;
            let short_id = '' + rarity + ('000'+(i*8+j)).slice(-3);
            collection[type][short_id] = evo;
          }
        }
      };
    });
  };
  
  M.hasSavedData = function() {
    try {
      return localStorage.hasOwnProperty("collectionTrackerState") && localStorage.collectionTrackerState.length > 5;
    } catch {
      return false;
    }
  };
  
  M.isObtained = function(shortId, collectableType) {
    collectableType = collectableType == 's' ? 's' : 'c';
    if (collection === null) readCollection();
    if (collection === null) return false;
    return (collection[collectableType][shortId] || 0) > 0;
  };
  
  window.CollectionTrackerState = M;
})();
</script>