Windows 10 Tech Previewでちと横道にそれてしまったがnw.jsでのデスクトップアプリ作成を再開している。何を作りたいのかというとWebGLでレンダリングしたものをYouTube動画としてアップロードするというものである。 アップロードするためにはOAuth認証を通さないといけないので認証コードを書いていた。下がそのコードの抜粋である。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// OAuth認証を行う // | |
youtube_apikey = apikeys.apiKey; | |
var url = 'https://accounts.google.com/o/oauth2/auth?client_id=' | |
+ apikeys.clientId + '&redirect_uri=' + encodeURIComponent('urn:ietf:wg:oauth:2.0:oob') | |
+ '&scope=' + encodeURIComponent('https://www.googleapis.com/auth/youtube') | |
+ '&response_type=code&access_type=offline'; | |
// 認証ページに飛ぶ // | |
gui.Window.open(url) | |
.on('loaded', function () { | |
var this_ = this; | |
var title = this_.title; | |
// 承認をクリックしていただいた | |
if (title.match(/Success\scode/)) { | |
var code = title.split('=')[1]; | |
console.log('Auth Success.' + code); | |
// アクセストークン・リフレッシュトークンをもらう | |
(function () { | |
var form | |
= 'code=' + encodeURIComponent(code) + '&' | |
+ 'client_id=' + encodeURIComponent(apikeys.clientId) + '&' | |
+ 'client_secret=' + encodeURIComponent(apikeys.clientSecret) + '&' | |
+ 'redirect_uri=' + encodeURIComponent('urn:ietf:wg:oauth:2.0:oob') + '&' | |
+ 'grant_type=authorization_code'; | |
var urlOpts = { | |
host: 'accounts.google.com', | |
path: '/o/oauth2/token', | |
method: 'POST', | |
headers: { | |
'Content-Type': 'application/x-www-form-urlencoded', | |
'Content-Length': form.length | |
} | |
}; | |
var result = q.defer(); | |
var req = https.request(urlOpts, function (res) { | |
var data = ''; | |
res.setEncoding('utf8'); | |
res.on('data', function (chunk) { | |
data += chunk; | |
}) | |
.on('end', function (res) { | |
result.resolve(JSON.parse(data)); | |
console.log(data); | |
}) | |
.on('error', function (e) { | |
console.log('ERROR:' + e.stack); | |
result.reject(e); | |
}); | |
}); | |
req.write(form); | |
req.end(); | |
return result.promise; | |
})() | |
.then(function (tokens_) { | |
tokens = tokens_; | |
this_.close(); | |
query(); | |
}).catch(function (e) { | |
alert('認証中にエラーが発生しました。' + e); | |
}); | |
} | |
// キャンセルされたもしくは他のエラーが発生した | |
if (title.match(/error/)) { | |
alert('認証中にエラーが発生しました。' + title); | |
console.log(title); | |
this_.close(); | |
} | |
}).focus(); |
当初このコードを書いて動かすとストリームエラーが多発して全然動かなかった。試しにnw.jsをアップデートしたところ動くようになった。おそらくnw.jsに何らかの不具合があったのだろう。
nw.jsが面白いのはHTML中のscriptタグで読み込んだスクリプトとnodeモジュールを混在させられるところだ。これのメリットというのをまだ見いだせないではいるけれども。
ネイティブUIのモジュールとかもあって、Webセキュリティのために通常不可な操作もできるようになっているのも面白い。ネイティブ・アドオンも当然対応しているしその気になればなんでもできそうな気がする。
ただNTVS(Node Tools For Visual Studio)のエディタはもちろんnode.js用なのでscriptタグで読み込んだライブラリのインテリセンスは効かない。またhtmlファイル上でインラインで書いたとしてもrequireしたモジュールはインテリセンスしてくれない。これが悩みどころではある。