edqx / node-scratch-client

A client for the scratch 3.0 website.
16 stars 7 forks source link

Cloud bug #5

Open qucchia opened 3 years ago

qucchia commented 3 years ago

Sometimes when trying to connect to the cloud like this:

Client.login().then(() => {
  let cloud = Client.session.createCloudSession(548738926);
  cloud.connect().then(() => {
    console.log("Successfully connected to cloud!");
    cloud.on("set", variable => {
      console.log("Cloud variable", variable.name, "set to", variable.value);
    });
  });
});

The following error appears:

undefined:2
{"method":"set","project_id":"548862682","name":"☁ CloudService response","value":"2410100100050202100307010909100703003819142363351915632419173523"}
^

SyntaxError: Unexpected token { in JSON at position 86
    at JSON.parse (<anonymous>)
    at WebSocket.<anonymous> (/home/runner/dictionary/node_modules/node-scratch-client/src/Struct/CloudSession.js:87:25)
    at WebSocket.emit (events.js:314:20)
    at WebSocket.EventEmitter.emit (domain.js:483:12)
    at Receiver.receiverOnMessage (/home/runner/dictionary/node_modules/node-scratch-client/node_modules/ws/lib/websocket.js:789:20)
    at Receiver.emit (events.js:314:20)
    at Receiver.EventEmitter.emit (domain.js:483:12)
    at Receiver.dataMessage (/home/runner/dictionary/node_modules/node-scratch-client/node_modules/ws/lib/receiver.js:422:14)
    at /home/runner/dictionary/node_modules/node-scratch-client/node_modules/ws/lib/receiver.js:379:23
    at /home/runner/dictionary/node_modules/node-scratch-client/node_modules/ws/lib/permessage-deflate.js:298:9

This is because sometimes the API sends multiple objects at once in a single string, like so:

`{"method":"set","project_id":"548862682","name":"☁ CloudService request","value":"0"}
{"method":"set","project_id":"548862682","name":"☁ CloudService response","value":"2410100100050202100307010909100703003819142363351915632419173523"}`

The way to solve this is simple. Separate the string by line to make an array of chunks, and run the code for every one of them, replacing the function on line 85 in src/Struct/CloudSession.js with this:

connection.on("message", function (chunks) {
  let chunksArr = chunks.split("\n");
  for (let i = 0; i < chunksArr.length; i++) {
    let chunk = chunksArr[i];
    if (!chunk) {
      continue;
    }
    let json = JSON.parse(chunk);

    _this._client._debugLog("CloudData: Received message: " + json);

    if (json.method === "set") {
      _this._variables[json.name]  = new CloudVariable(_this._client, {
        name: json.name,
        value: json.value
      });

      _this.emit("set", _this._variables[json.name]);
    } else {
      _this._client._debugLog("CloudData: Method not supported: " + json.method);
    }
  }
});