Skip to content

Commit

Permalink
direnvでid等を管理するように&非同期処理を修正
Browse files Browse the repository at this point in the history
  • Loading branch information
ilim0t committed Dec 12, 2018
1 parent 87002e0 commit 6407d18
Show file tree
Hide file tree
Showing 4 changed files with 90 additions and 54 deletions.
17 changes: 9 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,16 @@ OSKの部室の様子を様子をオンラインで確認できるプロジェ
## Google Photos APIs を使えようにする
1. [Photos Library API](https://console.developers.google.com/apis/library/photoslibrary.googleapis.com)を有効にする.
1. [認証情報](https://console.developers.google.com/apis/credentials)でOAuth クライアント IDを作成する (アプリケーションの種類 は その他)
1. 作成した`クライアント ID``クライアント シークレット``oauth2.keys.json`に以下のように保存する
1. 作成した`クライアント ID``クライアント シークレット``.envrc`に以下のように保存する

```json:oauth2.keys.json
{
"web": {
"client_id": "477...oav.apps.googleusercontent.com",
"client_secret": "yEP..."
}
}
```shell
export client_id="477...oav.apps.googleusercontent.com"
export client_secret="yEP..."
```
4. `direnv`の有効化方法に従う`
Macでbashなら
```shell
direnv allow
```

## カメラを使えるようにする
Expand Down
36 changes: 30 additions & 6 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,43 @@ const {capture} = require("./caputure");
const slack = require("./slack");

const main = async () => {
const oAuth2Client = await photoapi.getOAuthToken();
const {client_id, client_secret} = process.env;
if (client_id === undefined || client_secret === undefined) {
console.log("READMEに従ってGoogle Photos APIsの認証鍵を設定してください");
process.exit(1);
}
const oAuth2Client = await photoapi.getOAuthToken(client_id, client_secret);

const albumTitle = "bushitsuchan_album";
const albums = await photoapi.getAlbumList(oAuth2Client);
let album = albums.filter((album) => album.title === albumTitle);
if (!album.length) {
let album = albums.filter((album) => album.title === albumTitle)[0];

if (album === undefined) {
album = await photoapi.createAlbum(oAuth2Client, albumTitle);
await photoapi.shareAlbum(oAuth2Client, album.id);
}
//https://developers.google.com/photos/library/guides/api-limits-quotas に抵触しないように!!
const interval = 10 * 1000;
if (60 * 60 * 24 * 1000 / 10000 * 3 > interval) {
console.log(`注意: 1日あたり${(60 * 60 * 24 * 3 / interval * 1000).toLocaleString()}回PhotoAPIを叩く設定で,1日の上限10,000回を越してしまいます`);
}
setInterval(async () => {
const url = await capture(oAuth2Client, album);
slack.send(url); // ここをカスタマイズしてください
}, 5000);
const url = await capture(oAuth2Client, album).catch(e => {
console.error(e.name);
if (e.name === "StatusCodeError") {
console.error(JSON.parse(e.error).error.message);
return;
}
console.error(e.message);
// console.error(e);
});

if (!url) {
return;
}
const shortURL = await photoapi.getShortURL(url);
slack.send(shortURL); // ここをカスタマイズしてください
}, interval);
};


Expand Down
31 changes: 22 additions & 9 deletions caputure.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,26 +26,39 @@ const Webcam = NodeWebcam.create({
* @param {OAuth2Client}oAuth2Client
* @param {Object} album
*/
module.exports.capture = (oAuth2Client, album) => {
return new Promise((resolve, reject) => {
Webcam.capture("", async (err, photo) => {
module.exports.capture = async (oAuth2Client, album) => {
const photo = await new Promise((resolve, reject) => {
Webcam.capture("capture", (err, photo) => {
if (err) {
reject(err);
}
const uploadToken = await photoapi.uploadPhoto(oAuth2Client, photo, Date().toLocaleString());
const {mediaItem} = await photoapi.createAlbumMediaItem(oAuth2Client, album.id, uploadToken, "");
const {baseUrl} = await photoapi.getMediaItem(oAuth2Client, mediaItem.id);
resolve(photoapi.getShortURL(baseUrl));
resolve(photo);
})
})
}).catch(e => {
console.error(e);
console.error(
"READMEに従ってカメラを使えるようにしてください\n" +
"また,OSやセキュリティソフトでカメラへのアクセスをブロックしている可能性もあります 解除してください\n");
process.exit(1);
});
const uploadToken = await photoapi.uploadPhoto(oAuth2Client, photo, Date().toLocaleString());
const mediaItem = await photoapi.createAlbumMediaItem(oAuth2Client, album.id, uploadToken, "");
if (mediaItem === undefined) {
console.error()
}
const {baseUrl} = await photoapi.getMediaItem(oAuth2Client, mediaItem.mediaItem.id);
if (baseUrl === undefined || baseUrl === "") {
console.error()
}
return baseUrl;
};

async function main() {
const oAuth2Client = await photoapi.getOAuthToken();

const albumTitle = "bushitsuchan_test_album";
const albums = await photoapi.getAlbumList(oAuth2Client);
let album = albums.filter((album) => album.title === albumTitle);
let album = albums.filter((album) => album.title === albumTitle)[0];
if (!album.length) {
album = await photoapi.createAlbum(oAuth2Client, albumTitle);
await photoapi.shareAlbum(oAuth2Client, album.id);
Expand Down
60 changes: 29 additions & 31 deletions photoAPI.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,15 +29,10 @@ const rpap = rp.defaults({
/**
* @returns {Promise<OAuth2Client>}
*/
module.exports.getOAuthToken = async () => {
const keyPath = path.join(__dirname, "oauth2.keys.json");
let keys = {};
if (fs.existsSync(keyPath)) {
keys = require(keyPath).web;
}
module.exports.getOAuthToken = (client_id, client_secret) => {
const oAuth2Client = new google.auth.OAuth2(
keys["client_id"],
keys["client_secret"],
client_id,
client_secret,
"urn:ietf:wg:oauth:2.0:oob"
);
const scopes = [
Expand All @@ -63,10 +58,13 @@ module.exports.getOAuthToken = async () => {
return new Promise(resolve => {
rl.question("入力: ", async authorizationCode => {
rl.close();
const value = await oAuth2Client.getToken(authorizationCode);
const token = value.tokens;
oAuth2Client.setCredentials(token);
fs.writeFileSync(tokenPath, JSON.stringify(token));
if (authorizationCode === "") {
console.error("入力が無効です 再実行してください");
process.exit(1);
}
const {tokens} = await oAuth2Client.getToken(authorizationCode);
oAuth2Client.setCredentials(tokens);
fs.writeFileSync(tokenPath, JSON.stringify(tokens));
resolve(oAuth2Client);
})
});
Expand All @@ -76,18 +74,18 @@ module.exports.getOAuthToken = async () => {
* @param {OAuth2Client} oAuth2Client
* @returns {Promise<Array.<Object>>}
*/
module.exports.getAlbumList = async (oAuth2Client) => {
module.exports.getAlbumList = async oAuth2Client => {
const accessToken = await oAuth2Client.getAccessToken();
const url = "https://photoslibrary.googleapis.com/v1/albums";
const headers = {
"Content-type": "application/json",
Authorization: `Bearer ${accessToken.token}`
};
const response = await rpap(url, {
return rpap(url, {
method: "GET",
headers: headers
});
return response["albums"]
})
.then(response => response["albums"]);
};

/**
Expand All @@ -105,7 +103,7 @@ module.exports.uploadPhoto = async (oAuth2Client, photo, filename) => {
"X-Goog-Upload-File-Name": filename,
"X-Goog-Upload-Protocol": "raw"
};
return await rpap(url, {
return rpap(url, {
method: "POST",
headers: headers,
body: photo
Expand Down Expand Up @@ -135,12 +133,12 @@ module.exports.createMediaItem = async (oAuth2Client, uploadToken, description)
}
]
};
const response = await rpap(url, {
return rpap(url, {
method: "POST",
headers: headers,
body: JSON.stringify(body)
});
return response["newMediaItemResults"];
})
.then(response => response["newMediaItemResults"]);
};

/**
Expand Down Expand Up @@ -168,12 +166,12 @@ module.exports.createAlbumMediaItem = async (oAuth2Client, albumID, uploadToken,
}
]
};
const response = await rpap(url, {
return rpap(url, {
method: "POST",
headers: headers,
body: JSON.stringify(body)
});
return response["newMediaItemResults"][0];
})
.then(response => response["newMediaItemResults"][0])
};

/**
Expand All @@ -193,7 +191,7 @@ module.exports.createAlbum = async (oAuth2Client, title) => {
title: title
}
};
return await rpap(url, {
return rpap(url, {
method: "POST",
headers: headers,
body: JSON.stringify(body)
Expand All @@ -218,7 +216,7 @@ module.exports.shareAlbum = async (oAuth2Client, albumID) => {
"isCommentable": "true"
}
};
return await rpap(url, {
return rpap(url, {
method: "POST",
headers: headers,
body: JSON.stringify(body)
Expand All @@ -237,24 +235,24 @@ module.exports.getMediaItem = async (oAuth2Client, mediaItemID) => {
"Constent-type": "application/json",
Authorization: `Bearer ${accessToken.token}`
};
return await rpap(url, {
return rpap(url, {
method: "GET",
headers: headers,
});
};

module.exports.getShortURL = async url => {
const ret = await rpap.get(`http://is.gd/create.php?format=simple&format=json&url=${url}`);
return JSON.parse(ret)["shorturl"];
module.exports.getShortURL = url => {
return rpap.get(`http://is.gd/create.php?format=simple&format=json&url=${url}`)
.then(result => JSON.parse(result)["shorturl"]);
};

async function main() {
const oAuth2Client = await module.exports.getOAuthToken();

const albumTitle = "bushitsuchan_test_album";
const albums = await module.exports.getAlbumList(oAuth2Client);
let album = albums.filter((album) => album.title === albumTitle);
if (!album.length) {
let album = albums.filter((album) => album.title === albumTitle)[0];
if (album === undefined) {
album = await module.exports.createAlbum(oAuth2Client, albumTitle);
await module.exports.shareAlbum(oAuth2Client, album.id);
}
Expand Down

0 comments on commit 6407d18

Please sign in to comment.