Search in sources :

Example 1 with StepikApiClient

use of org.stepik.api.client.StepikApiClient in project intellij-plugins by StepicOrg.

the class StepikAuthManager method initStepikApiClient.

@NotNull
private static synchronized StepikApiClient initStepikApiClient() {
    String osName = System.getProperty("os.name");
    String jre = System.getProperty("java.version");
    String userAgent = String.format("Stepik Union/%s (%s) StepikApiClient/%s %s/%s JRE/%s", getVersion(), osName, StepikApiClient.getVersion(), getCurrentProduct(), getCurrentProductVersion(), jre);
    logger.info(userAgent);
    HttpConfigurable instance = HttpConfigurable.getInstance();
    StepikApiClient client;
    if (instance.USE_HTTP_PROXY) {
        logger.info(String.format("Uses proxy: Host = %s, Port = %s", instance.PROXY_HOST, instance.PROXY_PORT));
        HttpTransportClient transportClient;
        transportClient = HttpTransportClient.getInstance(instance.PROXY_HOST, instance.PROXY_PORT, userAgent);
        client = new StepikApiClient(transportClient);
    } else {
        client = new StepikApiClient(userAgent);
    }
    long lastUserId = getLastUser();
    TokenInfo tokenInfo = getTokenInfo(lastUserId, client);
    client.setTokenInfo(tokenInfo);
    return client;
}
Also used : StepikApiClient(org.stepik.api.client.StepikApiClient) HttpConfigurable(com.intellij.util.net.HttpConfigurable) HttpTransportClient(org.stepik.api.client.HttpTransportClient) TokenInfo(org.stepik.api.objects.auth.TokenInfo) NotNull(org.jetbrains.annotations.NotNull)

Example 2 with StepikApiClient

use of org.stepik.api.client.StepikApiClient in project intellij-plugins by StepicOrg.

the class FormListener method getAttempt.

private static void getAttempt(@NotNull Project project, @NotNull StepNode node) {
    StepikApiClient stepikApiClient = authAndGetStepikApiClient(true);
    stepikApiClient.attempts().post().step(node.getId()).executeAsync().whenComplete((attempts, e) -> {
        if (attempts != null) {
            node.cleanLastReply();
            StepikProjectManager.updateSelection(project);
        } else {
            logger.warn(e);
        }
    });
}
Also used : StepikAuthManager.authAndGetStepikApiClient(org.stepik.core.stepik.StepikAuthManager.authAndGetStepikApiClient) StepikApiClient(org.stepik.api.client.StepikApiClient)

Example 3 with StepikApiClient

use of org.stepik.api.client.StepikApiClient in project intellij-plugins by StepicOrg.

the class StepikAbstractGetQuery method execute.

@NotNull
@Override
public R execute() {
    StepikApiClient stepikApiClient = getStepikAction().getStepikApiClient();
    if (!isCacheEnabled() || !stepikApiClient.isCacheEnabled()) {
        return super.execute();
    }
    List<String> ids = getParam(IDS_KEY);
    if (ids.isEmpty()) {
        return super.execute();
    }
    Path cachePath = stepikApiClient.getCachePath();
    Path courseCache = cachePath.resolve(getCacheSubdirectory());
    R items;
    try {
        items = getResponseClass().newInstance();
    } catch (InstantiationException | IllegalAccessException e) {
        throw new StepikClientException("Can't create a new instance for a response class", e);
    }
    List<String> idsForQuery;
    if (Files.exists(courseCache)) {
        idsForQuery = new ArrayList<>();
        for (String id : ids) {
            Path file = courseCache.resolve(id + JSON_EXTENSION);
            if (Files.exists(file)) {
                long updateFileTime = file.toFile().lastModified();
                long currentTime = new Date().getTime();
                long diff = currentTime - updateFileTime;
                if (diff > 0 && diff <= getCacheLifeTime()) {
                    Object item = null;
                    try {
                        String text = Utils.readFile(file);
                        //noinspection unchecked
                        item = getJsonConverter().fromJson(text, items.getItemClass());
                    } catch (JsonSyntaxException ignored) {
                    }
                    if (item != null) {
                        //noinspection unchecked
                        items.getItems().add(item);
                        continue;
                    }
                }
            }
            idsForQuery.add(id);
        }
    } else {
        idsForQuery = ids;
    }
    if (!idsForQuery.isEmpty()) {
        id(idsForQuery);
        R loadedItems = super.execute();
        //            noinspection unchecked
        loadedItems.getItems().forEach((item) -> flushCourse(item, courseCache));
        //noinspection unchecked
        items.getItems().addAll(loadedItems.getItems());
    }
    return items;
}
Also used : Path(java.nio.file.Path) StepikApiClient(org.stepik.api.client.StepikApiClient) StepikClientException(org.stepik.api.exceptions.StepikClientException) Date(java.util.Date) JsonSyntaxException(com.google.gson.JsonSyntaxException) AbstractObject(org.stepik.api.objects.AbstractObject) NotNull(org.jetbrains.annotations.NotNull)

Example 4 with StepikApiClient

use of org.stepik.api.client.StepikApiClient in project intellij-plugins by StepicOrg.

the class StepikFilesAction method get.

@NotNull
public String get(@NotNull String url, String contentType) {
    StepikApiClient stepikApi = getStepikApiClient();
    TransportClient transportClient = stepikApi.getTransportClient();
    Map<String, String> headers = new HashMap<>();
    TokenInfo tokenInfo = stepikApi.getTokenInfo();
    String accessToken = tokenInfo.getAccessToken();
    if (accessToken != null) {
        String tokenType = tokenInfo.getTokenType();
        headers.put(HttpHeaders.AUTHORIZATION, tokenType + " " + accessToken);
    }
    headers.put(HttpHeaders.CONTENT_TYPE, contentType);
    ClientResponse response = transportClient.get(stepikApi, url, headers);
    if (response.getStatusCode() / 100 != 2) {
        String message = "Failed query to " + url + " returned the status code " + response.getStatusCode();
        logger.warn(message);
        if (response.getStatusCode() == StatusCodes.SC_UNAUTHORIZED) {
            throw new StepikUnauthorizedException(message);
        } else {
            throw new StepikClientException(message);
        }
    }
    String result = response.getBody();
    if (result == null) {
        throw new StepikClientException("Request successfully but the response body is null: " + url);
    }
    return result;
}
Also used : ClientResponse(org.stepik.api.client.ClientResponse) StepikApiClient(org.stepik.api.client.StepikApiClient) StepikUnauthorizedException(org.stepik.api.exceptions.StepikUnauthorizedException) TransportClient(org.stepik.api.client.TransportClient) HashMap(java.util.HashMap) TokenInfo(org.stepik.api.objects.auth.TokenInfo) StepikClientException(org.stepik.api.exceptions.StepikClientException) NotNull(org.jetbrains.annotations.NotNull)

Example 5 with StepikApiClient

use of org.stepik.api.client.StepikApiClient in project intellij-plugins by StepicOrg.

the class StepikProjectManager method refreshCourse.

private void refreshCourse() {
    if (project == null || root == null) {
        return;
    }
    root.setProject(project);
    executor.execute(() -> {
        StepikApiClient stepikApiClient = authAndGetStepikApiClient();
        if (isAuthenticated()) {
            root.reloadData(project, stepikApiClient);
        }
        ProgressManager.getInstance().run(new Task.Backgroundable(project, "Synchronize Project") {

            @Override
            public void run(@NotNull ProgressIndicator indicator) {
                if (project.isDisposed()) {
                    return;
                }
                repairProjectFiles(root);
                repairSandbox();
                ApplicationManager.getApplication().invokeLater(() -> {
                    VirtualFileManager.getInstance().syncRefresh();
                    setSelected(selected, false);
                });
            }

            private void repairSandbox() {
                VirtualFile projectDir = project.getBaseDir();
                if (projectDir != null && projectDir.findChild(EduNames.SANDBOX_DIR) == null) {
                    Application application = ApplicationManager.getApplication();
                    ModifiableModuleModel model = application.runReadAction((Computable<ModifiableModuleModel>) () -> ModuleManager.getInstance(project).getModifiableModel());
                    application.invokeLater(() -> application.runWriteAction(() -> {
                        try {
                            new SandboxModuleBuilder(projectDir.getPath()).createModule(model);
                            model.commit();
                        } catch (IOException | ConfigurationException | JDOMException | ModuleWithNameAlreadyExists e) {
                            logger.warn("Failed repair Sandbox", e);
                        }
                    }));
                }
            }
        });
    });
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) StepikAuthManager.authAndGetStepikApiClient(org.stepik.core.stepik.StepikAuthManager.authAndGetStepikApiClient) StepikApiClient(org.stepik.api.client.StepikApiClient) Task(com.intellij.openapi.progress.Task) SandboxModuleBuilder(org.stepik.plugin.projectWizard.idea.SandboxModuleBuilder) ModuleWithNameAlreadyExists(com.intellij.openapi.module.ModuleWithNameAlreadyExists) IOException(java.io.IOException) JDOMException(org.jdom.JDOMException) ModifiableModuleModel(com.intellij.openapi.module.ModifiableModuleModel) ConfigurationException(com.intellij.openapi.options.ConfigurationException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) ProgressIndicator(com.intellij.openapi.progress.ProgressIndicator) Application(com.intellij.openapi.application.Application) Computable(com.intellij.openapi.util.Computable)

Aggregations

StepikApiClient (org.stepik.api.client.StepikApiClient)22 StepikAuthManager.authAndGetStepikApiClient (org.stepik.core.stepik.StepikAuthManager.authAndGetStepikApiClient)18 StepikClientException (org.stepik.api.exceptions.StepikClientException)12 NotNull (org.jetbrains.annotations.NotNull)9 StudyNode (org.stepik.core.courseFormat.StudyNode)5 ProgressIndicator (com.intellij.openapi.progress.ProgressIndicator)4 StepNode (org.stepik.core.courseFormat.StepNode)4 Task (com.intellij.openapi.progress.Task)3 VirtualFile (com.intellij.openapi.vfs.VirtualFile)3 IOException (java.io.IOException)3 HashMap (java.util.HashMap)3 Nullable (org.jetbrains.annotations.Nullable)3 StudyObject (org.stepik.api.objects.StudyObject)3 TokenInfo (org.stepik.api.objects.auth.TokenInfo)3 Submission (org.stepik.api.objects.submissions.Submission)3 User (org.stepik.api.objects.users.User)3 StepikAuthManager.getCurrentUser (org.stepik.core.stepik.StepikAuthManager.getCurrentUser)3 Application (com.intellij.openapi.application.Application)2 Logger (com.intellij.openapi.diagnostic.Logger)2 Project (com.intellij.openapi.project.Project)2