Skip to content

Instantly share code, notes, and snippets.

@kuhel
Last active December 14, 2019 11:06
Show Gist options
  • Save kuhel/4f5d46ebc81165c461676b757591e63e to your computer and use it in GitHub Desktop.
Save kuhel/4f5d46ebc81165c461676b757591e63e to your computer and use it in GitHub Desktop.
import fetchStream from 'fetch-readablestream';
const CORS_PROXY = "https://cors-anywhere.herokuapp.com/";
const APP_ID = 9999999;
async function fetchFileStream(fileAddress, filename, imgType) {
return fetchStream(fileAddress)
.then(response => readAllChunks(response.body))
.then(chunks => new File(chunks, filename, {type: imgType}));
};
const readAllChunks = (readableStream) {
const reader = readableStream.getReader();
const chunks = [];
const pump = () => {
return reader.read().then(({value, done}) => {
if (done)
return chunks;
chunks.push(value);
return pump();
});
}
return pump();
}
async function publishOnWall() {
const authToken = await connect.send("VKWebAppGetAuthToken", {
"app_id": APP_ID,
"scope": "photos"
});
const serverToPhoto = await connect.send("VKWebAppCallAPIMethod", {
method: "photos.getWallUploadServer",
params: {access_token: authToken.data.access_token, v: "5.95"}
});
const uploadUrl = serverToPhoto.data.response.upload_url;
const request = new FormData();
request.append("photo", await fetchFileStream(wallPhoto, "story.png", 'image/png'));
const {server, photo, hash} = await fetch(CORS_PROXY + uploadUrl, {
method: "POST",
body: request
}).then((response) => response.json());
const res = await connect.send("VKWebAppCallAPIMethod", {
method: "photos.saveWallPhoto",
params: {
access_token: authToken.data.access_token, server, photo, hash,
v: "5.95"
}
});
const {id: photo_id, owner_id} = res.data.response[0];
await connect.send("VKWebAppShowWallPostBox", {
message: `Сообщение на стену с фото`,
attachments: `photo${owner_id}_${photo_id},https://vk.com/app${APP_ID}`
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment