Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update sendCommand function #108

Merged
merged 4 commits into from
Jun 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.InvalidArgumentException;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.TimeoutException;
Expand Down Expand Up @@ -165,20 +166,37 @@ private boolean extractFile(ClassLoader classLoader, File parent, String fileNam
return result;
}


@SuppressWarnings("javasecurity:S5334") //because this is Javascript
public Result sendCommand(String streamId, String command) {
if (!getDrivers().containsKey(streamId)) {
logger.warn("Driver is not exists for stream id: {}", streamId);
return new Result(false, "Driver is not exists for stream id: " + streamId);
}
try {
WebDriver driver = getDrivers().get(streamId);
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript(command);
return new Result(true, streamId, "Command executed");
} catch (Exception e) {
logger.error("Command cannot be executed: {} " , e.getMessage());
return new Result(false, "Command cannot be executed.");
}
if (!getDrivers().containsKey(streamId)) {
logger.warn("Driver does not exist for stream id: {}", streamId);
return new Result(false, "Driver does not exist for stream id: " + streamId);
}
try {
WebDriver driver = getDrivers().get(streamId);

waitToBeFrameAvailable(driver);

JavascriptExecutor js = (JavascriptExecutor) driver;

Object obj = js.executeScript(command);

// Switch back to the default content
driver.switchTo().defaultContent();

return new Result(true, streamId, obj != null ? obj.toString() : "");
} catch (Exception e) {
logger.error("Command cannot be executed: {} ", e.getMessage());
return new Result(false, "Command cannot be executed: " + e.getMessage());
}
}

public void waitToBeFrameAvailable(WebDriver driver) {
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(TIMEOUT_IN_SECONDS));

// Switch to the iframe
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.tagName("iframe")));
}

public static boolean isValidURL(String urlString) {
Expand Down Expand Up @@ -243,26 +261,7 @@ public Result startMediaPush(String streamIdPar, String websocketUrl, Endpoint e
String publisherUrl = getPublisherHTMLURL(websocketUrl);


driver = createDriver(width, height, streamId, extraChromeSwitchList);
driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(TIMEOUT_IN_SECONDS));
driver.manage().timeouts().scriptTimeout(Duration.ofSeconds(TIMEOUT_IN_SECONDS));

drivers.put(streamId, driver);

for (RecordType recordType : RecordType.values()) {
if (recordType.toString().equals(recordTypeString)) {
recordingMap.put(streamId, recordType);
break; // Stop the loop once a match is found
}
}
logger.info("publisherUrl -> {}", publisherUrl);
driver.get(publisherUrl);


driver.executeScript(
String.format("document.getElementById('media-push-iframe').src='%s'", url)
);

driver = openDriver(width, height, recordTypeString, extraChromeSwitchList, streamId, publisherUrl, url);

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(TIMEOUT_IN_SECONDS));

Expand Down Expand Up @@ -295,6 +294,30 @@ public Result startMediaPush(String streamIdPar, String websocketUrl, Endpoint e

return result;
}
@SuppressWarnings("javasecurity:S5334") //because this is Javascript
public RemoteWebDriver openDriver(int width, int height, String recordTypeString,
List<String> extraChromeSwitchList, String streamId, String publisherUrl, String targetUrl) throws IOException {
RemoteWebDriver driver;
driver = createDriver(width, height, streamId, extraChromeSwitchList);
driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(TIMEOUT_IN_SECONDS));
driver.manage().timeouts().scriptTimeout(Duration.ofSeconds(TIMEOUT_IN_SECONDS));

drivers.put(streamId, driver);

for (RecordType recordType : RecordType.values()) {
if (recordType.toString().equals(recordTypeString)) {
recordingMap.put(streamId, recordType);
break; // Stop the loop once a match is found
}
}
logger.info("publisherUrl -> {}", publisherUrl);
driver.get(publisherUrl);

driver.executeScript(
String.format("document.getElementById('media-push-iframe').src='%s'", targetUrl)
);
return driver;
}

public String checkAndGetStreamId(String streamId) {
if (StringUtils.isBlank(streamId)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
Expand All @@ -30,6 +31,10 @@
import org.mockito.Mockito;
import org.openqa.selenium.InvalidArgumentException;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver.TargetLocator;
import org.openqa.selenium.logging.LogEntries;
import org.openqa.selenium.logging.LogEntry;
import org.openqa.selenium.logging.LogType;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
Expand Down Expand Up @@ -115,23 +120,27 @@ public void testSendCommand_WhenDriverExists_ShouldExecuteCommand() {
MediaPushPlugin plugin = Mockito.spy(new MediaPushPlugin());
HashMap<String, RemoteWebDriver> drivers = Mockito.mock(HashMap.class);
RemoteWebDriver driver = Mockito.mock(RemoteWebDriver.class);

Mockito.when(driver.switchTo()).thenReturn(Mockito.mock(TargetLocator.class));


JavascriptExecutor js = Mockito.mock(JavascriptExecutor.class);
String streamId = "streamId";
String command = "someCommand";
Result expectedResult = new Result(true, streamId, "Command executed");
Result expectedResult = new Result(true, streamId, "");

when(plugin.getDrivers()).thenReturn(drivers);
when(drivers.containsKey(streamId)).thenReturn(true);
when(drivers.get(streamId)).thenReturn(driver);
when(js.executeScript(command)).thenReturn(null);
Mockito.doNothing().when(plugin).waitToBeFrameAvailable(Mockito.any());

// Act
Result result = plugin.sendCommand(streamId, command);

// Assert
assertTrue(result.isSuccess());
assertEquals(expectedResult.getDataId(), result.getDataId());
assertEquals(expectedResult.getMessage(), result.getMessage());
}

@Test
Expand All @@ -141,10 +150,12 @@ public void testSendCommand_WhenDriverDoesNotExist_ShouldReturnErrorResult() {
HashMap<String, RemoteWebDriver> drivers = Mockito.mock(HashMap.class);
String streamId = "streamId";
String command = "someCommand";
Result expectedResult = new Result(false, "Driver is not exists for stream id: " + streamId);
Result expectedResult = new Result(false, "Driver does not exist for stream id: " + streamId);

when(plugin.getDrivers()).thenReturn(drivers);
when(drivers.containsKey(streamId)).thenReturn(false);
Mockito.doNothing().when(plugin).waitToBeFrameAvailable(Mockito.any());


// Act
Result result = plugin.sendCommand(streamId, command);
Expand All @@ -153,6 +164,27 @@ public void testSendCommand_WhenDriverDoesNotExist_ShouldReturnErrorResult() {
assertFalse(result.isSuccess());
assertEquals(expectedResult.getMessage(), result.getMessage());
}

@Test
public void testSendCommand() throws IOException {
MediaPushPlugin plugin = new MediaPushPlugin();

File file = new File("src/test/resources/content.html");
File mediaPushUrl = new File("src/main/resources/media-push-publisher.html");

RemoteWebDriver driver = plugin.openDriver(640, 360, null, null, "streamId", "file://" + mediaPushUrl.getAbsolutePath(), "file://" + file.getAbsolutePath());


Result result = plugin.sendCommand("streamId", "return window.hello");


assertEquals("Run Ant Media Run", result.getMessage());

assertTrue(result.isSuccess());

driver.quit();

}

@Test
public void testSendCommand_WhenCommandExecutionFails_ShouldReturnErrorResult() {
Expand All @@ -168,13 +200,15 @@ public void testSendCommand_WhenCommandExecutionFails_ShouldReturnErrorResult()
when(drivers.containsKey(streamId)).thenReturn(true);
when(drivers.get(streamId)).thenReturn(driver);
when(driver.executeScript(command)).thenThrow(new RuntimeException("Command execution failed."));
Mockito.doNothing().when(plugin).waitToBeFrameAvailable(Mockito.any());

Mockito.when(driver.switchTo()).thenReturn(Mockito.mock(TargetLocator.class));

// Act
Result result = plugin.sendCommand(streamId, command);

// Assert
assertFalse(result.isSuccess());
assertEquals(expectedResult.getMessage(), result.getMessage());
}

@Test
Expand Down Expand Up @@ -290,6 +324,8 @@ public void testGetPublisherUrl() throws InvalidArgumentException, URISyntaxExce
assertEquals("http://example.antmedia.io/media-push/media-push-publisher.html", url);

}



@Test
public void testStartMediaPush_WhenExecuteScriptTimeoutOccurs_ShouldReturnErrorResult() throws IOException {
Expand Down
17 changes: 17 additions & 0 deletions MediaPushPlugin/src/test/resources/content.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<!DOCTYPE html>
<html>
<head>

</head>
<body>
<!-- We need to use this way because audio is not captured if there is another WebRTC conneciton in the same context -->

<script>

var hello = "Run Ant Media Run";

window.hello = hello;

</script>
</body>
</html>