aboutsummaryrefslogtreecommitdiffstats
path: root/data/lib/rpcutils.js
blob: d29fd6852261e1e27888086203e04f896468fa98 (plain) (blame)
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
//Released under the MIT/X11 license
//http://www.opensource.org/licenses/mit-license.php
"use strict";

/*
We should first login and then we shouldn't bother with it.
It could be interesting to know how many logins per second are bad.
 */

function JSONRPCLogin(callback) {
  if (!constantData.passwordState.password) {
    return;
  }

  console.myDebug("JSONRPCLogin: passObj = " +
    constantData.passwordState.toSource());
  makeJSONRPCCall("User.login", {
    login: getLogin(),
    password: constantData.passwordState.password,
    remember: false
  }, function(logResult) {
    callback();
  });
};


// Make a JSONL-RPC call ... most of the business logic should stay in the
// content script
// http://json-rpc.org/wd/JSON-RPC-1-1-WD-20060807.html
function makeJSONRPCCall(method, params, callback) {

  var msg = {
      "version": "1.1",
      "method": method,
      "params": params
  };

  console.myDebug("makeJSONRPCCall(" + method +
    "): out = " + JSON.stringify(msg));

  var req = new XMLHttpRequest();
  req.open('POST', "/jsonrpc.cgi", true);
  req.onreadystatechange = function (aEvt) {
    if (req.readyState == 4) {
      if(req.status == 200) {
        console.myDebug("makeJSONRPCCall (" + method +
          "): in = " + req.responseText);
        var JSONresponse = JSON.parse(req.responseText);
        if ("error" in JSONresponse) {
          throw new Error("Error in JSON-RPC call:\n" +
            JSONresponse.error);
        }
        callback(JSONresponse);
      }
      else {
        console.error('Error', req.statusText);
      }
    }
  };
  req.setRequestHeader('Content-Type', "application/json");
  req.send(JSON.stringify(msg));
};