Forge Node.js クイックスタート ~ 付録

<本記事は2019年12月10日に Forge SDK 更新と Forge Viewer v7 にあわせて一部改定しています。>

Forge Node.js クイックスタートについて記したブログ記事では、その1その 2 の 2 回にわたって、Forge SDK を用いたアプリ認証、ファイルのアップロード・変換までバッチ処理的に実装し、最後に手動で URL パラメータを用いた方法で Viewer.htm を利用してデザイン ファイルの表示しました。

ここでは、付録として Node.js 標準のミドルウェア(別名:パッケージ、あるいは、モジュール)である http を利用して 、Viewer 表示処理の部分を自動化してみたいと思います。

まず、前回作成した dmSample.js の冒頭の箇所で、http モジュールを読み込む処理を 1 行(青字箇所)追記します。

var fs = require('fs');
var http = require('http');
var ForgeSDK = require('./../src/index');

次に、同じく dmSample.js の manifestFile() 関数の後に、次のコードを追記してください。

var server = http.createServer();
server.listen(3000, "localhost");
console.log("Server is listening port 3000");
var showViewer = function (credentials, encodedURN) {
    server.on('request', function (req, res) {
        var access_token = credentials["access_token"];
        res.writeHead(200, { 'Content-Type': 'text/html' });
        var data = [
            '<html>',
            '  <head>',
            '    <title>Forge Viewer</title>',
            '    <meta charset="utf-8">',
            '    <link rel="stylesheet" href="https://developer.api.autodesk.com/modelderivative/v2/viewers/7.*/style.min.css" type="text/css">',
            '    <script src="https://developer.api.autodesk.com/modelderivative/v2/viewers/7.*/viewer3D.min.js" type="text/javascript"></script>',
            '    <script src="https://code.jquery.com/jquery-2.1.2.min.js"></script>',
            '    <script>',
            '      $(document).ready(function () {',
            '',
            '        var options = {',
            "          env: 'AutodeskProduction',",
            "          api: 'derivativeV2',",
            "          language: 'ja',",
            '          getAccessToken: function (onTokenReady) {',
            "            var token = '" + access_token + "';",
            '            var timeInSeconds = 3600;',
            '            onTokenReady(token, timeInSeconds);',
            '          }',
            '        };',
            '',
            '        Autodesk.Viewing.Initializer(options, function () {',
            "          _viewer = new Autodesk.Viewing.GuiViewer3D(document.getElementById('viewer3d'), options);",
            '',
            '          var startedCode = _viewer.start();',
            '          if (startedCode > 0) {',
            "            console.error('Failed to create a Viewer: WebGL not supported.');",
            '            return;', '          }',
            '',
            "          console.log('Initialization complete, loading a model next...');",
            '',
            "          var documentId = '" + "urn:" + encodedURN + "';",
            '          Autodesk.Viewing.Document.load(documentId, onDocumentLoadSuccess, onDocumentLoadFailure);',
            '        });',
            '', '        function onDocumentLoadSuccess(viewerDocument) {',
            '          var viewables = viewerDocument.getRoot().search({',
            "            'type': 'geometry',",
            "            'role': '3d'",
            '          });',
            '          _viewer.loadDocumentNode(viewerDocument, viewables[0]).then(i => {',
            '          });',
            '        }',
            '',
            '        function onDocumentLoadFailure() {',
            "          console.error('Failed fetching Forge manifest');",
            '        }',
            '',
            '      });',
            '    </script>',
            '  </head>',
            '  <body>',
            '    <div id="viewer3d"></div>',
            '  </body>',
            '</html>'].join('n');
        res.write(data);
        res.end();
    });
}

/** * Create an access token and run the API calls. */
oAuth2TwoLegged.authenticate().then(function (credentials) {
    console.log("**** Got Credentials", credentials);
    createBucketIfNotExist(BUCKET_KEY).then(
        function (createBucketRes) {
            console.log("**** Create bucket if not exist response:", createBucketRes.body);
            getBuckets().then(function (getBucketsRes) {
                console.log("**** Get all buckets response:");
                var bucketsArray = getBucketsRes.body.items;
                bucketsArray.map(function (currentBucket) {
                    console.log(currentBucket.bucketKey);
                })
            }, function (err) {
                console.error(err);
            });
            uploadFile(BUCKET_KEY, FILE_PATH, FILE_NAME).then(function (uploadRes) {
                console.log("**** Upload file response:", uploadRes.body);
                deleteFile(BUCKET_KEY, FILE_NAME).then(function (deleteRes) {
                    console.log("**** Delete file response status code:", deleteRes.statusCode);
                }, defaultHandleError);
                var objectId = uploadRes.body.objectId;
                console.log("objectId:", objectId);
                var urn = base64encode(objectId);
                console.log("urn:", urn);
                translateFile(urn).then(function (translateRes) {
                    manifestFile(urn).then(function () {
                        console.log("**** Your File is ready for viewing");
                        showViewer(credentials, urn);
                    }, defaultHandleError)
                }, defaultHandleError);
            }, defaultHandleError);
        }, defaultHandleError);
}, defaultHandleError);

これで実装は終了です。前回と同様に Node.js command prompt から dmSample.js を指定すると、一連の処理が始まります。**** Your File is ready for viewing のメッセージが表示されたら、Web ブラウザを起動して localhost:3000 を URL 欄に入力してください。変換されたデザイン ファイルが表示されるはずです。

A 3D model of a chair with a yellow seat and gray metallic support, displayed in a browser interface.

あまり美しい実装ではありませんが、Web ブラウザからリクエストによって、Node.js のローカル環境で動的に Viewer.htm 相当の内容をレンダリングするものです。Forge Node.js クイックスタート ~ その 2  で URL パラメータとして渡していた Access Token と ドキュメント ID を、直接代入文として生成しています。

Web ページの生成は、showViewer() 関数内の server.on() で定義したコールバック関数が担当しています。このような処理は、ここまでのクイックスタートの実装を拡張することを前提としているので、あくまでテスト用です。実用向きではありませんので、その点はご注意ください。

By Toshiaki Isezaki

Discover more from Autodesk Developer Blog

Subscribe now to keep reading and get access to the full archive.

Continue reading