Skip to content

Commit

Permalink
Make requested changes
Browse files Browse the repository at this point in the history
  • Loading branch information
MilapNaik committed Nov 1, 2023
1 parent 4d55f59 commit 3335532
Show file tree
Hide file tree
Showing 3 changed files with 67 additions and 93 deletions.
60 changes: 49 additions & 11 deletions src/BrightScriptCommands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { util as rokuDebugUtil } from 'roku-debug/dist/util';
import type { RemoteControlManager, RemoteControlModeInitiator } from './managers/RemoteControlManager';
import type { WhatsNewManager } from './managers/WhatsNewManager';
import type { ActiveDeviceManager } from './ActiveDeviceManager';
import * as xml2js from 'xml2js';

export class BrightScriptCommands {

Expand Down Expand Up @@ -263,20 +264,21 @@ export class BrightScriptCommands {
}
});

this.registerCommand('openQuickInputBox', async (url: string, placeholder: string, appNames: vscode.QuickPickItem[]) => {
const stuffUserTyped = await util.showQuickPickInputBox({
placeholder: placeholder,
items: appNames,
returnDetail: true
});
this.registerCommand('openRegistry', async (host: string) => {
if (!host) {
host = await this.getRemoteHost();
}
const apps = await util.httpGet(`http://${host}:8060/query/apps`);
let parsedApps = this.parseXmlResponse(apps.body);
const selectedApp = await vscode.window.showQuickPick(parsedApps, { placeHolder: 'Which app would you like to see the registry for?' });

if (stuffUserTyped) {
const appId = stuffUserTyped.replace('App ID: ', '');
const newUrl = url.replace('{appId}', appId);
if (selectedApp) {
const appId = (selectedApp as any).appId;
let url = `http://${host}:8060/query/registry/${appId}`;
try {
await vscode.env.openExternal(vscode.Uri.parse(newUrl));
await vscode.env.openExternal(vscode.Uri.parse(url));
} catch (error) {
await vscode.window.showErrorMessage(`Tried to open url but failed: ${newUrl}`);
await vscode.window.showErrorMessage(`Tried to open url but failed: ${url}`);
}
}
});
Expand Down Expand Up @@ -439,4 +441,40 @@ export class BrightScriptCommands {
private async sendAsciiToDevice(character: string) {
await this.sendRemoteCommand(character, undefined, true);
}

private parseXmlResponse(responseData) {
let appNames: vscode.QuickPickItem[] = [];

// Extract the XML content
const xmlStartIndex = responseData.indexOf('<?xml');
const xmlContent = responseData.slice(xmlStartIndex);
xml2js.parseString(xmlContent, (err, result) => {
if (err) {
console.error('Error parsing XML:', err);
return;
}

appNames = result.apps.app
// Map the XML data to QuickPickItem objects
.map((appData: any) => {
return {
label: appData._,
detail: `ID: ${appData.$.id}`,
description: `${appData.$.version}`,
appId: `${appData.$.id}`
} as vscode.QuickPickItem;
})
// Have the app with id 'dev' be at the top
.sort((a, b) => {
if (a.appId === 'dev') {
return -1;
}
if (b.appId === 'dev') {
return 1;
}
return a.label.localeCompare(b.label);
});
});
return appNames;
}
}
15 changes: 15 additions & 0 deletions src/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@ import * as url from 'url';
import { debounce } from 'debounce';
import * as vscode from 'vscode';
import { Cache } from 'brighterscript/dist/Cache';
import * as r from 'postman-request';
import type { Response } from 'request';
import type * as requestType from 'request';
const request = r as typeof requestType;

class Util {
public async readDir(dirPath: string) {
Expand Down Expand Up @@ -385,6 +389,17 @@ class Util {
public escapeRegex(text: string) {
return text?.toString().replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}

/**
* Do an http GET request
*/
public httpGet(url: string) {
return new Promise<Response>((resolve, reject) => {
request.get(url, (err, response) => {
return err ? reject(err) : resolve(response);
});
});
}
}

const util = new Util();
Expand Down
85 changes: 3 additions & 82 deletions src/viewProviders/OnlineDevicesViewProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import { firstBy } from 'thenby';
import { util } from '../util';
import { ViewProviderId } from './ViewProviderId';
import { Socket } from 'net';
import * as xml2js from 'xml2js';

/**
* A sequence used to generate unique IDs for tree items that don't care about having a key
Expand Down Expand Up @@ -51,80 +50,7 @@ export class OnlineDevicesViewProvider implements vscode.TreeDataProvider<vscode

private devices: Array<RokuDeviceDetails>;

private async getAppData(deviceIp: string): Promise<vscode.QuickPickItem[]> {
return new Promise<vscode.QuickPickItem[]>((resolve, reject) => {
const appNames: vscode.QuickPickItem[] = [];
const client: Socket = new Socket();
const port = 8060;

const httpRequest = `GET /query/apps HTTP/1.1\r\n` +
`Host: ${deviceIp}:${port}\r\n` +
`Connection: close\r\n\r\n`;
client.connect({ host: deviceIp, port: port }, () => {
client.write(httpRequest);
});

let responseData = '';
client.on('data', (data) => {
responseData += data.toString();
});

client.on('end', () => {
try {
const parsedData = this.parseXmlResponse(responseData);
resolve(parsedData);
} catch (error) {
console.error('Error:', error);
reject(error);
} finally {
client.end();
}
});

client.on('error', (error) => {
console.error(`Error: ${error.message}`);
client.destroy();
reject(error);
});
});
}

private parseXmlResponse(responseData) {
let appNames: vscode.QuickPickItem[] = [];

// Extract the XML content
const xmlStartIndex = responseData.indexOf('<?xml');
const xmlContent = responseData.slice(xmlStartIndex);
xml2js.parseString(xmlContent, (err, result) => {
if (err) {
console.error('Error parsing XML:', err);
return;
}

appNames = result.apps.app
// Map the XML data to QuickPickItem objects
.map((appData: any) => {
return {
label: appData._,
detail: `App ID: ${appData.$.id}`,
description: `${appData.$.version}`
} as vscode.QuickPickItem;
})
// Have the app with id 'dev' be at the top
.sort((a, b) => {
if (a.detail === 'App ID: dev') {
return -1;
}
if (b.detail === 'App ID: dev') {
return 1;
}
return a.label.localeCompare(b.label);
});
});
return appNames;
}

async getChildren(element?: DeviceTreeItem | DeviceInfoTreeItem): Promise<DeviceTreeItem[] | DeviceInfoTreeItem[]> {
getChildren(element?: DeviceTreeItem | DeviceInfoTreeItem): vscode.ProviderResult<DeviceTreeItem[] | DeviceInfoTreeItem[]> {
if (!element) {
if (this.devices) {
let items: DeviceTreeItem[] = [];
Expand Down Expand Up @@ -216,9 +142,6 @@ export class OnlineDevicesViewProvider implements vscode.TreeDataProvider<vscode

if (semver.satisfies(element.details['software-version'], '>=11')) {
// TODO: add ECP system hooks here in the future (like registry call, etc...)
let appNames: vscode.QuickPickItem[] = [];
appNames = await this.getAppData(device.ip);

result.unshift(
this.createDeviceInfoTreeItem({
label: '🔗 View Registry',
Expand All @@ -227,11 +150,9 @@ export class OnlineDevicesViewProvider implements vscode.TreeDataProvider<vscode
tooltip: 'View the ECP Registry',
description: device.ip,
command: {
command: 'extension.brightscript.openQuickInputBox',
command: 'extension.brightscript.openRegistry',
title: 'Open',
arguments: [`http://${device.ip}:8060/query/registry/{appId}`,
'Which app would you like to see the registry for?',
appNames]
arguments: [device.ip]
}
})
);
Expand Down

0 comments on commit 3335532

Please sign in to comment.