connection.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792
  1. import Websock from "./websock";
  2. import * as message from "./message.js";
  3. import * as rendezvous from "./rendezvous.js";
  4. import { loadVp9 } from "./codec";
  5. import * as sha256 from "fast-sha256";
  6. import * as globals from "./globals";
  7. import { decompress, mapKey, sleep } from "./common";
  8. const PORT = 21116;
  9. // only the first is used to init `HOST`
  10. const HOSTS = [
  11. "rs-sg.rustdesk.com",
  12. "rs-cn.rustdesk.com",
  13. "rs-us.rustdesk.com",
  14. ];
  15. let HOST = localStorage.getItem("rendezvous-server") || HOSTS[0];
  16. //根据协议设置为ws或wss
  17. const SCHEMA=location.protocol=="https:"?"wss://":"ws://";
  18. type MsgboxCallback = (type: string, title: string, text: string) => void;
  19. type DrawCallback = (data: Uint8Array) => void;
  20. //const cursorCanvas = document.createElement("canvas");
  21. export default class Connection {
  22. _msgs: any[];
  23. _ws: Websock | undefined;
  24. _interval: any;
  25. _id: string;
  26. _hash: message.Hash | undefined;
  27. _msgbox: MsgboxCallback;
  28. _draw: DrawCallback;
  29. _peerInfo: message.PeerInfo | undefined;
  30. _firstFrame: Boolean | undefined;
  31. _videoDecoder: any;
  32. _password: Uint8Array | undefined;
  33. _options: any;
  34. _videoTestSpeed: number[];
  35. //_cursors: { [name: number]: any };
  36. constructor() {
  37. this._msgbox = globals.msgbox;
  38. this._draw = globals.draw;
  39. this._msgs = [];
  40. this._id = "";
  41. this._videoTestSpeed = [0, 0];
  42. //this._cursors = {};
  43. }
  44. async start(id: string) {
  45. try {
  46. await this._start(id);
  47. } catch (e: any) {
  48. this.msgbox(
  49. "error",
  50. "Connection Error",
  51. e.type == "close" ? "Reset by the peer" : String(e)
  52. );
  53. }
  54. }
  55. async _start(id: string) {
  56. if (!this._options) {
  57. this._options = globals.getPeers()[id] || {};
  58. }
  59. if (!this._password) {
  60. const p = this.getOption("password");
  61. if (p) {
  62. try {
  63. this._password = Uint8Array.from(JSON.parse("[" + p + "]"));
  64. } catch (e) {
  65. console.error(e);
  66. }
  67. }
  68. }
  69. this._interval = setInterval(() => {
  70. while (this._msgs.length) {
  71. this._ws?.sendMessage(this._msgs[0]);
  72. this._msgs.splice(0, 1);
  73. }
  74. }, 1);
  75. this.loadVideoDecoder();
  76. const uri = getDefaultUri();
  77. const ws = new Websock(uri, true);
  78. this._ws = ws;
  79. this._id = id;
  80. console.log(
  81. new Date() + ": Conntecting to rendezvoous server: " + uri + ", for " + id
  82. );
  83. await ws.open();
  84. console.log(new Date() + ": Connected to rendezvoous server");
  85. const conn_type = rendezvous.ConnType.DEFAULT_CONN;
  86. const nat_type = rendezvous.NatType.SYMMETRIC;
  87. const punch_hole_request = rendezvous.PunchHoleRequest.fromPartial({
  88. id,
  89. licence_key: localStorage.getItem("key") || undefined,
  90. conn_type,
  91. nat_type,
  92. token: localStorage.getItem("access_token") || undefined,
  93. });
  94. ws.sendRendezvous({ punch_hole_request });
  95. const msg = (await ws.next()) as rendezvous.RendezvousMessage;
  96. ws.close();
  97. console.log(new Date() + ": Got relay response", msg);
  98. const phr = msg.punch_hole_response;
  99. const rr = msg.relay_response;
  100. if (phr) {
  101. if (phr?.other_failure) {
  102. this.msgbox("error", "Error", phr?.other_failure);
  103. return;
  104. }
  105. if (phr.failure != rendezvous.PunchHoleResponse_Failure.UNRECOGNIZED) {
  106. switch (phr?.failure) {
  107. case rendezvous.PunchHoleResponse_Failure.ID_NOT_EXIST:
  108. this.msgbox("error", "Error", "ID does not exist");
  109. break;
  110. case rendezvous.PunchHoleResponse_Failure.OFFLINE:
  111. this.msgbox("error", "Error", "Remote desktop is offline");
  112. break;
  113. case rendezvous.PunchHoleResponse_Failure.LICENSE_MISMATCH:
  114. this.msgbox("error", "Error", "Key mismatch");
  115. break;
  116. case rendezvous.PunchHoleResponse_Failure.LICENSE_OVERUSE:
  117. this.msgbox("error", "Error", "Key overuse");
  118. break;
  119. }
  120. }
  121. } else if (rr) {
  122. if (!rr.version) {
  123. this.msgbox("error", "Error", "Remote version is low, not support web");
  124. return;
  125. }
  126. await this.connectRelay(rr);
  127. }
  128. }
  129. async connectRelay(rr: rendezvous.RelayResponse) {
  130. const pk = rr.pk;
  131. let uri = rr.relay_server;
  132. if (uri) {
  133. uri = getrUriFromRs(uri, true, 2);
  134. } else {
  135. uri = getDefaultUri(true);
  136. }
  137. const uuid = rr.uuid;
  138. console.log(new Date() + ": Connecting to relay server: " + uri);
  139. const ws = new Websock(uri, false);
  140. await ws.open();
  141. console.log(new Date() + ": Connected to relay server");
  142. this._ws = ws;
  143. const request_relay = rendezvous.RequestRelay.fromPartial({
  144. licence_key: localStorage.getItem("key") || undefined,
  145. uuid,
  146. });
  147. ws.sendRendezvous({ request_relay });
  148. const secure = (await this.secure(pk)) || false;
  149. globals.pushEvent("connection_ready", { secure, direct: false });
  150. await this.msgLoop();
  151. }
  152. async secure(pk: Uint8Array | undefined) {
  153. if (pk) {
  154. const RS_PK = "OeVuKk5nlHiXp+APNn0Y3pC1Iwpwn44JGqrQCsWqmBw=";
  155. try {
  156. pk = await globals.verify(pk, localStorage.getItem("key") || RS_PK);
  157. if (pk) {
  158. const idpk = message.IdPk.decode(pk);
  159. if (idpk.id == this._id) {
  160. pk = idpk.pk;
  161. }
  162. }
  163. if (pk?.length != 32) {
  164. pk = undefined;
  165. }
  166. } catch (e) {
  167. console.error(e);
  168. pk = undefined;
  169. }
  170. if (!pk)
  171. console.error(
  172. "Handshake failed: invalid public key from rendezvous server"
  173. );
  174. }
  175. if (!pk) {
  176. // send an empty message out in case server is setting up secure and waiting for first message
  177. const public_key = message.PublicKey.fromPartial({});
  178. this._ws?.sendMessage({ public_key });
  179. return;
  180. }
  181. const msg = (await this._ws?.next()) as message.Message;
  182. let signedId: any = msg?.signed_id;
  183. if (!signedId) {
  184. console.error("Handshake failed: invalid message type");
  185. const public_key = message.PublicKey.fromPartial({});
  186. this._ws?.sendMessage({ public_key });
  187. return;
  188. }
  189. try {
  190. signedId = await globals.verify(signedId.id, Uint8Array.from(pk!));
  191. } catch (e) {
  192. console.error(e);
  193. // fall back to non-secure connection in case pk mismatch
  194. console.error("pk mismatch, fall back to non-secure");
  195. const public_key = message.PublicKey.fromPartial({});
  196. this._ws?.sendMessage({ public_key });
  197. return;
  198. }
  199. const idpk = message.IdPk.decode(signedId);
  200. const id = idpk.id;
  201. const theirPk = idpk.pk;
  202. if (id != this._id!) {
  203. console.error("Handshake failed: sign failure");
  204. const public_key = message.PublicKey.fromPartial({});
  205. this._ws?.sendMessage({ public_key });
  206. return;
  207. }
  208. if (theirPk.length != 32) {
  209. console.error(
  210. "Handshake failed: invalid public box key length from peer"
  211. );
  212. const public_key = message.PublicKey.fromPartial({});
  213. this._ws?.sendMessage({ public_key });
  214. return;
  215. }
  216. const [mySk, asymmetric_value] = globals.genBoxKeyPair();
  217. const secret_key = globals.genSecretKey();
  218. const symmetric_value = globals.seal(secret_key, theirPk, mySk);
  219. const public_key = message.PublicKey.fromPartial({
  220. asymmetric_value,
  221. symmetric_value,
  222. });
  223. this._ws?.sendMessage({ public_key });
  224. this._ws?.setSecretKey(secret_key);
  225. console.log("secured");
  226. return true;
  227. }
  228. async msgLoop() {
  229. while (true) {
  230. const msg = (await this._ws?.next()) as message.Message;
  231. // console.log("msg", msg);
  232. if (msg?.hash) {
  233. this._hash = msg?.hash;
  234. const tmp = this.getOption('tmppwd')
  235. if(!this._password && tmp){
  236. this._password = Uint8Array.from(JSON.parse("[" + tmp + "]"));
  237. this.setOption('tmppwd', '')
  238. }
  239. if (!this._password)
  240. this.msgbox("input-password", "Password Required", "");
  241. this.login();
  242. } else if (msg?.test_delay) {
  243. const test_delay = msg?.test_delay;
  244. console.log(test_delay);
  245. if (!test_delay.from_client) {
  246. this._ws?.sendMessage({ test_delay });
  247. }
  248. } else if (msg?.login_response) {
  249. const r = msg?.login_response;
  250. if (r.error) {
  251. if (r.error == "Wrong Password") {
  252. this._password = undefined;
  253. this.msgbox(
  254. "re-input-password",
  255. r.error,
  256. "Do you want to enter again?"
  257. );
  258. } else {
  259. this.msgbox("error", "Login Error", r.error);
  260. }
  261. } else if (r.peer_info) {
  262. this.handlePeerInfo(r.peer_info);
  263. }
  264. } else if (msg?.video_frame) {
  265. this.handleVideoFrame(msg?.video_frame!);
  266. } else if (msg?.clipboard) {
  267. const cb = msg?.clipboard;
  268. if (cb.compress) {
  269. const c = await decompress(cb.content);
  270. if (!c) continue;
  271. cb.content = c;
  272. }
  273. try {
  274. globals.copyToClipboard(new TextDecoder().decode(cb.content));
  275. } catch (e) {
  276. console.error(e);
  277. }
  278. // globals.pushEvent("clipboard", cb);
  279. } else if (msg?.cursor_data) {
  280. const cd = msg?.cursor_data;
  281. const c = await decompress(cd.colors);
  282. if (!c) continue;
  283. cd.colors = c;
  284. globals.pushEvent("cursor_data", cd);
  285. /*
  286. let ctx = cursorCanvas.getContext("2d");
  287. cursorCanvas.width = cd.width;
  288. cursorCanvas.height = cd.height;
  289. let imgData = new ImageData(
  290. new Uint8ClampedArray(c),
  291. cd.width,
  292. cd.height
  293. );
  294. ctx?.clearRect(0, 0, cd.width, cd.height);
  295. ctx?.putImageData(imgData, 0, 0);
  296. let url = cursorCanvas.toDataURL();
  297. const img = document.createElement("img");
  298. img.src = url;
  299. this._cursors[cd.id] = img;
  300. //cursorCanvas.width /= 2.;
  301. //cursorCanvas.height /= 2.;
  302. //ctx?.drawImage(img, cursorCanvas.width, cursorCanvas.height);
  303. url = cursorCanvas.toDataURL();
  304. document.body.style.cursor =
  305. "url(" + url + ")" + cd.hotx + " " + cd.hoty + ", default";
  306. console.log(document.body.style.cursor);
  307. */
  308. } else if (msg?.cursor_id) {
  309. globals.pushEvent("cursor_id", { id: msg?.cursor_id });
  310. } else if (msg?.cursor_position) {
  311. globals.pushEvent("cursor_position", msg?.cursor_position);
  312. } else if (msg?.misc) {
  313. if (!this.handleMisc(msg?.misc)) break;
  314. } else if (msg?.audio_frame) {
  315. globals.playAudio(msg?.audio_frame.data);
  316. }
  317. }
  318. }
  319. msgbox(type_: string, title: string, text: string) {
  320. this._msgbox?.(type_, title, text);
  321. }
  322. draw(frame: any) {
  323. this._draw?.(frame);
  324. globals.draw(frame);
  325. }
  326. close() {
  327. this._msgs = [];
  328. clearInterval(this._interval);
  329. this._ws?.close();
  330. this._videoDecoder?.close();
  331. }
  332. refresh() {
  333. const misc = message.Misc.fromPartial({ refresh_video: true });
  334. this._ws?.sendMessage({ misc });
  335. }
  336. setMsgbox(callback: MsgboxCallback) {
  337. this._msgbox = callback;
  338. }
  339. setDraw(callback: DrawCallback) {
  340. this._draw = callback;
  341. }
  342. login(password: string | undefined = undefined) {
  343. if (password) {
  344. const salt = this._hash?.salt;
  345. let p = hash([password, salt!]);
  346. this._password = p;
  347. const challenge = this._hash?.challenge;
  348. p = hash([p, challenge!]);
  349. this.msgbox("connecting", "Connecting...", "Logging in...");
  350. this._sendLoginMessage(p);
  351. } else {
  352. let p = this._password;
  353. if (p) {
  354. const challenge = this._hash?.challenge;
  355. p = hash([p, challenge!]);
  356. }
  357. this._sendLoginMessage(p);
  358. }
  359. }
  360. async reconnect() {
  361. this.close();
  362. await this.start(this._id);
  363. }
  364. _sendLoginMessage(password: Uint8Array | undefined = undefined) {
  365. const login_request = message.LoginRequest.fromPartial({
  366. username: this._id!,
  367. my_id: "web", // to-do
  368. my_name: "web", // to-do
  369. password,
  370. option: this.getOptionMessage(),
  371. video_ack_required: true,
  372. });
  373. this._ws?.sendMessage({ login_request });
  374. }
  375. getOptionMessage(): message.OptionMessage | undefined {
  376. let n = 0;
  377. const msg = message.OptionMessage.fromPartial({});
  378. const q = this.getImageQualityEnum(this.getImageQuality(), true);
  379. const yes = message.OptionMessage_BoolOption.Yes;
  380. if (q != undefined) {
  381. msg.image_quality = q;
  382. n += 1;
  383. }
  384. if (this._options["show-remote-cursor"]) {
  385. msg.show_remote_cursor = yes;
  386. n += 1;
  387. }
  388. if (this._options["lock-after-session-end"]) {
  389. msg.lock_after_session_end = yes;
  390. n += 1;
  391. }
  392. if (this._options["privacy-mode"]) {
  393. msg.privacy_mode = yes;
  394. n += 1;
  395. }
  396. if (this._options["disable-audio"]) {
  397. msg.disable_audio = yes;
  398. n += 1;
  399. }
  400. if (this._options["disable-clipboard"]) {
  401. msg.disable_clipboard = yes;
  402. n += 1;
  403. }
  404. return n > 0 ? msg : undefined;
  405. }
  406. sendVideoReceived() {
  407. const misc = message.Misc.fromPartial({ video_received: true });
  408. this._ws?.sendMessage({ misc });
  409. }
  410. handleVideoFrame(vf: message.VideoFrame) {
  411. if (!this._firstFrame) {
  412. this.msgbox("", "", "");
  413. this._firstFrame = true;
  414. }
  415. if (vf.vp9s) {
  416. const dec = this._videoDecoder;
  417. var tm = new Date().getTime();
  418. var i = 0;
  419. const n = vf.vp9s?.frames.length;
  420. vf.vp9s.frames.forEach((f) => {
  421. dec.processFrame(f.data.slice(0).buffer, (ok: any) => {
  422. i++;
  423. if (i == n) this.sendVideoReceived();
  424. if (ok && dec.frameBuffer && n == i) {
  425. this.draw(dec.frameBuffer);
  426. const now = new Date().getTime();
  427. var elapsed = now - tm;
  428. this._videoTestSpeed[1] += elapsed;
  429. this._videoTestSpeed[0] += 1;
  430. if (this._videoTestSpeed[0] >= 30) {
  431. console.log(
  432. "video decoder: " +
  433. parseInt(
  434. "" + this._videoTestSpeed[1] / this._videoTestSpeed[0]
  435. )
  436. );
  437. this._videoTestSpeed = [0, 0];
  438. }
  439. }
  440. });
  441. });
  442. }
  443. }
  444. handlePeerInfo(pi: message.PeerInfo) {
  445. this._peerInfo = pi;
  446. if (pi.displays.length == 0) {
  447. this.msgbox("error", "Remote Error", "No Display");
  448. return;
  449. }
  450. this.msgbox("success", "Successful", "Connected, waiting for image...");
  451. globals.pushEvent("peer_info", pi);
  452. const p = this.shouldAutoLogin();
  453. if (p) this.inputOsPassword(p);
  454. const username = this.getOption("info")?.username;
  455. if (username && !pi.username) pi.username = username;
  456. this.setOption("info", pi);
  457. if (this.getRemember()) {
  458. if (this._password?.length) {
  459. const p = this._password.toString();
  460. if (p != this.getOption("password")) {
  461. this.setOption("password", p);
  462. console.log("remember password of " + this._id);
  463. }
  464. }
  465. } else {
  466. this.setOption("password", undefined);
  467. }
  468. }
  469. shouldAutoLogin(): string {
  470. const l = this.getOption("lock-after-session-end");
  471. const a = !!this.getOption("auto-login");
  472. const p = this.getOption("os-password");
  473. if (p && l && a) {
  474. return p;
  475. }
  476. return "";
  477. }
  478. handleMisc(misc: message.Misc) {
  479. if (misc.audio_format) {
  480. globals.initAudio(
  481. misc.audio_format.channels,
  482. misc.audio_format.sample_rate
  483. );
  484. } else if (misc.chat_message) {
  485. globals.pushEvent("chat", { text: misc.chat_message.text });
  486. } else if (misc.permission_info) {
  487. const p = misc.permission_info;
  488. console.info("Change permission " + p.permission + " -> " + p.enabled);
  489. let name;
  490. switch (p.permission) {
  491. case message.PermissionInfo_Permission.Keyboard:
  492. name = "keyboard";
  493. break;
  494. case message.PermissionInfo_Permission.Clipboard:
  495. name = "clipboard";
  496. break;
  497. case message.PermissionInfo_Permission.Audio:
  498. name = "audio";
  499. break;
  500. default:
  501. return;
  502. }
  503. globals.pushEvent("permission", { [name]: p.enabled });
  504. } else if (misc.switch_display) {
  505. this.loadVideoDecoder();
  506. globals.pushEvent("switch_display", misc.switch_display);
  507. } else if (misc.close_reason) {
  508. this.msgbox("error", "Connection Error", misc.close_reason);
  509. this.close();
  510. return false;
  511. }
  512. return true;
  513. }
  514. getRemember(): Boolean {
  515. return this._options["remember"] || false;
  516. }
  517. setRemember(v: Boolean) {
  518. this.setOption("remember", v);
  519. }
  520. getOption(name: string): any {
  521. return this._options[name];
  522. }
  523. setOption(name: string, value: any) {
  524. if (value == undefined) {
  525. delete this._options[name];
  526. } else {
  527. this._options[name] = value;
  528. }
  529. this._options["tm"] = new Date().getTime();
  530. const peers = globals.getPeers();
  531. peers[this._id] = this._options;
  532. localStorage.setItem("peers", JSON.stringify(peers));
  533. }
  534. inputKey(
  535. name: string,
  536. down: boolean,
  537. press: boolean,
  538. alt: Boolean,
  539. ctrl: Boolean,
  540. shift: Boolean,
  541. command: Boolean
  542. ) {
  543. const key_event = mapKey(name, globals.isDesktop());
  544. if (!key_event) return;
  545. if (alt && (name == "VK_MENU" || name == "RAlt")) {
  546. alt = false;
  547. }
  548. if (ctrl && (name == "VK_CONTROL" || name == "RControl")) {
  549. ctrl = false;
  550. }
  551. if (shift && (name == "VK_SHIFT" || name == "RShift")) {
  552. shift = false;
  553. }
  554. if (command && (name == "Meta" || name == "RWin")) {
  555. command = false;
  556. }
  557. key_event.down = down;
  558. key_event.press = press;
  559. key_event.modifiers = this.getMod(alt, ctrl, shift, command);
  560. this._ws?.sendMessage({ key_event });
  561. }
  562. ctrlAltDel() {
  563. const key_event = message.KeyEvent.fromPartial({ down: true });
  564. if (this._peerInfo?.platform == "Windows") {
  565. key_event.control_key = message.ControlKey.CtrlAltDel;
  566. } else {
  567. key_event.control_key = message.ControlKey.Delete;
  568. key_event.modifiers = this.getMod(true, true, false, false);
  569. }
  570. this._ws?.sendMessage({ key_event });
  571. }
  572. inputString(seq: string) {
  573. const key_event = message.KeyEvent.fromPartial({ seq });
  574. this._ws?.sendMessage({ key_event });
  575. }
  576. switchDisplay(display: number) {
  577. const switch_display = message.SwitchDisplay.fromPartial({ display });
  578. const misc = message.Misc.fromPartial({ switch_display });
  579. this._ws?.sendMessage({ misc });
  580. }
  581. async inputOsPassword(seq: string) {
  582. this.inputMouse();
  583. await sleep(50);
  584. this.inputMouse(0, 3, 3);
  585. await sleep(50);
  586. this.inputMouse(1 | (1 << 3));
  587. this.inputMouse(2 | (1 << 3));
  588. await sleep(1200);
  589. const key_event = message.KeyEvent.fromPartial({ press: true, seq });
  590. this._ws?.sendMessage({ key_event });
  591. }
  592. lockScreen() {
  593. const key_event = message.KeyEvent.fromPartial({
  594. down: true,
  595. control_key: message.ControlKey.LockScreen,
  596. });
  597. this._ws?.sendMessage({ key_event });
  598. }
  599. getMod(alt: Boolean, ctrl: Boolean, shift: Boolean, command: Boolean) {
  600. const mod: message.ControlKey[] = [];
  601. if (alt) mod.push(message.ControlKey.Alt);
  602. if (ctrl) mod.push(message.ControlKey.Control);
  603. if (shift) mod.push(message.ControlKey.Shift);
  604. if (command) mod.push(message.ControlKey.Meta);
  605. return mod;
  606. }
  607. inputMouse(
  608. mask: number = 0,
  609. x: number = 0,
  610. y: number = 0,
  611. alt: Boolean = false,
  612. ctrl: Boolean = false,
  613. shift: Boolean = false,
  614. command: Boolean = false
  615. ) {
  616. const mouse_event = message.MouseEvent.fromPartial({
  617. mask,
  618. x,
  619. y,
  620. modifiers: this.getMod(alt, ctrl, shift, command),
  621. });
  622. this._ws?.sendMessage({ mouse_event });
  623. }
  624. toggleOption(name: string) {
  625. const v = !this._options[name];
  626. const option = message.OptionMessage.fromPartial({});
  627. const v2 = v
  628. ? message.OptionMessage_BoolOption.Yes
  629. : message.OptionMessage_BoolOption.No;
  630. switch (name) {
  631. case "show-remote-cursor":
  632. option.show_remote_cursor = v2;
  633. break;
  634. case "disable-audio":
  635. option.disable_audio = v2;
  636. break;
  637. case "disable-clipboard":
  638. option.disable_clipboard = v2;
  639. break;
  640. case "lock-after-session-end":
  641. option.lock_after_session_end = v2;
  642. break;
  643. case "privacy-mode":
  644. option.privacy_mode = v2;
  645. break;
  646. case "block-input":
  647. option.block_input = message.OptionMessage_BoolOption.Yes;
  648. break;
  649. case "unblock-input":
  650. option.block_input = message.OptionMessage_BoolOption.No;
  651. break;
  652. default:
  653. return;
  654. }
  655. if (name.indexOf("block-input") < 0) this.setOption(name, v);
  656. const misc = message.Misc.fromPartial({ option });
  657. this._ws?.sendMessage({ misc });
  658. }
  659. getImageQuality() {
  660. return this.getOption("image-quality");
  661. }
  662. getImageQualityEnum(
  663. value: string,
  664. ignoreDefault: Boolean
  665. ): message.ImageQuality | undefined {
  666. switch (value) {
  667. case "low":
  668. return message.ImageQuality.Low;
  669. case "best":
  670. return message.ImageQuality.Best;
  671. case "balanced":
  672. return ignoreDefault ? undefined : message.ImageQuality.Balanced;
  673. default:
  674. return undefined;
  675. }
  676. }
  677. setImageQuality(value: string) {
  678. this.setOption("image-quality", value);
  679. const image_quality = this.getImageQualityEnum(value, false);
  680. if (image_quality == undefined) return;
  681. const option = message.OptionMessage.fromPartial({ image_quality });
  682. const misc = message.Misc.fromPartial({ option });
  683. this._ws?.sendMessage({ misc });
  684. }
  685. loadVideoDecoder() {
  686. this._videoDecoder?.close();
  687. loadVp9((decoder: any) => {
  688. this._videoDecoder = decoder;
  689. console.log("vp9 loaded");
  690. console.log(decoder);
  691. });
  692. }
  693. }
  694. function testDelay() {
  695. var nearest = "";
  696. HOSTS.forEach((host) => {
  697. const now = new Date().getTime();
  698. new Websock(getrUriFromRs(host), true).open().then(() => {
  699. console.log("latency of " + host + ": " + (new Date().getTime() - now));
  700. if (!nearest) {
  701. HOST = host;
  702. localStorage.setItem("rendezvous-server", host);
  703. }
  704. });
  705. });
  706. }
  707. testDelay();
  708. function getDefaultUri(isRelay: Boolean = false): string {
  709. const host = localStorage.getItem("custom-rendezvous-server");
  710. return getrUriFromRs(host || HOST, isRelay);
  711. }
  712. /*
  713. function isHttps() {
  714. return window.location.protocol === "https:"
  715. }
  716. function domain(uri: string) {
  717. return uri.indexOf(":") > 0 ? uri.split(":")[0] : uri
  718. }*/
  719. function getrUriFromRs(
  720. uri: string,
  721. isRelay: Boolean = false,
  722. roffset: number = 0
  723. ): string {
  724. //v2
  725. //if (isHttps()) return "wss://" + domain(uri) + "/ws/" + (isRelay ? "relay" : "id");
  726. if (uri.indexOf(":") > 0) {
  727. const tmp = uri.split(":");
  728. const port = parseInt(tmp[1]);
  729. uri = tmp[0] + ":" + (port + (isRelay ? roffset || 3 : 2));
  730. } else {
  731. uri += ":" + (PORT + (isRelay ? 3 : 2));
  732. }
  733. return SCHEMA + uri;
  734. }
  735. function hash(datas: (string | Uint8Array)[]): Uint8Array {
  736. const hasher = new sha256.Hash();
  737. datas.forEach((data) => {
  738. if (typeof data == "string") {
  739. data = new TextEncoder().encode(data);
  740. }
  741. return hasher.update(data);
  742. });
  743. return hasher.digest();
  744. }