summaryrefslogtreecommitdiff
path: root/src/pkjs/index.js
blob: 129d3944f4eb37e819a0ca0bb1c61826f9adb9d3 (plain)
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
var Keys = require('message_keys');

var CSV_STORAGE_KEY = 'fastforge.backup.csv';
var CSV_UPDATED_AT_KEY = 'fastforge.backup.csv.updated_at';

function ensureArraySize(rows, total) {
  if (!rows || rows.length !== total) {
    return new Array(total);
  }
  return rows;
}

function storeCsv(rows) {
  var csv = rows.join('\n');
  localStorage.setItem(CSV_STORAGE_KEY, csv);
  localStorage.setItem(CSV_UPDATED_AT_KEY, new Date().toISOString());
  console.log('FastForge backup stored, bytes=' + csv.length);
}

function onAppMessage(event) {
  var payload = event.payload || {};
  var status = payload[Keys.EXPORT_STATUS];
  var sequence = payload[Keys.EXPORT_SEQUENCE];
  var total = payload[Keys.EXPORT_TOTAL];
  var row = payload[Keys.EXPORT_ROW];

  if (typeof status === 'string') {
    console.log('FastForge export status: ' + status);
  }

  if (typeof sequence !== 'number' || typeof total !== 'number' || typeof row !== 'string') {
    if (typeof status !== 'string') {
      console.log('FastForge backup chunk missing fields: ' + JSON.stringify(payload));
    }
    return;
  }

  var rows = ensureArraySize(onAppMessage.rows, total);
  rows[sequence] = row;
  onAppMessage.rows = rows;

  if (sequence + 1 === total) {
    storeCsv(rows);
    onAppMessage.rows = null;
  }
}

Pebble.addEventListener('ready', function() {
  console.log('FastForge companion ready');
});

Pebble.addEventListener('appmessage', onAppMessage);