Skip to content

Commit

Permalink
Handle 202 in repository, clean example
Browse files Browse the repository at this point in the history
  • Loading branch information
omouren committed Feb 3, 2021
1 parent 35361e8 commit 671f8da
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 61 deletions.
62 changes: 19 additions & 43 deletions examples/live-replay-to-igtv.example.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import {IgApiClient, LiveEntity} from '../src';
import Bluebird = require('bluebird');
const pngToJpeg = require('png-to-jpeg')
const sharp = require('sharp');
const https = require('https');
const axios = require('axios');

const ig = new IgApiClient();

Expand Down Expand Up @@ -67,54 +67,30 @@ async function login() {
await ig.live.endBroadcast(broadcast_id);

// Get live thumbnails, required to post on IGTV
let data = await ig.live.getPostLiveThumbnails(broadcast_id)
let data = await ig.live.getPostLiveThumbnails(broadcast_id);

// Download any thumb
let file = await new Promise((resolve) => https.get(data.thumbnails[0], (download) => {
let ds = [];
download.on("data", (d) => ds.push(d));
download.on("end", () => resolve(Buffer.concat(ds)))
}))
// Use an HTTP client to download any thumb
let {data: file} = await axios.get(data.thumbnails[0], {responseType: 'arraybuffer'});

// (optional) Resize thumb to a vertical one
// (optional) Resize thumb to a vertical one and convert to jpg
file = await sharp(file)
.resize(720, 1280)
.png()
.toBuffer()

// It will be a png, it must be converted to jpg
file = await pngToJpeg({quality: 100})(file)
.resize({width: 720, height: 1280})
.jpeg({
quality: 100,
})
.toBuffer();

// Upload the thumbnail with a broadcast id for a replay and get uploadId
let upload = await ig.upload.photo({file, broadcastId: broadcast_id})

let igtv = null
let currentRetry = 0
let maxRetry = 3
let retryDelay = 4
while (!igtv) {
// This endpoint can return an error "202 Accepted; Transcode not finished yet" if Instagram has not finished to process the previous upload, so retry later in this case
try {
igtv = await ig.media.configureToIgtv({
upload_id: upload.upload_id,
title: 'A title',
caption: 'A description',
igtv_share_preview_to_feed: '1',
})

console.log(`Live posted to IGTV : ${igtv.upload_id}`))
} catch (e) {
currentRetry++
if (currentRetry > maxRetry) {
throw e
} else {
await (new Promise(resolve => {
setTimeout(resolve, currentRetry * retryDelay)
}))
}
}
}
let upload = await ig.upload.photo({file, broadcastId: broadcast_id});

let igtv = await ig.media.configureToIgtv({
upload_id: upload.upload_id,
title: 'A title',
caption: 'A description',
igtv_share_preview_to_feed: '1',
}, 2000)

console.log(`Live posted to IGTV : ${igtv.upload_id}`));
// now you're basically done
})();

Expand Down
53 changes: 35 additions & 18 deletions src/repositories/media.repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import { MediaRepositoryConfigureResponseRootObject } from '../responses';
import Chance = require('chance');
import { MediaRepositoryCheckOffensiveCommentResponseRootObject } from '../responses';
import { StoryMusicQuestionResponse, StoryTextQuestionResponse } from '../types/story-response.options';
import { IgResponseError } from "../errors";

export class MediaRepository extends Repository {
public async info(mediaId: string): Promise<MediaInfoResponseRootObject> {
Expand Down Expand Up @@ -576,7 +577,7 @@ export class MediaRepository extends Repository {
return body;
}

public async configureToIgtv(options: MediaConfigureToIgtvOptions) {
public async configureToIgtv(options: MediaConfigureToIgtvOptions, retryDelay: number = 1000) {
const form: MediaConfigureToIgtvOptions = defaultsDeep(options, {
caption: '',
date_time_original: new Date().toISOString().replace(/[-:]/g, ''),
Expand All @@ -598,23 +599,39 @@ export class MediaRepository extends Repository {
});
const retryContext = options.retryContext;
delete form.retryContext;
const { body } = await this.client.request.send({
url: '/api/v1/media/configure_to_igtv/',
method: 'POST',
qs: {
video: '1',
},
headers: {
is_igtv_video: '1',
retry_context: JSON.stringify(retryContext),
},
form: this.client.request.sign({
...form,
_csrftoken: this.client.state.cookieCsrfToken,
_uid: this.client.state.cookieUserId,
_uuid: this.client.state.uuid,
}),
});

let body = null;
let response = null;
while (!body) {
try {
response = await this.client.request.send({
url: '/api/v1/media/configure_to_igtv/',
method: 'POST',
qs: {
video: '1',
},
headers: {
is_igtv_video: '1',
retry_context: JSON.stringify(retryContext),
},
form: this.client.request.sign({
...form,
_csrftoken: this.client.state.cookieCsrfToken,
_uid: this.client.state.cookieUserId,
_uuid: this.client.state.uuid,
}),
});

body = response.body;
} catch (e) {
// Endpoint can return an error "202 Accepted; Transcode not finished yet" if Instagram has not finished to process the upload, retry after a delay
if (!(e instanceof IgResponseError && e.response.statusCode === 202)) {
throw e;
} else {
await new Promise(resolve => setTimeout(resolve, retryDelay));
}
}
}
return body;
}

Expand Down

0 comments on commit 671f8da

Please sign in to comment.