1. 程式人生 > >Using View and Data API with Meteor

Using View and Data API with Meteor

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.

Screen Shot 2016-01-28 at 1.48.12 PM

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

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

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;


    }
})

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>

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);

        }

    });

});

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.

Screen Shot 2016-01-28 at 1.45.51 PM

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>

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.

相關推薦

Using View and Data API with Meteor

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 que

使用AxisHelper幫助理解View and Data API中的座標系統

大家使用View and Data API做三維模型開發,必然首先要理解View and Data API的座標系統,即XYZ三個軸向分別是怎麼定義的。Three.js裡面提供了一個AxisHelper,但如果你直接運用的話,你會發現在viewer中並不顯示,並且控制檯中會有這樣的錯誤資訊:"Only THR

View and Data API Tips: Constrain Viewer Within a div Container

When working with View and Data API, you probably want to contain viewer into a <div> tag, the position and size of <div> can be defined with

Autodesk View and Data API二次開發學習指南

什麼是View and Data API? 使用View and Data API,你可以輕鬆的在網頁上顯示大型三維模型或者二維圖紙而不需要安裝任何外掛。通過View and Data API,你可以對模型進行視點控制、選擇控制、屬性資訊查詢等等,而且還可以把這樣無外掛的模型瀏覽器和您自己的其他資訊系統整合

View and Data API中更改指定元素的顏色

大家在使用View and Data API開發過程中,經常會用到的就是改變某些元素的顏色已區別顯示。比如根據某些屬性做不同顏色的專題顯示,或者用不同顏色表示施工進度,或者只是簡單的以顏色變化來提醒使用者以示區別。作為開發者,一定會喜歡看的這樣的API://load the extension viewe

View and Data API Tips : Conversion between DbId and node

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 eleme

View and Data API Tips: Hide elements in viewer completely

With View and Data API, you can hide some elements in viewer by calling “viewer.hide(dbIds)”, when the elements are hided, it actually make it transparen

Topic Modeling and Data Visualization with Python/Flask

TemplatesBase.htmlFirst, we’ll want to make our base template. I like to include all of these templates in a templates folder, as you can see from our tree

建立View and Data – 3D模型

View and Data – 3D模型 (轉自:blog.csdn.net/zzzh2088/article/details/64921162) 1、建立展示3D模型的容器,引入必要的css和js檔案 <!DOCTYPE html> <head&

Getting Started With the Slack API Using Python and Flask

The slick hosted chat application Slack is all the rage this year. The tool’s adoption isn’t empty hype - it’s incredibly useful for communicating with

[HTML5] Inlining images with SVG and data URIs

mtu pan -h too tty pps ffffff row nts The main reason you want to do I"nlining images with SVG and data URIs" is to reduce http request.

problem-solving-with-algorithms-and-data-structure-usingpython(使用python解決算法和數據結構) -- 基本數據結構(一)

匹配 剛才 第一個 ems sem spl pla 查看 線性數據結構 1. 什麽是線性數據結構? 棧,隊列,deques, 列表是一類數據的容器,它們數據項之間的順序由添加或刪除的順序決定。 一旦一個數據項被添加,它相對於前後元素一直保持該位置不變。 諸

使用Kong的oauth2.0,請求重定向url,返回“no route and no API found with those values”

官方提供的endpoints有兩個:/oauth2/authorize 以及 /oauth2/token。(詳情請看:https://docs.konghq.com/hub/kong-inc/oauth2/) 注意事項有以下3點: 1、如果api添加了“uris”,比如“/test",那麼訪問的

Data Cleaning with Python and Pandas: Detecting Missing Values

Data Cleaning with Python and Pandas: Detecting Missing ValuesData cleaningcan be a tedious task.It’s the start of a new project and you’re excited to appl

Building a Big Data Pipeline With Airflow, Spark and Zeppelin

Building a Big Data Pipeline With Airflow, Spark and Zeppelin“black tunnel interior with white lights” by Jared Arango on UnsplashIn this data-driven era,

Train your own ML model using Scikit and use in iOS app with CoreML (and probably with Augmented…

Next we plot the data using below code —%matplotlib inlineimport matplotlib.pyplot as pltiris_data.hist(bins=50, figsize=(20,15))plt.show()Plot of sepal_le

Predict wildfire intensity using NASA satellite data and machine learning

About this video Mitigating natural disasters is one of the world’s greatest challenges, and some of the most devastating natural di

Fast Order Search Using Yelp’s Data Pipeline and Elasticsearch

Since its inception in 2013, Yelp has grown its transactions platform to tens of millions of orders. With this growth, it’s become slow and cumberso

Build your first Web API with F#, Giraffe and host it on Azure Cloud

Build your first Web API with F#, Giraffe and host it on Azure CloudBuilding a Web API using F# and Giraffe, hosting on Azure CloudToday I am going to talk