将特殊字符写入表字段时,Fusion表认证丢失

时间:2012-10-09 14:41:00

标签: javascript google-apps-script google-fusion-tables

我是谷歌应用程序脚本和融合表的新手。我正在为我的公司开发一个CRM应用程序,我正在使用谷歌网站,谷歌应用程序脚本和融合表来做到这一点。 我还使用了O'Reilly的“Google Script - Enterprise Application Essentials”一书中的一个例子来构建我的应用程序。 我使用Fusion表作为我的项目的数据库,我运行函数doOAuth()来授予每个人在Fusion表上执行操作的权限。(请参阅下面的代码,其中包含我从本书中获得的doOAuth代码)。 该应用程序适用于我对融合表的每个命令。我能够读取表格的内容,我也能够对其进行搜索,但是当我在桌面上写入新数据或更新现有数据时,我面临着一个恼人的问题。 我在我的应用程序上有一些文本框,我插入了一些数据,这些数据写入表中,到目前为止没问题,当我向这些文本框添加常用文本时,我在更新数据或将数据插入融合表时没有问题。但是当我在这些文本框中添加任何特殊字符时,如:á,ã,à,ä,é,õ,í等等,我收到一条消息,告诉我需要自动调整才能执行该过程。但我已经给了授权。似乎授权丢失了。即使我再次运行doOAuth()函数,也不会给出权限。当参数是特殊字符时,insertFusionObj()和writeFusionObj()函数(在下面的代码中列出)似乎有问题。我不知道这是函数中的问题还是融合表插入和更新问题。 我真的很感激,如果有人可以帮我解决这个问题,因为我的应用程序旨在用于葡萄牙语,它有一些特殊字符,当负责向应用程序添加信息的人使用它时,他可能会使用特殊字符插入和更新融合表。

我期待着一些帮助。 最好的祝福 Rafael Setti Nogueira

代码:

    /**
     * ---FusionService---
     *
     *  Copyright (c) 2011 James Ferreira
     *
     *  Licensed under the Apache License, Version 2.0 (the "License");
     *  you may not use this file except in compliance with the License.
     *  You may obtain a copy of the License at
     *
     *      http://www.apache.org/licenses/LICENSE-2.0
     *
     *  Unless required by applicable law or agreed to in writing, software
     *  distributed under the License is distributed on an "AS IS" BASIS,
     *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     *  See the License for the specific language governing permissions and
     *  limitations under the License.
     */

    /**
     * FusionService 
     * @author James Ferreira
     * @documentation http://goo.gl/pBSvF
     *
     * @requires Script Insert ID: ?????
     *           ObjService http://goo.gl/JdEHW
     *
     * @requires The Fusion Table ID MUST be set in a Script property. 
     *           This will allow you to change it at anytime using
     *           ScriptProperties.setProperty('FUSION_ID', '<your ID>'); 
     *
     *
     * Search for records in a Fusion Table 
     *
     * @params {string}  target   Quoted column name(s) ('First Name', 'Last Name') OR (*) for all 
     * @params {string}  where    valid statement see http://goo.gl/SkHI1
     *                            'Last Name' CONTAINS IGNORING CASE 'Ferr' 
     *                             AND 'First Name' CONTAINS IGNORING CASE 'J'" 
     *
     * @returns {array}           [[headers],[match row],[match row]...]
     *                            If no match returns []
     */
    function searchFusion(target, where){
      var values = [];
      if (target == '*'){
        var headers = getFusionHeaders();
        for(var i in headers){
          values.push("'"+headers[i]+"'"); 
        }   
      }else{
        values.push(target); 
      }
      var arrayResult = fusionRequest("get", "SELECT "+values.toString()+",ROWID FROM "+
                                      FUSION_ID+" WHERE "+ where).split(/\n/);
      for (var i in arrayResult){
        arrayResult[i] = arrayResult[i].split(/,/); 
      }
      arrayResult.splice(arrayResult.length-1, 1);
      return arrayResult;
    }

    /**
     * Updates a record in the Fusion table
     * Note: fusionObj must contain rowid of Fusion table record
     *
     * @params  {object}  fusionObj  object with properties from cameled column names
     * @returns {string}             OK if successful
     */
    function writeFusionObj(fusionObj){
      var values = [];
      var headers = getFusionHeaders();   
      for(var i in headers){
        if (fusionObj[camelString(headers[i])] != undefined)
        values.push("'"+headers[i] +"'='"+fusionObj[camelString(headers[i])]+"'"); 
      }  
     return fusionRequest("post", "UPDATE "+FUSION_ID+" SET "+values.toString()+
                          " WHERE ROWID = '"+fusionObj.rowid+"'") 
    }

    /**
     * Add a new record to a Fusion table
     *
     * @params  {object}  fusionObj  object with properties from cameled column names
     * @returns {integer}            rowid useful for unique ID of record
     */
    function insertFusionObj(fusionObj){
      var values = [];
      var columns =[];
      var headers = getFusionHeaders(); 

      for(var i in headers){
        columns.push("'"+headers[i] +"'");
        values.push("'"+fusionObj[camelString(headers[i])]+"'"); 
      }  
      return parseInt(fusionRequest("post", "INSERT INTO "+FUSION_ID+
                        " ("+columns.toString()+") VALUES ("+values.toString()+")").substring(5));
    }

    /**
     * Get the Fusion row ID for a given column header and unique value
     *
     * @returns {integer}    Fusion ROWID for record
     */
    function getFusionROWID(header, key){
     return parseInt(fusionRequest("get", "SELECT ROWID FROM "+FUSION_ID+
                                   " WHERE '"+header+"'='"+key+"'").substring(5));
    }

    /**
     * get the column header names from Fusion Table
     *
     * @returns {array}    [header, header, ...]
     */
    function getFusionHeaders(){
      var headers = [];
      var result = fusionRequest("get", "DESCRIBE "+FUSION_ID).split(/\n/);
        for (var i in result){
        result[i] = result[i].split(/,/); 
        headers.push(result[i][1]);  
      }  
      headers.splice(0, 1);
      headers.splice(headers.length-1, 1);
      return headers;  
    }

    /**
     * Deletes a record in the Fusion Table
     *
     * @params  {string}  rowid  the ID of a Fusion table row
     */
    function deleteFusionRow(rowid){  
       fusionRequest("post", "DELETE FROM "+FUSION_ID+" WHERE ROWID = '"+rowid+"'");  
    }

    /**
     * The get or post request to the Fusion API 
     *
     * @params  {string}  reqMethod  get or post
     * @params  {string}  sql        String  A sgl type request see http://goo.gl/aVP3B
     * @returns {integer}            Fusion rowid useful for unique ID of record
     */
    function fusionRequest(method, sql) {

      var url = "https://www.google.com/fusiontables/api/query";

      if (USE_OAUTH){
        var fetchArgs = googleOAuth_();   
      }else{
        var fetchArgs = new Object();
        fetchArgs.headers = {"Authorization": "GoogleLogin auth=" + getAuthToken_()};
      } 
      fetchArgs.method = method; 

      if( method == 'get' ) {
        url += '?sql='+sql;
        fetchArgs.payload = null;
      } else{
        fetchArgs.payload = 'sql='+sql;
      } 
      return UrlFetchApp.fetch(url, fetchArgs).getContentText(); 
    }

    /**
     * @private for OAuth
     */
    function googleOAuth_() {
      var oAuthConfig = UrlFetchApp.addOAuthService('fusion');
      oAuthConfig.setRequestTokenUrl("https://www.google.com/accounts/"+
                 "OAuthGetRequestToken?scope=https://www.google.com/fusiontables/api/query");
      oAuthConfig.setAuthorizationUrl("https://www.google.com/accounts/OAuthAuthorizeToken");
      oAuthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");
      oAuthConfig.setConsumerKey('anonymous');
      oAuthConfig.setConsumerSecret('anonymous');
      return {oAuthServiceName:'fusion', oAuthUseToken:"always"};
    }


    /**
     * @private for client Auth
     * @returns String(auth token for a user)
     */ 
    function getAuthToken_() {

      var response = UrlFetchApp.fetch("https://www.google.com/accounts/ClientLogin", {
          method: "post",
          payload: "accountType=GOOGLE" +
                   "&Email=" + ScriptProperties.getProperty('CUSTOMER_KEY') + 
                   "&Passwd=" + encodeURIComponent(ScriptProperties.getProperty('CUSTOMER_SECRET'))+ 
                   "&service=fusiontables" +
                   "&Source=testing"
      });
      var responseStr = response.getContentText();
      responseStr = responseStr.slice(responseStr.search("Auth=") + 5, responseStr.length);
      responseStr = responseStr.replace(/\n/g, "");
      return responseStr;
    }


    /**
     * Used to authenticate to Fusion Tables
     * Run it twice!
     */
    function doOAuth(){
      var method = 'get';
      var sql = "SHOW TABLES";  
      Logger.log(fusionRequest(method,sql));
    }

    var USE_OAUTH = true; 
    var FUSION_ID = ScriptProperties.getProperty('FUSION_ID');

0 个答案:

没有答案