Search in sources :

Example 1 with StatusResult

use of org.brunocvcunha.instagram4j.requests.payload.StatusResult in project instagram4j by brunocvcunha.

the class InstagramDirectShareRequest method execute.

@Override
public StatusResult execute() throws ClientProtocolException, IOException {
    String recipients = "\"" + String.join("\",\"", this.recipients.toArray(new String[0])) + "\"";
    List<Map<String, String>> data = new ArrayList<Map<String, String>>();
    Map<String, String> map = new HashMap<String, String>();
    if (shareType == ShareType.MEDIA) {
        map.put("type", "form-data");
        map.put("name", "media_id");
        map.put("data", mediaId);
        data.add(map);
    }
    map = map.size() > 0 ? new HashMap<String, String>() : map;
    map.put("type", "form-data");
    map.put("name", "recipient_users");
    map.put("data", "[[" + recipients + "]]");
    data.add(map);
    map = new HashMap<String, String>();
    map.put("type", "form-data");
    map.put("name", "client_context");
    map.put("data", InstagramGenericUtil.generateUuid(true));
    data.add(map);
    map = new HashMap<String, String>();
    map.put("type", "form-data");
    map.put("name", "thread_ids");
    map.put("data", "[]");
    data.add(map);
    map = new HashMap<String, String>();
    map.put("type", "form-data");
    map.put("name", "text");
    map.put("data", message == null ? "" : message);
    data.add(map);
    HttpPost post = createHttpRequest();
    post.setEntity(new ByteArrayEntity(buildBody(data, api.getUuid()).getBytes(StandardCharsets.UTF_8)));
    try (CloseableHttpResponse response = api.getClient().execute(post)) {
        api.setLastResponse(response);
        int resultCode = response.getStatusLine().getStatusCode();
        String content = EntityUtils.toString(response.getEntity());
        log.info("Direct-share request result: " + resultCode + ", " + content);
        post.releaseConnection();
        StatusResult result = parseResult(resultCode, content);
        return result;
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) ByteArrayEntity(org.apache.http.entity.ByteArrayEntity) HashMap(java.util.HashMap) StatusResult(org.brunocvcunha.instagram4j.requests.payload.StatusResult) ArrayList(java.util.ArrayList) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) HashMap(java.util.HashMap) Map(java.util.Map)

Example 2 with StatusResult

use of org.brunocvcunha.instagram4j.requests.payload.StatusResult in project instagram4j by brunocvcunha.

the class InstagramUploadVideoRequest method configureThumbnail.

/**
 * Configures the thumbnails for the given uploadId
 * @param uploadId The session id
 * @return Result
 * @throws Exception
 * @throws IOException
 * @throws ClientProtocolException
 */
protected StatusResult configureThumbnail(String uploadId) throws Exception, IOException, ClientProtocolException {
    try (FFmpegFrameGrabber frameGrabber = new FFmpegFrameGrabber(videoFile)) {
        frameGrabber.start();
        Java2DFrameConverter converter = new Java2DFrameConverter();
        int width = frameGrabber.getImageWidth();
        int height = frameGrabber.getImageHeight();
        long length = frameGrabber.getLengthInTime();
        BufferedImage bufferedImage;
        if (thumbnailFile == null) {
            bufferedImage = MyImageUtils.deepCopy(converter.convert(frameGrabber.grabImage()));
            thumbnailFile = File.createTempFile("insta", ".jpg");
            log.info("Generated thumbnail: " + thumbnailFile.getAbsolutePath());
            ImageIO.write(bufferedImage, "JPG", thumbnailFile);
        } else {
            bufferedImage = ImageIO.read(thumbnailFile);
        }
        holdOn();
        StatusResult thumbnailResult = api.sendRequest(new InstagramUploadPhotoRequest(thumbnailFile, caption, uploadId));
        log.info("Thumbnail result: " + thumbnailResult);
        StatusResult configureResult = api.sendRequest(InstagramConfigureVideoRequest.builder().uploadId(uploadId).caption(caption).duration(length).width(width).height(height).build());
        log.info("Video configure result: " + configureResult);
        return configureResult;
    }
}
Also used : FFmpegFrameGrabber(org.bytedeco.javacv.FFmpegFrameGrabber) StatusResult(org.brunocvcunha.instagram4j.requests.payload.StatusResult) BufferedImage(java.awt.image.BufferedImage) Java2DFrameConverter(org.bytedeco.javacv.Java2DFrameConverter)

Example 3 with StatusResult

use of org.brunocvcunha.instagram4j.requests.payload.StatusResult in project instagram4j by brunocvcunha.

the class InstagramUploadVideoJobRequest method execute.

@Override
public StatusResult execute() throws ClientProtocolException, IOException {
    String url = getUrl();
    log.info("URL Upload: " + url);
    HttpPost post = new HttpPost(url);
    post.addHeader("X-IG-Capabilities", "3Q4=");
    post.addHeader("X-IG-Connection-Type", "WIFI");
    post.addHeader("Cookie2", "$Version=1");
    post.addHeader("Accept-Language", "en-US");
    post.addHeader("Accept-Encoding", "gzip, deflate");
    post.addHeader("Content-Type", "application/octet-stream");
    post.addHeader("Session-ID", uploadId);
    post.addHeader("Connection", "keep-alive");
    post.addHeader("Content-Disposition", "attachment; filename=\"video.mp4\"");
    post.addHeader("job", uploadJob);
    post.addHeader("Host", "upload.instagram.com");
    post.addHeader("User-Agent", InstagramConstants.USER_AGENT);
    log.info("User-Agent: " + InstagramConstants.USER_AGENT);
    try (FileInputStream is = new FileInputStream(videoFile)) {
        byte[] videoData = MyStreamUtils.readContentBytes(is);
        // TODO: long ranges? need to handle?
        int requestSize = (int) Math.floor(videoData.length / 4.0);
        int lastRequestExtra = (int) (videoData.length - (requestSize * 3));
        for (int i = 0; i < 4; i++) {
            int start = i * requestSize;
            int end;
            if (i == 3) {
                end = i * requestSize + lastRequestExtra;
            } else {
                end = (i + 1) * requestSize;
            }
            int actualLength = (i == 3 ? lastRequestExtra : requestSize);
            String contentRange = String.format("bytes %s-%s/%s", start, end - 1, videoData.length);
            // post.setHeader("Content-Length", String.valueOf(end - start));
            post.setHeader("Content-Range", contentRange);
            byte[] range = Arrays.copyOfRange(videoData, start, start + actualLength);
            log.info("Total is " + videoData.length + ", sending " + actualLength + " (starting from " + start + ") -- " + range.length + " bytes.");
            post.setEntity(EntityBuilder.create().setBinary(range).build());
            try (CloseableHttpResponse response = api.getClient().execute(post)) {
                int resultCode = response.getStatusLine().getStatusCode();
                String content = EntityUtils.toString(response.getEntity());
                log.info("Result of part " + i + ": " + content);
                post.releaseConnection();
                response.close();
                if (resultCode != 200 && resultCode != 201) {
                    throw new IllegalStateException("Failed uploading video (" + resultCode + "): " + content);
                }
            }
        }
        return new StatusResult("ok");
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) StatusResult(org.brunocvcunha.instagram4j.requests.payload.StatusResult) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) FileInputStream(java.io.FileInputStream)

Example 4 with StatusResult

use of org.brunocvcunha.instagram4j.requests.payload.StatusResult in project instagram4j by brunocvcunha.

the class InstagramUploadPhotoRequest method execute.

@Override
public InstagramConfigurePhotoResult execute() throws ClientProtocolException, IOException {
    if (uploadId == null) {
        uploadId = String.valueOf(System.currentTimeMillis());
    }
    HttpPost post = createHttpRequest();
    post.setEntity(createMultipartEntity());
    try (CloseableHttpResponse response = api.getClient().execute(post)) {
        api.setLastResponse(response);
        int resultCode = response.getStatusLine().getStatusCode();
        String content = EntityUtils.toString(response.getEntity());
        log.info("Photo Upload result: " + resultCode + ", " + content);
        post.releaseConnection();
        StatusResult result = parseResult(resultCode, content);
        if (!result.getStatus().equalsIgnoreCase("ok")) {
            throw new RuntimeException("Error happened in photo upload: " + result.getMessage());
        }
        InstagramConfigurePhotoResult configurePhotoResult = api.sendRequest(new InstagramConfigurePhotoRequest(imageFile, uploadId, caption));
        log.info("Configure photo result: " + configurePhotoResult);
        if (!configurePhotoResult.getStatus().equalsIgnoreCase("ok")) {
            throw new IllegalArgumentException("Failed to configure image: " + configurePhotoResult.getMessage());
        }
        StatusResult exposeResult = api.sendRequest(new InstagramExposeRequest());
        log.info("Expose result: " + exposeResult);
        if (!exposeResult.getStatus().equalsIgnoreCase("ok")) {
            throw new IllegalArgumentException("Failed to expose image: " + exposeResult.getMessage());
        }
        return configurePhotoResult;
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) StatusResult(org.brunocvcunha.instagram4j.requests.payload.StatusResult) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) InstagramExposeRequest(org.brunocvcunha.instagram4j.requests.internal.InstagramExposeRequest) InstagramConfigurePhotoRequest(org.brunocvcunha.instagram4j.requests.internal.InstagramConfigurePhotoRequest) InstagramConfigurePhotoResult(org.brunocvcunha.instagram4j.requests.payload.InstagramConfigurePhotoResult)

Example 5 with StatusResult

use of org.brunocvcunha.instagram4j.requests.payload.StatusResult in project instagram4j by brunocvcunha.

the class InstagramUploadVideoRequest method execute.

@Override
public StatusResult execute() throws ClientProtocolException, IOException {
    HttpPost post = createHttpRequest();
    String uploadId = String.valueOf(System.currentTimeMillis());
    post.setEntity(createMultipartEntity(uploadId));
    try (CloseableHttpResponse response = api.getClient().execute(post)) {
        api.setLastResponse(response);
        int resultCode = response.getStatusLine().getStatusCode();
        String content = EntityUtils.toString(response.getEntity());
        log.info("First phase result " + resultCode + ": " + content);
        post.releaseConnection();
        InstagramUploadVideoResult firstPhaseResult = parseJson(content, InstagramUploadVideoResult.class);
        if (!firstPhaseResult.getStatus().equalsIgnoreCase("ok")) {
            throw new RuntimeException("Error happened in video upload session start: " + firstPhaseResult.getMessage());
        }
        String uploadUrl = firstPhaseResult.getVideo_upload_urls().get(3).get("url").toString();
        String uploadJob = firstPhaseResult.getVideo_upload_urls().get(3).get("job").toString();
        StatusResult uploadJobResult = api.sendRequest(new InstagramUploadVideoJobRequest(uploadId, uploadUrl, uploadJob, videoFile));
        log.info("Upload result: " + uploadJobResult);
        if (!uploadJobResult.getStatus().equalsIgnoreCase("ok")) {
            throw new RuntimeException("Error happened in video upload submit job: " + uploadJobResult.getMessage());
        }
        StatusResult thumbnailResult = configureThumbnail(uploadId);
        if (!thumbnailResult.getStatus().equalsIgnoreCase("ok")) {
            throw new IllegalArgumentException("Failed to configure thumbnail: " + thumbnailResult.getMessage());
        }
        return api.sendRequest(new InstagramExposeRequest());
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) InstagramUploadVideoResult(org.brunocvcunha.instagram4j.requests.payload.InstagramUploadVideoResult) StatusResult(org.brunocvcunha.instagram4j.requests.payload.StatusResult) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) InstagramExposeRequest(org.brunocvcunha.instagram4j.requests.internal.InstagramExposeRequest) InstagramUploadVideoJobRequest(org.brunocvcunha.instagram4j.requests.internal.InstagramUploadVideoJobRequest)

Aggregations

StatusResult (org.brunocvcunha.instagram4j.requests.payload.StatusResult)6 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)4 HttpPost (org.apache.http.client.methods.HttpPost)4 InstagramExposeRequest (org.brunocvcunha.instagram4j.requests.internal.InstagramExposeRequest)2 BufferedImage (java.awt.image.BufferedImage)1 FileInputStream (java.io.FileInputStream)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1 Map (java.util.Map)1 SneakyThrows (lombok.SneakyThrows)1 ByteArrayEntity (org.apache.http.entity.ByteArrayEntity)1 InstagramConfigurePhotoRequest (org.brunocvcunha.instagram4j.requests.internal.InstagramConfigurePhotoRequest)1 InstagramUploadVideoJobRequest (org.brunocvcunha.instagram4j.requests.internal.InstagramUploadVideoJobRequest)1 InstagramConfigurePhotoResult (org.brunocvcunha.instagram4j.requests.payload.InstagramConfigurePhotoResult)1 InstagramUploadVideoResult (org.brunocvcunha.instagram4j.requests.payload.InstagramUploadVideoResult)1 FFmpegFrameGrabber (org.bytedeco.javacv.FFmpegFrameGrabber)1 Java2DFrameConverter (org.bytedeco.javacv.Java2DFrameConverter)1