Using View and Data API with Meteor

By Daniel Du

I have been studying Meteor these days, and find that Meteor is really a mind-blowing framework, I can talk about this latter. I was inspired by this question on forum and started to looking at the possibilities of using View and Data API in Meteor. Since the way of Meteor works is so different, I have to say that it is not pleasant experience to do that especially for a meteor starter like me. Anyway, after struggling for days, trying this and that, I finally made a simple working site and deployed it as http://lmv.meteor.com. In this post I will write down how I did this, hopefully it is helpful in case you are doing similar stuff.

Firstly I created a Meteor project with “meteor create myproject” command, which creates a “hello world” project. To make it look nice, I refactored the folder structure according to the document of meteor about file structure as below:
.
├── README.md
├── client
│   ├── index.html
│   ├── index.js
│   ├── style.css
│   └── viewer
│       ├── viewer.html
│       └── viewer.js
├── lib
└── server
    └── index.js

The “client” folder contains the contents which are running at client side, “server” folder contains the scripts which are running at server side.

To use View and Data API, we need to do the authentication process to get access token with consumer key/ secret key, which can be applied from http://developer.autodesk.com .  The authentication should be done at server side, otherwise your secret key will be peeked by hackers, so I will do the authentication in “\server\index.js”. But first let me add the “http” package to send REST request to Autodesk authentication server from meteor. You can do this by running command “meteor add http” from command line, and you can also edit “./meteor/packages” file directly, so here is my packages file:

===========================

# Meteor packages used by this project, one per line.
# Check this file (and the other files in this directory) into your repository.
#
# ‘meteor add‘ and ‘meteor remove‘ will edit this file for you,
# but you can also edit it by hand.

meteor-base             # Packages every Meteor app needs to have
mobile-experience       # Packages for a great mobile UX
mongo                   # The database Meteor supports right now
blaze-html-templates    # Compile .html files into Meteor Blaze views
session                 # Client-side reactive dictionary for your app
jquery                  # Helpful client-side library
tracker                 # Meteor‘s client-side reactive programming library

standard-minifiers      # JS/CSS minifiers run for production mode
es5-shim                # ECMAScript 5 compatibility for older browsers.
ecmascript              # Enable ECMAScript2015+ syntax in app code

autopublish             # Publish all data to the clients (for prototyping)
insecure                # Allow all DB writes from clients (for prototyping)

# Allow to send REST calls to authentication server
http

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

=============================

With that, I can add a Meteor method to do authentication from “/server/index.js”,. It can be called from client side with “Meteor.call()”. Here is the code snippet, please note that I am using synchronous mode when doing “Meteor.http.post”, as I found that I cannot get the returned access token from client side afterwards if I use async mode.

Meteor.startup(function () {
    // code to run on server at startup
});

Meteor.methods({

    getAccessToken: function () {

        this.unblock();

        var credentials = {

            credentials: {
                // Replace placeholder below by the Consumer Key and Consumer Secret you got from
                // http://developer.autodesk.com/ for the production server
                client_id: process.env.CONSUMERKEY || ‘replace with your consumer key‘,
                client_secret: process.env.CONSUMERSECRET || ‘your secrete key‘,
                grant_type: ‘client_credentials‘
            },

            // If you which to use the Autodesk View & Data API on the staging server, change this url
            BaseUrl: ‘https://developer.api.autodesk.com‘,
            Version: ‘v1‘
        };

        credentials.AuthenticationURL = credentials.BaseUrl + ‘/authentication/‘ + credentials.Version + ‘/authenticate‘

        //must use synchronous mode
        var result = Meteor.http.post(
            credentials.AuthenticationURL,
            {params: credentials.credentials}
        );
        //get the access token object
        return result.data;

    }
})

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

Now let’s back to the client side, in “/client/viewer/viewer.html” I created a simple template as below:

<Template name="viewer">

    <h2>Autodesk View and Data API</h2>
    <div id="viewer" class="viewer">

    </div>
</Template>

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }In the “\viewer\viewer.js”, I will try to get the access token first with following code: 

Template.viewer.onCreated(function(){

    //console.log(‘viewer template created.‘)
    Meteor.call(‘getAccessToken‘, function (error, result) {
        if (error) {
            console.log(error);
        }
        else {
            var token = result.access_token;
            console.log(token);

            //initialize the viewer
            initViewer(token);

        }

    });

});

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

When the viewer template is created, I call to the server side meteor method to do authentication and get the access token, once I get the access token, I can initialize a viewer at client side with View and Data JavaScript API. Now I can see the token from console of developer tool, so far so good.

 

To use View and Data API, we need to add reference to viewer JavaScript libraries. It seems a very basic thing but it turns out to be the difficult part when it comes to Meteor. This blog introduced two ways to add a script tag into meteor. I tried this solution by creating a script template and load the “viewer3d.js” and viewer style file on the fly, but when I am trying to create a viewer with View and Data JavaScript API, I run to the problem as described in the forum post:

"Uncaught ReferenceError: AutodeskNamespace is not defined"

If I examined to the network tab of browser development tool, the “viewer3d.min.js” has not been loaded yet when I was trying to use it.

Meteor controls the load process of JS files and it is not easy to control the load order, here is the load order as described on meteor document:

The JavaScript and CSS files in an application are loaded according to these rules:

Files in the lib directory at the root of your application are loaded first.

Files that match main.* are loaded after everything else.

Files in subdirectories are loaded before files in parent directories, so that files in the deepest subdirectory are loaded first (after lib), and files in the root directory are loaded last (other than main.*).

Within a directory, files are loaded in alphabetical order by filename.

These rules stack, so that within lib, for example, files are still loaded in alphabetical order; and if there are multiple files named main.js, the ones in subdirectories are loaded earlier.

So since viewer js lib is loaded very late, I cannot use it in viewer.js to initialize the viewer. Luckily, I found that if I put the <script src=””/> tag into <head>, it will be loaded first, so in “/client/index.html”:

<head>
  <title>hello</title>
    <link rel="stylesheet" type="text/css" href="https://developer.api.autodesk.com/viewingservice/v1/viewers/style.css"/>
    <script src="https://developer.api.autodesk.com/viewingservice/v1/viewers/viewer3D.min.js"></script>
</head>

<body>
  <h1>Welcome to Meteor!</h1>

  {{> hello}}

  {{> viewer }}
</body>

<template name="hello">
  <button>Click Me</button>
  <p>You‘ve pressed the button {{counter}} times.</p>
</template>

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

OK, with that I can initialized viewer in “/client/viewer/viewer.js” file, the code snippet is below:

Template.viewer.onCreated(function(){

    //console.log(‘viewer template created.‘)
    Meteor.call(‘getAccessToken‘, function (error, result) {
        if (error) {
            console.log(error);
        }
        else {
            var token = result.access_token;
            console.log(token);

            //initialize the viewer
            initViewer(token);

        }

    });

});

var initViewer = function (token) {

    var defaultUrn = ‘dXJuOmFkc2sub2JqZWN0czpvcy5vYmplY3Q6bW9kZWwyMDE2LTAxLTI4LTAyLTQ0LTM2LWlkbWpjajl5ZXlnYzhwN3h5bDBwZXB5dm54OWkvZ2F0ZWhvdXNlLm53ZA==‘;

    if (defaultUrn.indexOf(‘urn:‘) !== 0)
        defaultUrn = ‘urn:‘ + defaultUrn;

    function initializeViewer(containerId, documentId, role) {
        var viewerContainer = document.getElementById(containerId);
        var viewer = new Autodesk.Viewing.Private.GuiViewer3D(
            viewerContainer);
        viewer.start();

        Autodesk.Viewing.Document.load(documentId,
            function (document) {
                var rootItem = document.getRootItem();
                var geometryItems = Autodesk.Viewing.Document.getSubItemsWithProperties(
                    rootItem,
                    { ‘type‘: ‘geometry‘, ‘role‘: role },
                    true);

                viewer.load(document.getViewablePath(geometryItems[0]));
            },

            // onErrorCallback
            function (msg) {
                console.log("Error loading document: " + msg);
            }
        );
    }

    function initialize() {
        var options = {
            env: "AutodeskProduction",
            //getAccessToken: getToken,
            //refreshToken: getToken
            accessToken : token
        };

        Autodesk.Viewing.Initializer(options, function () {
            initializeViewer(‘viewer‘, defaultUrn, ‘3d‘);
        });
    }

    //call
    initialize();

}

Now I have a running meteor application with viewer embedded. I also posted my sample on github, so you may want to take a look to check the complete code. Hope it helps some.

https://github.com/Developer-Autodesk/meteor-view.and.data.api

时间: 2024-10-06 21:19:23

Using View and Data API with Meteor的相关文章

View and Data API tips: 缓存Access Token

对于云API服务,常见的方式就是按照API调用次数收费,某些API调用也就有某些限制,比如在特定时间内只允许调用指定的次数以免造成滥用.虽然Autodesk的view and Data API目前还没有应用这样的限制,但我们最好也能实现这样的机制,比如对于或者Access Token这样的操作,一个Access Token是有一定的有效期的,在这个token的有效期内,我们就没必要重复发出API调用获取新的Acces Token,只有返回仍然有效的token就可以了.下面是c#实现的简单的逻辑,

View and Data API Tips: how to make viewer full screen

By Daniel Du If you have not heard of View and Data API, here is the idea, the View & Data API enables web developers to very easily display 3D (and 2D) models on a WebGL-enabled browser. please read this one first and get a key from http://developer

View and Data API Tips : Conversion between DbId and node

By Daniel Du In View and Data client side API, The assets in the Autodesk Viewer have an object tree, a tree structure that represents the model hierarchy. Each element in model can be representing as a node of model tree. Each node has a dbId, this

Autodesk View and Data API用户调查

相信大家已经听过Autodesk View and Data Web Service (API) 了吧,还没有? 下面这个就是用Autodesk View and Data Web Service嵌入的模型哦,先玩儿玩儿吧 :)   你也可以把这个模型嵌入到你自己的网站中. 我在和客户交流的时候,很多人都反应云服务器在国外,中国用户使用上就比较犹豫,那么如果把服务器架设在国内,你会用吗?做一下调查吧,让Autodesk听到你的声音.常言道,会哭的孩子有奶吃,不会哭的孩子被饿死啊,5555~  

Autodesk View and Data API练练手

大家如果参加过我们的活动,你应该已经听过看过不少关于View and Data Web Service的例子里,如果还没有的话,请看看下面这几篇: http://www.cnblogs.com/junqilian/category/594048.html 如果你已经了解了Viewer,那有没有兴趣练练手,把这样酷的三维模型嵌入到你自己的网页中呢?那么开始练练手吧. ?体验代码资料下载:http://pan.baidu.com/s/15zZMQ 在下载解压缩后你应该可以看到下面的目录结构,其中ha

初探物联网 - 基于Arduino的气象站和View and Data API的结合实例

如果你参加了上个月在北京的Autodesk 开发者日,你应该看到了我做的关于Arduino的物联网实例演示,如果你没看到,欢迎参加14号在上海的开发者日,到时候我会再演(xian)示(bai)一下. 这是个基于这样一个场景的简单演示.我的一个建筑物上面安装了这样一个温度传感器,随时把当前环境温度上传到云端,在浏览器端可以显示这个建筑物的三维模型和温度变化曲线图.如果温度到达一定的高温,比如大于40度,那可能是起火了,就需要发出高温报警,在三维模型中定位出报警的温度传感器的位置,并发出火警警报.

使用View为Data Source的Form开发要点

(Data Source为View) 要点一:创建View的SQL语法 View的SQL里必须指定Form里唯一一个对其新增.修改.删除的基本表及其主键,其它表为辅助信息表,其字段仅用来在Form里显示.如下例: NCINV_SUB_PERSON_HEADERS 为基本表,主键为HEADER_ID PER_PEOPLE_F 为辅助表 要点二:Form里的Block属性设置 Database属性集的Query Database Source Name属性为视图名,如:NCINV_SUB_PERSO

ASP.NET MVC View 和 Web API 的基本权限验证

ASP.NET MVC 5.0已经发布一段时间了,适应了一段时间,准备把原来的MVC项目重构了一遍,先把基本权限验证这块记录一下. 环境:Windows 7 Professional SP1 + Microsoft Visual Studio 2013(MVC 5 + Web API 2) 修改Web.config,增加Forms验证模式,在system.web节点中增加以下配置: <authentication mode="Forms"> <forms loginU

Gluon Data API

http://mxnet.apache.org/api/python/gluon/data.html import sys import os import time import mxnet as mx from mxnet import autograd,nd from mxnet import gluon,init from mxnet.gluon import data as gdata,loss as gloss from mxnet.gluon import nn #gdata.Ar