Showing preview only (211K chars total). Download the full file or copy to clipboard to get everything.
Repository: entaq/GoogleAppsScript
Branch: master
Commit: 672e8209d88d
Files: 98
Total size: 185.6 KB
Directory structure:
gitextract_o4r4wtx7/
├── .gitignore
├── Android/
│ ├── ClientCode/
│ │ ├── AndroidManifest.xml
│ │ ├── README
│ │ ├── gen/
│ │ │ └── com/
│ │ │ └── google/
│ │ │ └── android/
│ │ │ └── gcm/
│ │ │ └── demo/
│ │ │ └── app/
│ │ │ ├── BuildConfig.java
│ │ │ ├── Manifest.java
│ │ │ └── R.java
│ │ ├── libs/
│ │ │ ├── android-support-v4.jar
│ │ │ └── gcm.jar
│ │ ├── project.properties
│ │ ├── res/
│ │ │ ├── layout/
│ │ │ │ ├── main.xml
│ │ │ │ └── rowlayout.xml
│ │ │ ├── menu/
│ │ │ │ ├── inventory.xml
│ │ │ │ └── options_menu.xml
│ │ │ ├── values/
│ │ │ │ ├── dimens.xml
│ │ │ │ └── strings.xml
│ │ │ ├── values-sw600dp/
│ │ │ │ └── dimens.xml
│ │ │ └── values-sw720dp-land/
│ │ │ └── dimens.xml
│ │ └── src/
│ │ └── com/
│ │ └── google/
│ │ └── android/
│ │ └── gcm/
│ │ └── demo/
│ │ └── app/
│ │ ├── CommonUtilities.java
│ │ ├── DemoActivity.java
│ │ ├── GCMIntentService.java
│ │ ├── Item.java
│ │ ├── ServerUtilities.java
│ │ └── SimpleArrayAdapter.java
│ ├── GCM_Registrar_Script/
│ │ ├── code.gs
│ │ ├── scriptdb.gs
│ │ └── ui.html
│ ├── InventoryContentService.gs
│ ├── SharedDb.gs
│ ├── readme.md
│ └── track-and-notify.gs
├── ContentService/
│ ├── Addressbook-VCF/
│ │ ├── Code.gs
│ │ └── vcard_template.html
│ ├── Gmail-RSS/
│ │ ├── code.gs
│ │ └── rss.html
│ ├── Inventory-JSON-API-iOS/
│ │ ├── Inventory-iOS/
│ │ │ ├── Inventory/
│ │ │ │ ├── AppDelegate.h
│ │ │ │ ├── AppDelegate.m
│ │ │ │ ├── Inventory-Info.plist
│ │ │ │ ├── Inventory-Prefix.pch
│ │ │ │ ├── MasterViewController.h
│ │ │ │ ├── MasterViewController.m
│ │ │ │ ├── en.lproj/
│ │ │ │ │ ├── InfoPlist.strings
│ │ │ │ │ └── MainStoryboard.storyboard
│ │ │ │ └── main.m
│ │ │ └── Inventory.xcodeproj/
│ │ │ ├── project.pbxproj
│ │ │ ├── project.xcworkspace/
│ │ │ │ ├── contents.xcworkspacedata
│ │ │ │ └── xcuserdata/
│ │ │ │ └── anagarajan.xcuserdatad/
│ │ │ │ ├── UserInterfaceState.xcuserstate
│ │ │ │ └── WorkspaceSettings.xcsettings
│ │ │ └── xcuserdata/
│ │ │ └── anagarajan.xcuserdatad/
│ │ │ ├── xcdebugger/
│ │ │ │ └── Breakpoints.xcbkptlist
│ │ │ └── xcschemes/
│ │ │ ├── InventorySample.xcscheme
│ │ │ └── xcschememanagement.plist
│ │ └── code.gs
│ ├── Simple-JSONP/
│ │ ├── SimpleHtml-JSFiddle.html
│ │ └── code.gs
│ └── readme.md
├── DriveSDK/
│ ├── AppsScript.gs
│ ├── ChromeWebStoreVersion/
│ │ └── SimpleZipAndSend.gs
│ ├── FlowManager.gs
│ └── readme.md
├── FusionTables/
│ ├── RowUtilities.gs
│ ├── SampleDataExchange.gs
│ └── readme.md
├── GoogleAppsAdminAudit.gs
├── IO2013/
│ ├── Drive/
│ │ ├── Code.gs
│ │ ├── README.md
│ │ ├── SpreadsheetUtils.gs
│ │ └── ui.html
│ └── YouTubeAnalytics/
│ ├── Code.gs
│ ├── README.md
│ ├── oauth2.gs
│ ├── oauthsuccess.html
│ ├── twitter.gs
│ └── ui.html
├── NYTimesCampaignContribution.gs
├── README.md
├── SAP/
│ ├── Forms/
│ │ ├── Code.gs
│ │ └── product_template.html
│ ├── Gmail Schemas/
│ │ ├── Code.gs
│ │ └── mail_template.html
│ ├── README.md
│ └── Sheets/
│ ├── Code.gs
│ └── ui.html
├── Salesforce.com/
│ ├── OAuthAndUploadContactsToSalesforce.gs
│ ├── RowUtilities.gs
│ ├── ScanEmailToSalesforce.gs
│ └── readme.md
├── ScriptDbVisualizer/
│ ├── Code.gs
│ ├── ScriptDbConsole.html
│ └── readme.md
├── Twilio/
│ ├── MakePhoneCall/
│ │ ├── MakePhoneCall.gs
│ │ └── twiml.html
│ ├── RecieveSMS/
│ │ └── RecieveSMS.gs
│ └── readme.md
├── WhiteHouseHackday/
│ ├── Code.gs
│ ├── README.md
│ └── ui.html
└── YouTube/
├── CreateGDLCalendar.gs
├── YouTubeAnalytics.gs
└── readme.md
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
#ignore these files
.DS_Store
================================================
FILE: Android/ClientCode/AndroidManifest.xml
================================================
<?xml version="1.0" encoding="utf-8"?>
<!--
- Copyright 2012 Google Inc.
-
- 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.
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.google.android.gcm.demo.app"
android:versionCode="1"
android:versionName="1.0" >
<!-- GCM requires Android SDK version 2.2 (API level 8) or above. -->
<!--
The targetSdkVersion is optional, but it's always a good practice
to target higher versions.
-->
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="16" />
<!-- GCM connects to Google Services. -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- GCM requires a Google account. -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<!-- Keeps the processor from sleeping when a message is received. -->
<uses-permission android:name="android.permission.WAKE_LOCK" />
<!--
Creates a custom permission so only this app can receive its messages.
NOTE: the permission *must* be called PACKAGE.permission.C2D_MESSAGE,
where PACKAGE is the application's package name.
-->
<permission
android:name="com.google.android.gcm.demo.app.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.google.android.gcm.demo.app.permission.C2D_MESSAGE" />
<!-- This app has permission to register and receive data message. -->
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<!-- Main activity. -->
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:name="com.google.android.gcm.demo.app.DemoActivity"
android:label="@string/app_name"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!--
BroadcastReceiver that will receive intents from GCM
services and handle them to the custom IntentService.
The com.google.android.c2dm.permission.SEND permission is necessary
so only GCM services can send data messages for the app.
-->
<receiver
android:name="com.google.android.gcm.GCMBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<!-- Receives the actual messages. -->
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<!-- Receives the registration id. -->
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="com.google.android.gcm.demo.app" />
</intent-filter>
</receiver>
<!--
Application-specific subclass of GCMBaseIntentService that will
handle received messages.
By default, it must be named .GCMIntentService, unless the
application uses a custom BroadcastReceiver that redefines its name.
-->
<service android:name="com.google.android.gcm.demo.app.GCMIntentService" />
</application>
</manifest>
================================================
FILE: Android/ClientCode/README
================================================
GCM demo app
------------
1.To create the project settings, type:
android update project --name GCMDemo -p . --target android-16
2.To build the app, type:
ant clean debug
(but set SENDER_ID and SERVER_URL on /src/com/google/android/gcm/demo/app/CommonUtilities.java first)
3.To install the app, type
ant installd
================================================
FILE: Android/ClientCode/gen/com/google/android/gcm/demo/app/BuildConfig.java
================================================
/** Automatically generated file. DO NOT MODIFY */
package com.google.android.gcm.demo.app;
public final class BuildConfig {
public final static boolean DEBUG = true;
}
================================================
FILE: Android/ClientCode/gen/com/google/android/gcm/demo/app/Manifest.java
================================================
/* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
package com.google.android.gcm.demo.app;
public final class Manifest {
public static final class permission {
/**
Creates a custom permission so only this app can receive its messages.
NOTE: the permission *must* be called PACKAGE.permission.C2D_MESSAGE,
where PACKAGE is the application's package name.
*/
public static final String C2D_MESSAGE="com.google.android.gcm.demo.app.permission.C2D_MESSAGE";
}
}
================================================
FILE: Android/ClientCode/gen/com/google/android/gcm/demo/app/R.java
================================================
/* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
package com.google.android.gcm.demo.app;
public final class R {
public static final class attr {
}
public static final class dimen {
/** Default screen margins, per the Android Design guidelines.
Customize dimensions originally defined in res/values/dimens.xml (such as
screen margins) for sw720dp devices (e.g. 10" tablets) in landscape here.
*/
public static final int activity_horizontal_margin=0x7f040000;
public static final int activity_vertical_margin=0x7f040001;
}
public static final class drawable {
public static final int ic_launcher=0x7f020000;
public static final int ic_stat_gcm=0x7f020001;
}
public static final class id {
public static final int action_settings=0x7f070004;
public static final int display=0x7f070000;
public static final int inventoryCount=0x7f070003;
public static final int inventoryName=0x7f070001;
public static final int label=0x7f070002;
public static final int options_clear=0x7f070007;
public static final int options_exit=0x7f070008;
public static final int options_refresh_data=0x7f070009;
public static final int options_register=0x7f070005;
public static final int options_unregister=0x7f070006;
}
public static final class layout {
public static final int main=0x7f030000;
public static final int rowlayout=0x7f030001;
}
public static final class menu {
public static final int inventory=0x7f060000;
public static final int options_menu=0x7f060001;
}
public static final class string {
public static final int action_settings=0x7f050013;
public static final int already_registered=0x7f050002;
public static final int app_name=0x7f050000;
public static final int error_config=0x7f050001;
public static final int gcm_deleted=0x7f050008;
public static final int gcm_error=0x7f050006;
public static final int gcm_message=0x7f050005;
public static final int gcm_recoverable_error=0x7f050007;
public static final int gcm_registered=0x7f050003;
public static final int gcm_unregistered=0x7f050004;
public static final int hello_world=0x7f050014;
public static final int options_clear=0x7f050010;
public static final int options_exit=0x7f050011;
public static final int options_refresh_data=0x7f050015;
public static final int options_register=0x7f05000e;
public static final int options_unregister=0x7f05000f;
public static final int server_register_error=0x7f05000c;
public static final int server_registered=0x7f05000a;
public static final int server_registering=0x7f050009;
public static final int server_unregister_error=0x7f05000d;
public static final int server_unregistered=0x7f05000b;
public static final int title_activity_inventory=0x7f050012;
}
}
================================================
FILE: Android/ClientCode/project.properties
================================================
# This file is automatically generated by Android Tools.
# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
#
# This file must be checked in Version Control Systems.
#
# To customize properties used by the Ant build system edit
# "ant.properties", and override values to adapt the script to your
# project structure.
#
# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home):
#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
# Project target.
target=android-17
================================================
FILE: Android/ClientCode/res/layout/main.xml
================================================
<?xml version="1.0" encoding="utf-8"?>
<!--
- Copyright 2012 Google Inc.
-
- 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.
-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/display"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textIsSelectable="true"/>
<ListView
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
================================================
FILE: Android/ClientCode/res/layout/rowlayout.xml
================================================
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/inventoryName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@+id/label"
android:textSize="17pt" >
</TextView>
<TextView
android:id="@+id/inventoryCount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:text="@+id/label"
android:textAlignment="center"
android:textSize="15pt" >
</TextView>
</LinearLayout>
================================================
FILE: Android/ClientCode/res/menu/inventory.xml
================================================
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/action_settings"
android:orderInCategory="100"
android:showAsAction="never"
android:title="@string/action_settings"/>
</menu>
================================================
FILE: Android/ClientCode/res/menu/options_menu.xml
================================================
<?xml version="1.0" encoding="utf-8"?>
<!--
- Copyright 2012 Google Inc.
-
- 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.
-->
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<!-- Typically, an application registers automatically, so options below
are disabled. Uncomment them if you want to manually register or
unregister the device (you will also need to uncomment the equivalent
options on DemoActivity.onOptionsItemSelected())
-->
<!--
<item
android:id="@+id/options_register"
android:title="@string/options_register">
</item>
<item
android:id="@+id/options_unregister"
android:title="@string/options_unregister">
</item>
-->
<item android:id="@+id/options_register" android:title="@string/options_register"></item><item android:id="@+id/options_unregister" android:title="@string/options_unregister"></item><item
android:id="@+id/options_clear"
android:title="@string/options_clear">
</item>
<item
android:id="@+id/options_exit"
android:title="@string/options_exit">
</item>
<item android:id="@+id/options_refresh_data" android:title="@string/options_refresh_data"></item>
</menu>
================================================
FILE: Android/ClientCode/res/values/dimens.xml
================================================
<resources>
<!-- Default screen margins, per the Android Design guidelines. -->
<dimen name="activity_horizontal_margin">16dp</dimen>
<dimen name="activity_vertical_margin">16dp</dimen>
</resources>
================================================
FILE: Android/ClientCode/res/values/strings.xml
================================================
<?xml version="1.0" encoding="utf-8"?>
<!--
- Copyright 2012 Google Inc.
-
- 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.
-->
<resources>
<string name="app_name">Apps Script GDL</string>
<string name="error_config">Please set the %1$s constant and recompile the app.</string>
<string name="already_registered">Device is already registered on server.</string>
<string name="gcm_registered">From GCM: device successfully registered!</string>
<string name="gcm_unregistered">From GCM: device successfully unregistered!</string>
<string name="gcm_message">From GCM: you got message!</string>
<string name="gcm_error">From GCM: error (%1$s).</string>
<string name="gcm_recoverable_error">From GCM: recoverable error (%1$s).</string>
<string name="gcm_deleted">From GCM: server deleted %1$d pending messages!</string>
<string name="server_registering">Trying (attempt %1$d/%2$d) to register device on Demo Server.</string>
<string name="server_registered">From Demo Server: successfully added device!</string>
<string name="server_unregistered">From Demo Server: successfully removed device!</string>
<string name="server_register_error">Could not register device on Demo Server after %1$d attempts.</string>
<string name="server_unregister_error">Could not unregister device on Demo Server (%1$s).</string>
<string name="options_register">Register</string>
<string name="options_unregister">Unregister</string>
<string name="options_clear">Clear</string>
<string name="options_exit">Exit</string>
<string name="title_activity_inventory">Inventory</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="options_refresh_data">Refresh Data</string>
</resources>
================================================
FILE: Android/ClientCode/res/values-sw600dp/dimens.xml
================================================
<resources>
<!--
Customize dimensions originally defined in res/values/dimens.xml (such as
screen margins) for sw600dp devices (e.g. 7" tablets) here.
-->
</resources>
================================================
FILE: Android/ClientCode/res/values-sw720dp-land/dimens.xml
================================================
<resources>
<!--
Customize dimensions originally defined in res/values/dimens.xml (such as
screen margins) for sw720dp devices (e.g. 10" tablets) in landscape here.
-->
<dimen name="activity_horizontal_margin">128dp</dimen>
</resources>
================================================
FILE: Android/ClientCode/src/com/google/android/gcm/demo/app/CommonUtilities.java
================================================
/*
* Copyright 2012 Google Inc.
*
* 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.
*/
package com.google.android.gcm.demo.app;
import android.content.Context;
import android.content.Intent;
/**
* Helper class providing methods and constants common to other classes in the
* app.
*/
public final class CommonUtilities {
/**
* Base URL of the Demo Server (such as http://my_host:8080/gcm-demo)
*/
static final String SERVER_URL = "https://script.google.com/macros/s/YOUR_SERVER_URL/exec";
/**
* Google API project id registered to use GCM.
*/
static final String SENDER_ID = "YOUR_SENDER_ID";
/**
* Tag used on log messages.
*/
static final String TAG = "GCMDemo";
/**
* Intent used to display a message in the screen.
*/
static final String DISPLAY_MESSAGE_ACTION =
"com.google.android.gcm.demo.app.DISPLAY_MESSAGE";
/**
* Intent's extra that contains the message to be displayed.
*/
static final String EXTRA_MESSAGE = "message";
/**
* Notifies UI to display a message.
* <p>
* This method is defined in the common helper because it's used both by
* the UI and the background service.
*
* @param context application's context.
* @param message message to be displayed.
*/
static void displayMessage(Context context, String message) {
Intent intent = new Intent(DISPLAY_MESSAGE_ACTION);
intent.putExtra(EXTRA_MESSAGE, message);
context.sendBroadcast(intent);
}
}
================================================
FILE: Android/ClientCode/src/com/google/android/gcm/demo/app/DemoActivity.java
================================================
/*
* Copyright 2012 Google Inc.
*
* 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.
*/
package com.google.android.gcm.demo.app;
import static com.google.android.gcm.demo.app.CommonUtilities.DISPLAY_MESSAGE_ACTION;
import static com.google.android.gcm.demo.app.CommonUtilities.EXTRA_MESSAGE;
import static com.google.android.gcm.demo.app.CommonUtilities.SENDER_ID;
import static com.google.android.gcm.demo.app.CommonUtilities.SERVER_URL;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import com.google.android.gcm.GCMRegistrar;
import android.app.ListActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.TextView;
/**
* Main UI for the demo app.
*/
public class DemoActivity extends ListActivity {
TextView mDisplay;
AsyncTask<Void, Void, Void> mRegisterTask;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
checkNotNull(SERVER_URL, "SERVER_URL");
checkNotNull(SENDER_ID, "SENDER_ID");
// Make sure the device has the proper dependencies.
GCMRegistrar.checkDevice(this);
// Make sure the manifest was properly set - comment out this line
// while developing the app, then uncomment it when it's ready.
GCMRegistrar.checkManifest(this);
setContentView(R.layout.main);
mDisplay = (TextView) findViewById(R.id.display);
registerReceiver(mHandleMessageReceiver,
new IntentFilter(DISPLAY_MESSAGE_ACTION));
final String regId = GCMRegistrar.getRegistrationId(this);
final Context context = this;
if (regId.equals("")) {
// Automatically registers application on startup.
GCMRegistrar.register(this, SENDER_ID);
} else {
// Device is already registered on GCM, check server.
if (GCMRegistrar.isRegisteredOnServer(this)) {
// Skips registration.
mDisplay.append(getString(R.string.already_registered) + "\n");
} else {
// Try to register again, but not in the UI thread.
// It's also necessary to cancel the thread onDestroy(),
// hence the use of AsyncTask instead of a raw thread.
mRegisterTask = new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
boolean registered =
ServerUtilities.register(context, regId);
// At this point all attempts to register with the app
// server failed, so we need to unregister the device
// from GCM - the app will try to register again when
// it is restarted. Note that GCM will send an
// unregistered callback upon completion, but
// GCMIntentService.onUnregistered() will ignore it.
if (!registered) {
GCMRegistrar.unregister(context);
}
return null;
}
@Override
protected void onPostExecute(Void result) {
mRegisterTask = null;
}
};
mRegisterTask.execute(null, null, null);
}
}
MyTask task = new MyTask();
task.execute();
}
private class MyTask extends AsyncTask<Void, Void, Void> {
ArrayList<Item> items = new ArrayList<Item>();
@Override
protected Void doInBackground(Void... params) {
try {
HttpClient hc = new DefaultHttpClient();
String URL = "https://script.google.com/macros/s/YOU_DATA_URL/exec";
HttpGet get = new HttpGet(URL);
HttpResponse rp = hc.execute(get);
if(rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
{
String result = EntityUtils.toString(rp.getEntity());
JSONArray objects = new JSONArray(result);
for (int i = 0; i < objects.length(); i++) {
JSONObject session = objects.getJSONObject(i);
Item item = new Item();
item.name = session.getString("item");
item.count = session.getString("quantity");
items.add(item);
}
}
} catch (Exception e) {
Log.e("ItemFeed", "Error loading JSON", e);
}
return null;
}
@Override
protected void onPostExecute(Void result) {
SimpleArrayAdapter adapter = new SimpleArrayAdapter(DemoActivity.this,items);
setListAdapter(adapter);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.options_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
/*
* Typically, an application registers automatically, so options
* below are disabled. Uncomment them if you want to manually
* register or unregister the device (you will also need to
* uncomment the equivalent options on options_menu.xml).
*/
case R.id.options_register:
GCMRegistrar.register(this, SENDER_ID);
return true;
case R.id.options_unregister:
GCMRegistrar.unregister(this);
return true;
case R.id.options_clear:
mDisplay.setText(null);
return true;
case R.id.options_exit:
finish();
return true;
case R.id.options_refresh_data:
MyTask task = new MyTask();
task.execute();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
protected void onDestroy() {
if (mRegisterTask != null) {
mRegisterTask.cancel(true);
}
unregisterReceiver(mHandleMessageReceiver);
GCMRegistrar.onDestroy(this);
super.onDestroy();
}
private void checkNotNull(Object reference, String name) {
if (reference == null) {
throw new NullPointerException(
getString(R.string.error_config, name));
}
}
private final BroadcastReceiver mHandleMessageReceiver =
new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
mDisplay.append(newMessage + "\n");
MyTask task = new MyTask();
task.execute();
}
};
}
================================================
FILE: Android/ClientCode/src/com/google/android/gcm/demo/app/GCMIntentService.java
================================================
/*
* Copyright 2012 Google Inc.
*
* 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.
*/
package com.google.android.gcm.demo.app;
import static com.google.android.gcm.demo.app.CommonUtilities.SENDER_ID;
import static com.google.android.gcm.demo.app.CommonUtilities.displayMessage;
import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.util.Log;
import com.google.android.gcm.GCMBaseIntentService;
import com.google.android.gcm.GCMRegistrar;
/**
* IntentService responsible for handling GCM messages.
*/
public class GCMIntentService extends GCMBaseIntentService {
@SuppressWarnings("hiding")
private static final String TAG = "GCMIntentService";
public GCMIntentService() {
super(SENDER_ID);
}
@Override
protected void onRegistered(Context context, String registrationId) {
Log.i(TAG, "Device registered: regId = " + registrationId);
displayMessage(context, getString(R.string.gcm_registered));
ServerUtilities.register(context, registrationId);
}
@Override
protected void onUnregistered(Context context, String registrationId) {
Log.i(TAG, "Device unregistered");
displayMessage(context, getString(R.string.gcm_unregistered));
if (GCMRegistrar.isRegisteredOnServer(context)) {
ServerUtilities.unregister(context, registrationId);
} else {
// This callback results from the call to unregister made on
// ServerUtilities when the registration to the server failed.
Log.i(TAG, "Ignoring unregister callback");
}
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
@Override
protected void onMessage(Context context, Intent intent) {
Log.i(TAG, "Received message");
String message = intent.getExtras().getString("message", getString(R.string.gcm_message));
displayMessage(context, message);
// notifies user
generateNotification(context, message);
}
@Override
protected void onDeletedMessages(Context context, int total) {
Log.i(TAG, "Received deleted messages notification");
String message = getString(R.string.gcm_deleted, total);
displayMessage(context, message);
// notifies user
generateNotification(context, message);
}
@Override
public void onError(Context context, String errorId) {
Log.i(TAG, "Received error: " + errorId);
displayMessage(context, getString(R.string.gcm_error, errorId));
}
@Override
protected boolean onRecoverableError(Context context, String errorId) {
// log message
Log.i(TAG, "Received recoverable error: " + errorId);
displayMessage(context, getString(R.string.gcm_recoverable_error,
errorId));
return super.onRecoverableError(context, errorId);
}
/**
* Issues a notification to inform the user that server has sent a message.
*/
private static void generateNotification(Context context, String message) {
int icon = R.drawable.ic_stat_gcm;
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(icon, message, when);
String title = context.getString(R.string.app_name);
Intent notificationIntent = new Intent(context, DemoActivity.class);
// set intent so it does not start a new activity
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent =
PendingIntent.getActivity(context, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, title, message, intent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.defaults = Notification.DEFAULT_ALL;
notificationManager.notify(0, notification);
}
}
================================================
FILE: Android/ClientCode/src/com/google/android/gcm/demo/app/Item.java
================================================
package com.google.android.gcm.demo.app;
public class Item {
String name;
String count;
}
================================================
FILE: Android/ClientCode/src/com/google/android/gcm/demo/app/ServerUtilities.java
================================================
/*
* Copyright 2012 Google Inc.
*
* 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.
*/
package com.google.android.gcm.demo.app;
import static com.google.android.gcm.demo.app.CommonUtilities.SERVER_URL;
import static com.google.android.gcm.demo.app.CommonUtilities.TAG;
import static com.google.android.gcm.demo.app.CommonUtilities.displayMessage;
import com.google.android.gcm.GCMRegistrar;
import android.content.Context;
import android.util.Log;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
/**
* Helper class used to communicate with the demo server.
*/
public final class ServerUtilities {
private static final int MAX_ATTEMPTS = 5;
private static final int BACKOFF_MILLI_SECONDS = 2000;
private static final Random random = new Random();
/**
* Register this account/device pair within the server.
*
* @return whether the registration succeeded or not.
*/
static boolean register(final Context context, final String regId) {
Log.i(TAG, "registering device (regId = " + regId + ")");
String serverUrl = SERVER_URL;// + "/register";
Map<String, String> params = new HashMap<String, String>();
params.put("regId", regId);
params.put("type", "register");
long backoff = BACKOFF_MILLI_SECONDS + random.nextInt(1000);
// Once GCM returns a registration id, we need to register it in the
// demo server. As the server might be down, we will retry it a couple
// times.
for (int i = 1; i <= MAX_ATTEMPTS; i++) {
Log.d(TAG, "Attempt #" + i + " to register");
try {
displayMessage(context, context.getString(
R.string.server_registering, i, MAX_ATTEMPTS));
post(serverUrl, params);
GCMRegistrar.setRegisteredOnServer(context, true);
String message = context.getString(R.string.server_registered);
CommonUtilities.displayMessage(context, message);
return true;
} catch (IOException e) {
// Here we are simplifying and retrying on any error; in a real
// application, it should retry only on unrecoverable errors
// (like HTTP error code 503).
Log.e(TAG, "Failed to register on attempt " + i, e);
if (i == MAX_ATTEMPTS) {
break;
}
try {
Log.d(TAG, "Sleeping for " + backoff + " ms before retry");
Thread.sleep(backoff);
} catch (InterruptedException e1) {
// Activity finished before we complete - exit.
Log.d(TAG, "Thread interrupted: abort remaining retries!");
Thread.currentThread().interrupt();
return false;
}
// increase backoff exponentially
backoff *= 2;
}
}
String message = context.getString(R.string.server_register_error,
MAX_ATTEMPTS);
CommonUtilities.displayMessage(context, message);
return false;
}
/**
* Unregister this account/device pair within the server.
*/
static void unregister(final Context context, final String regId) {
Log.i(TAG, "unregistering device (regId = " + regId + ")");
String serverUrl = SERVER_URL;// + "/unregister";
Map<String, String> params = new HashMap<String, String>();
params.put("regId", regId);
params.put("type","unregister");
try {
post(serverUrl, params);
GCMRegistrar.setRegisteredOnServer(context, false);
String message = context.getString(R.string.server_unregistered);
CommonUtilities.displayMessage(context, message);
} catch (IOException e) {
// At this point the device is unregistered from GCM, but still
// registered in the server.
// We could try to unregister again, but it is not necessary:
// if the server tries to send a message to the device, it will get
// a "NotRegistered" error message and should unregister the device.
String message = context.getString(R.string.server_unregister_error,
e.getMessage());
CommonUtilities.displayMessage(context, message);
}
}
/**
* Issue a POST request to the server.
*
* @param endpoint POST address.
* @param params request parameters.
*
* @throws IOException propagated from POST.
*/
private static void post(String endpoint, Map<String, String> params)
throws IOException {
URL url;
try {
url = new URL(endpoint);
} catch (MalformedURLException e) {
throw new IllegalArgumentException("invalid url: " + endpoint);
}
StringBuilder bodyBuilder = new StringBuilder();
Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
// constructs the POST body using the parameters
while (iterator.hasNext()) {
Entry<String, String> param = iterator.next();
bodyBuilder.append(param.getKey()).append('=')
.append(param.getValue());
if (iterator.hasNext()) {
bodyBuilder.append('&');
}
}
String body = bodyBuilder.toString();
Log.v(TAG, "Posting '" + body + "' to " + url);
byte[] bytes = body.getBytes();
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setFixedLengthStreamingMode(bytes.length);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
// post the request
OutputStream out = conn.getOutputStream();
out.write(bytes);
out.close();
// handle the response
int status = conn.getResponseCode();
if (status != 200) {
throw new IOException("Post failed with error code " + status);
}
} finally {
if (conn != null) {
conn.disconnect();
}
}
}
}
================================================
FILE: Android/ClientCode/src/com/google/android/gcm/demo/app/SimpleArrayAdapter.java
================================================
package com.google.android.gcm.demo.app;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class SimpleArrayAdapter extends ArrayAdapter<Item> {
private final Context context;
private final ArrayList<Item> values;
public SimpleArrayAdapter(Context context, ArrayList<Item> values) {
super(context, R.layout.rowlayout, values);
this.context = context;
this.values = values;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.rowlayout, parent, false);
Item i = values.get(position);
TextView nameTextView = (TextView) rowView.findViewById(R.id.inventoryName);
TextView countTextView = (TextView) rowView.findViewById(R.id.inventoryCount);
nameTextView.setText(i.name);
countTextView.setText(i.count);
return rowView;
}
}
================================================
FILE: Android/GCM_Registrar_Script/code.gs
================================================
function doGet() {
return HtmlService.createHtmlOutputFromFile('ui');
}
//import shared db library
//used the shared version intead of -
//ScriptDb.getMyDb()
var db = SharedDb.getDb();
function doPost(e) {
if(e.parameter.regId){
var reg = db.query({regId : e.parameter.regId}).next();
if(reg && e.parameter.type === 'unregister'){
db.remove(reg);
}
else if(!reg && e.parameter.type === 'register'){
db.save(e.parameter);
}
}
}
================================================
FILE: Android/GCM_Registrar_Script/scriptdb.gs
================================================
var db = SharedDb.getDb();
function saveObjToDb(obj){
try{
var savedObj = db.save(obj);
return "Saved ID - " + savedObj.getId();
}catch(e){
log(e);
throw(e);
}
}
function getCount(query){
try{
return "Current count for query is - " + db.count(query);
}catch(e){
log(e);
throw(e);
}
}
function loadIDsFromDb(idlist){
try{
return db.load(idlist);
}catch(e){
log(e);
throw(e);
}
}
function deleteByIds(idlist){
var obs_to_remove = loadIDsFromDb(idlist);
var results = db.removeBatch(obs_to_remove, false);
if (db.allOk(results)) {
return "Delete by IDs successfull!";
}
var failedObs = [];
for (var i = 0; i < results.length; i++) {
if (!results[i].successful()) {
failedObs.push(obs_to_remove[i]);
}
}
return "Failed to delete " + failedObs.length + " item(s) out of " + results.length;
}
function queryFromDb(query){
try{
var result = db.query(query);
var response = {};
while (result.hasNext()) {
var current = result.next();
response[current.getId()] = current;
}
return response;
}catch(e){
log(e);
throw(e);
}
}
function deleteAll(query) {
try{
while (true) {
var result = db.query(query);
if (result.getSize() == 0) {
break;
}
while (result.hasNext()) {
db.remove(result.next());
}
}
return "Delete for specified query successful!";
}catch(e){
log(e);
throw(e);
}
}
function log(msg){
//write to a logger here
//DocsList.getFileById('0B0JNj_IM2wiPMS1lZTFhZjVjNC0yZTBjLTRiOWItYWVhMy0yYTU1ZjdkMGVkMGE').append(msg+'\n');
}
================================================
FILE: Android/GCM_Registrar_Script/ui.html
================================================
<html>
<style>
pre {outline: 1px solid #ccc; padding: 5px; margin: 5px; }
.string { color: green; }
.number { color: darkorange; }
.boolean { color: blue; }
.null { color: magenta; }
.key { color: red; }
</style>
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script>
function output(inp) {
$('#results').prepend(inp);
}
//courtesy of http://stackoverflow.com/a/7220510/662551
function syntaxHighlight(json) {
json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
var cls = 'number';
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = 'key';
} else {
cls = 'string';
}
} else if (/true|false/.test(match)) {
cls = 'boolean';
} else if (/null/.test(match)) {
cls = 'null';
}
return '<span class="' + cls + '">' + match + '</span>';
});
}
$(document).ready(function() {
$('#saveItem').click(function(){
var input = $('#textarea').val();
input = JSON.parse(input);
google.script.run.withSuccessHandler(handleMessageResponse).withFailureHandler(addToLog).saveObjToDb(input);
});
$('#runQuery').click(function(){
var input = $('#textarea').val();
input = JSON.parse(input);
google.script.run.withSuccessHandler(handleQueryResponse).withFailureHandler(addToLog).queryFromDb(input);
});
$('#deleteAll').click(function(){
var input = $('#textarea').val();
input = JSON.parse(input);
google.script.run.withSuccessHandler(handleMessageResponse).withFailureHandler(addToLog).deleteAll(input);
});
$('#loadId').click(function(){
var input = $('#textarea').val();
var re = /\s*,\s*/;
var idList = input.split(re);
google.script.run.withSuccessHandler(handleQueryResponse).withFailureHandler(addToLog).loadIDsFromDb(idList);
});
$('#deleteByIds').click(function(){
var input = $('#textarea').val();
var re = /\s*,\s*/;
var idList = input.split(re);
google.script.run.withSuccessHandler(handleMessageResponse).withFailureHandler(addToLog).deleteByIds(idList);
});
$('#count').click(function(){
var input = $('#textarea').val();
input = JSON.parse(input);
google.script.run.withSuccessHandler(handleMessageResponse).withFailureHandler(addToLog).getCount(input);
});
});
function handleQueryResponse(responseObj){
$('#results').prepend('<hr><hr>');
if(Object.keys(responseObj).length==0){
output("No results found for query!");
}
//TODO: for load by IDs, this will print index, not object IDs
for (var prop in responseObj) {
if (responseObj.hasOwnProperty(prop)) {
output('<pre>ID: ' + prop+'\n'+syntaxHighlight(JSON.stringify(responseObj[prop], undefined, 4))+'</pre>');
}
}
}
function handleMessageResponse(response){
$('#results').prepend('<hr><hr>');
output(response);
}
function addToLog(error){
$('#results').prepend('<hr><hr>');
output("Error " + JSON.stringify(error));
}
</script>
<body>
<h2>Simple ScriptDb tester</h2>
<b>Enter a JavaScript Object to store, a ScriptDb query to run or IDs to lookup and press the appropriate button below</b><br>
<textarea id="textarea" rows="10" cols="100"></textarea><br>
<button id="count">Get Count</button>
<button id="saveItem">Save Object</button>
<button id="runQuery">Run Query</button>
<button id="loadId">Load by ID</button>
<button id="deleteByIds">Delete by ID</button>
<button id="deleteAll">Delete for Query</button>
<br><br>
<div id="results"></div>
<br><br>
By <a href="https://plus.google.com/117678608428606781684/posts">Arun Nagarajan</a>
</body>
</html>
================================================
FILE: Android/InventoryContentService.gs
================================================
function doGet() {
var ss = SpreadsheetApp.openById('YOUR_SS_ID');
var sheet = ss.getSheets()[0];
// Get the range of cells that store employee data.
var employeeDataRange = ss.getRangeByName("inventoryData");
// For every row of employee data, generate an employee object.
var employeeObjects = getRowsData(sheet, employeeDataRange);
return ContentService.createTextOutput(JSON.stringify(employeeObjects)).setMimeType(ContentService.MimeType.JSON);
}
// getRowsData iterates row by row in the input range and returns an array of objects.
// Each object contains all the data for a given row, indexed by its normalized column name.
// Arguments:
// - sheet: the sheet object that contains the data to be processed
// - range: the exact range of cells where the data is stored
// - columnHeadersRowIndex: specifies the row number where the column names are stored.
// This argument is optional and it defaults to the row immediately above range;
// Returns an Array of objects.
function getRowsData(sheet, range, columnHeadersRowIndex) {
columnHeadersRowIndex = columnHeadersRowIndex || range.getRowIndex() - 1;
var numColumns = range.getLastColumn() - range.getColumn() + 1;
var headersRange = sheet.getRange(columnHeadersRowIndex, range.getColumn(), 1, numColumns);
var headers = headersRange.getValues()[0];
return getObjects(range.getValues(), normalizeHeaders(headers));
}
// For every row of data in data, generates an object that contains the data. Names of
// object fields are defined in keys.
// Arguments:
// - data: JavaScript 2d array
// - keys: Array of Strings that define the property names for the objects to create
function getObjects(data, keys) {
var objects = [];
for (var i = 0; i < data.length; ++i) {
var object = {};
var hasData = false;
for (var j = 0; j < data[i].length; ++j) {
var cellData = data[i][j];
if (isCellEmpty(cellData)) {
continue;
}
object[keys[j]] = cellData;
hasData = true;
}
if (hasData) {
objects.push(object);
}
}
return objects;
}
// Returns an Array of normalized Strings.
// Arguments:
// - headers: Array of Strings to normalize
function normalizeHeaders(headers) {
var keys = [];
for (var i = 0; i < headers.length; ++i) {
var key = normalizeHeader(headers[i]);
if (key.length > 0) {
keys.push(key);
}
}
return keys;
}
// Normalizes a string, by removing all alphanumeric characters and using mixed case
// to separate words. The output will always start with a lower case letter.
// This function is designed to produce JavaScript object property names.
// Arguments:
// - header: string to normalize
// Examples:
// "First Name" -> "firstName"
// "Market Cap (millions) -> "marketCapMillions
// "1 number at the beginning is ignored" -> "numberAtTheBeginningIsIgnored"
function normalizeHeader(header) {
var key = "";
var upperCase = false;
for (var i = 0; i < header.length; ++i) {
var letter = header[i];
if (letter == " " && key.length > 0) {
upperCase = true;
continue;
}
if (!isAlnum(letter)) {
continue;
}
if (key.length == 0 && isDigit(letter)) {
continue; // first character must be a letter
}
if (upperCase) {
upperCase = false;
key += letter.toUpperCase();
} else {
key += letter.toLowerCase();
}
}
return key;
}
// Returns true if the cell where cellData was read from is empty.
// Arguments:
// - cellData: string
function isCellEmpty(cellData) {
return typeof(cellData) == "string" && cellData == "";
}
// Returns true if the character char is alphabetical, false otherwise.
function isAlnum(char) {
return char >= 'A' && char <= 'Z' ||
char >= 'a' && char <= 'z' ||
isDigit(char);
}
// Returns true if the character char is a digit, false otherwise.
function isDigit(char) {
return char >= '0' && char <= '9';
}
// Given a JavaScript 2d Array, this function returns the transposed table.
// Arguments:
// - data: JavaScript 2d Array
// Returns a JavaScript 2d Array
// Example: arrayTranspose([[1,2,3],[4,5,6]]) returns [[1,4],[2,5],[3,6]].
function arrayTranspose(data) {
if (data.length == 0 || data[0].length == 0) {
return null;
}
var ret = [];
for (var i = 0; i < data[0].length; ++i) {
ret.push([]);
}
for (var i = 0; i < data.length; ++i) {
for (var j = 0; j < data[i].length; ++j) {
ret[j][i] = data[i][j];
}
}
return ret;
}
================================================
FILE: Android/SharedDb.gs
================================================
var db = ScriptDb.getMyDb();
function getDb(){
return db;
}
function sendGCM(msg){
msg = msg || 'hello world!'; //give default message for debugging
var regIds = [];
var result = db.query({});
while (result.hasNext()) {
var current = result.next();
regIds.push(current.regId);
}
var apiKey = 'YOUR_API_KEY';
var payload = {'registration_ids' : regIds,
'data' : {
'message' : msg
}};
var urlFetchOptions = {'contentType' : 'application/json',
'headers' : {'Authorization' : 'key=' + apiKey},
'method' : 'post',
'payload' : JSON.stringify(payload)};
var gcmUrl = 'https://android.googleapis.com/gcm/send';
var response = UrlFetchApp.fetch(gcmUrl,urlFetchOptions).getContentText()
Logger.log(response);//for testing purposes. improve error handling here
}
================================================
FILE: Android/readme.md
================================================
Click the image below for video with more details -
[](http://www.youtube.com/watch?v=RSgMEtRl0sw&list=PL68F511F6E3C122EB)
================================================
FILE: Android/track-and-notify.gs
================================================
//create an onEdit trigger for this! in a spreadsheet bound script
//import shared db library
function sendNotification(){
var msg = "Edited at: " + new Date().toTimeString();
SharedDb.sendGCM(msg);
}
================================================
FILE: ContentService/Addressbook-VCF/Code.gs
================================================
function doGet() {
var contact = ContactsApp.getContact('youremail@gmail.com');
var t = HtmlService.createTemplateFromFile('vcard_template');
t.contact = contact;
var output = t.evaluate().getContent();
return ContentService.createTextOutput(output).downloadAsFile('ContactCard.vcf');
}
================================================
FILE: ContentService/Addressbook-VCF/vcard_template.html
================================================
BEGIN:VCARD
FN:<?= contact.getFullName(); ?>
TITLE:General Manager
ORG:<?= contact.getFullName(); ?>;North American Division;Manufacturing
ADR;POSTAL;WORK:;;P.O. Box 10010;AnyCity;AnyState;00000;U.S.A.
LABEL;POSTAL;WORK;ENCODING=QUOTED-PRINTABLE:P.O. Box 10010=0D=0A=
Anywhere, TN 37849=0D=0A=U.S.A.
ADR;PARCEL;WORK:;133 Anywhere St.;Suite 360;AnyCity;AnyState;00000;U.S.A.
LABEL;POSTAL;WORK;ENCODING=QUOTED-PRINTABLE:133 Anywhere St.=0D=0A=
Anywhere, TN 37849=0D=0A=U.S.A.
TEL;Work;VOICE;MESG;PREF:+1-234-456-7891 x56473
TEL;Home:+1-234-456-7891
TEL;Pager:+1-234-456-7891
TEL;Cell:+1-234-456-7891
TEL;Modem;FAX:+1-234-456-7891,,*3
EMAIL;Internet:anywhere@anywhere.com
URL:http://www.anywhere.com/mrh.vcf
UID:http://www.anywhere.com/mrh.vcf
TZ:-0500
BDAY:1997-11-29
REV:20090401T065518
VERSION:2.1
END:VCARD
================================================
FILE: ContentService/Gmail-RSS/code.gs
================================================
function doGet() {
var content = HtmlService.createTemplateFromFile('rss').evaluate().getContent();
return ContentService.createTextOutput(content).setMimeType(ContentService.MimeType.RSS);
}
================================================
FILE: ContentService/Gmail-RSS/rss.html
================================================
<rss version = "2.0">
<channel>
<title>Gmail Feed</title>
<? var threads = GmailApp.getInboxThreads();
var messages = GmailApp.getMessagesForThreads(threads);
for (var t in threads){ ?>
<item>
<title><?= threads[t].getFirstMessageSubject() ?></title>
<description><?= messages[t][0].getBody() ?></description>
<guid><?= threads[t].getId() ?></guid>
<pubDate><?= threads[t].getLastMessageDate().toUTCString() ?></pubDate>
</item>
<? } ?>
</channel>
</rss>
================================================
FILE: ContentService/Inventory-JSON-API-iOS/Inventory-iOS/Inventory/AppDelegate.h
================================================
#import <UIKit/UIKit.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end
================================================
FILE: ContentService/Inventory-JSON-API-iOS/Inventory-iOS/Inventory/AppDelegate.m
================================================
#import "AppDelegate.h"
@implementation AppDelegate
@synthesize window = _window;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application
{
/*
Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
*/
}
- (void)applicationDidEnterBackground:(UIApplication *)application
{
/*
Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
*/
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
/*
Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
*/
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
/*
Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
*/
}
- (void)applicationWillTerminate:(UIApplication *)application
{
/*
Called when the application is about to terminate.
Save data if appropriate.
See also applicationDidEnterBackground:.
*/
}
@end
================================================
FILE: ContentService/Inventory-JSON-API-iOS/Inventory-iOS/Inventory/Inventory-Info.plist
================================================
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleDisplayName</key>
<string>${PRODUCT_NAME}</string>
<key>CFBundleExecutable</key>
<string>${EXECUTABLE_NAME}</string>
<key>CFBundleIconFiles</key>
<array/>
<key>CFBundleIdentifier</key>
<string>entaq.${PRODUCT_NAME:rfc1034identifier}</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>${PRODUCT_NAME}</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1.0</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>UIMainStoryboardFile</key>
<string>MainStoryboard</string>
<key>UIRequiredDeviceCapabilities</key>
<array>
<string>armv7</string>
</array>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
</dict>
</plist>
================================================
FILE: ContentService/Inventory-JSON-API-iOS/Inventory-iOS/Inventory/Inventory-Prefix.pch
================================================
#import <Availability.h>
#ifndef __IPHONE_5_0
#warning "This project uses features only available in iOS SDK 5.0 and later."
#endif
#ifdef __OBJC__
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#endif
================================================
FILE: ContentService/Inventory-JSON-API-iOS/Inventory-iOS/Inventory/MasterViewController.h
================================================
#import <UIKit/UIKit.h>
@interface MasterViewController : UITableViewController {
NSArray *Items;
}
- (void)fetchItems;
- (IBAction)refreshItems:(id)sender;
@end
================================================
FILE: ContentService/Inventory-JSON-API-iOS/Inventory-iOS/Inventory/MasterViewController.m
================================================
#import "MasterViewController.h"
@implementation MasterViewController
- (void)awakeFromNib
{
[super awakeFromNib];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
[self fetchItems];
}
- (void)fetchItems
{
NSString *ServiceURL = @"https://script.google.com/macros/s/AKfycbyonCfUtv-tbIAUO4okOYI8sUCQR-hnJGcOAq8QCQ_86XYc8qg/exec";
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData* data = [NSData dataWithContentsOfURL:
[NSURL URLWithString: ServiceURL]];
NSError* error;
Items = [NSJSONSerialization JSONObjectWithData:data
options:kNilOptions
error:&error];
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
});
}
- (IBAction)refreshItems:(id)sender {
[self fetchItems];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return Items.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"ItemCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
NSDictionary *Item = [Items objectAtIndex:indexPath.row];
NSString *text = [Item objectForKey:@"item"];
NSString *name = [Item objectForKey:@"quantity"];
cell.textLabel.text = text;
cell.detailTextLabel.text = [NSString stringWithFormat:@"Current quantity %@", name];
return cell;
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
@end
================================================
FILE: ContentService/Inventory-JSON-API-iOS/Inventory-iOS/Inventory/en.lproj/InfoPlist.strings
================================================
/* Localized versions of Info.plist keys */
================================================
FILE: ContentService/Inventory-JSON-API-iOS/Inventory-iOS/Inventory/en.lproj/MainStoryboard.storyboard
================================================
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="2.0" toolsVersion="2844" systemVersion="12C60" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" initialViewController="3">
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="1930"/>
</dependencies>
<scenes>
<!--Navigation Controller-->
<scene sceneID="11">
<objects>
<navigationController id="3" sceneMemberID="viewController">
<navigationBar key="navigationBar" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="scaleToFill" id="4">
<autoresizingMask key="autoresizingMask"/>
</navigationBar>
<connections>
<segue destination="12" kind="relationship" relationship="rootViewController" id="19"/>
</connections>
</navigationController>
<placeholder placeholderIdentifier="IBFirstResponder" id="10" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="-1" y="64"/>
</scene>
<!--Master View Controller - Master-->
<scene sceneID="18">
<objects>
<tableViewController storyboardIdentifier="" title="Master" id="12" customClass="MasterViewController" sceneMemberID="viewController">
<tableView key="view" opaque="NO" clipsSubviews="YES" clearsContextBeforeDrawing="NO" contentMode="scaleToFill" alwaysBounceVertical="YES" dataMode="prototypes" style="plain" rowHeight="44" sectionHeaderHeight="22" sectionFooterHeight="22" id="13">
<rect key="frame" x="0.0" y="64" width="320" height="416"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
<prototypes>
<tableViewCell contentMode="scaleToFill" selectionStyle="blue" accessoryType="disclosureIndicator" hidesAccessoryWhenEditing="NO" indentationLevel="1" indentationWidth="0.0" reuseIdentifier="ItemCell" textLabel="soZ-1r-uBe" detailTextLabel="LdV-IG-mw5" style="IBUITableViewCellStyleSubtitle" id="8aw-gn-zx0">
<rect key="frame" x="0.0" y="22" width="320" height="44"/>
<autoresizingMask key="autoresizingMask"/>
<view key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center">
<rect key="frame" x="0.0" y="0.0" width="300" height="43"/>
<autoresizingMask key="autoresizingMask"/>
<subviews>
<label opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" text="Title" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" id="soZ-1r-uBe">
<rect key="frame" x="10" y="2" width="38" height="22"/>
<autoresizingMask key="autoresizingMask"/>
<fontDescription key="fontDescription" type="boldSystem" pointSize="18"/>
<color key="textColor" cocoaTouchSystemColor="darkTextColor"/>
<color key="highlightedColor" red="1" green="1" blue="1" alpha="1" colorSpace="calibratedRGB"/>
</label>
<label opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" text="Subtitle" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" id="LdV-IG-mw5">
<rect key="frame" x="10" y="24" width="47" height="18"/>
<autoresizingMask key="autoresizingMask"/>
<fontDescription key="fontDescription" type="system" pointSize="14"/>
<color key="textColor" red="0.50196078431372548" green="0.50196078431372548" blue="0.50196078431372548" alpha="1" colorSpace="calibratedRGB"/>
<color key="highlightedColor" red="1" green="1" blue="1" alpha="1" colorSpace="calibratedRGB"/>
</label>
</subviews>
<color key="backgroundColor" white="0.0" alpha="0.0" colorSpace="calibratedWhite"/>
</view>
<color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
</tableViewCell>
</prototypes>
<sections/>
<connections>
<outlet property="dataSource" destination="12" id="16"/>
<outlet property="delegate" destination="12" id="15"/>
</connections>
</tableView>
<navigationItem key="navigationItem" title="Inventory" id="35">
<barButtonItem key="rightBarButtonItem" title="Refresh" id="kbX-wS-g6y">
<connections>
<action selector="refreshItems:" destination="12" id="i5P-Jj-KLF"/>
</connections>
</barButtonItem>
</navigationItem>
</tableViewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="17" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="455" y="64"/>
</scene>
</scenes>
<classes>
<class className="MasterViewController" superclassName="UITableViewController">
<source key="sourceIdentifier" type="project" relativePath="./Classes/MasterViewController.h"/>
<relationships>
<relationship kind="action" name="refreshItems:"/>
</relationships>
</class>
</classes>
<simulatedMetricsContainer key="defaultSimulatedMetrics">
<simulatedStatusBarMetrics key="statusBar"/>
<simulatedOrientationMetrics key="orientation"/>
<simulatedScreenMetrics key="destination"/>
</simulatedMetricsContainer>
</document>
================================================
FILE: ContentService/Inventory-JSON-API-iOS/Inventory-iOS/Inventory/main.m
================================================
#import <UIKit/UIKit.h>
#import "AppDelegate.h"
int main(int argc, char *argv[])
{
@autoreleasepool {
return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
}
}
================================================
FILE: ContentService/Inventory-JSON-API-iOS/Inventory-iOS/Inventory.xcodeproj/project.pbxproj
================================================
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 46;
objects = {
/* Begin PBXBuildFile section */
69BB74F716B2D0C500EC6AF4 /* Default-568h@2x.png in Resources */ = {isa = PBXBuildFile; fileRef = 69BB74F616B2D0C500EC6AF4 /* Default-568h@2x.png */; };
6F4DFB9E14BA2B2200B110D2 /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6F4DFB9D14BA2B2200B110D2 /* UIKit.framework */; };
6F4DFBA014BA2B2200B110D2 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6F4DFB9F14BA2B2200B110D2 /* Foundation.framework */; };
6F4DFBA214BA2B2200B110D2 /* CoreGraphics.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6F4DFBA114BA2B2200B110D2 /* CoreGraphics.framework */; };
6F4DFBA814BA2B2200B110D2 /* InfoPlist.strings in Resources */ = {isa = PBXBuildFile; fileRef = 6F4DFBA614BA2B2200B110D2 /* InfoPlist.strings */; };
6F4DFBAA14BA2B2200B110D2 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 6F4DFBA914BA2B2200B110D2 /* main.m */; };
6F4DFBAE14BA2B2200B110D2 /* AppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 6F4DFBAD14BA2B2200B110D2 /* AppDelegate.m */; };
6F4DFBB114BA2B2200B110D2 /* MainStoryboard.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 6F4DFBAF14BA2B2200B110D2 /* MainStoryboard.storyboard */; };
6F4DFBB414BA2B2200B110D2 /* MasterViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 6F4DFBB314BA2B2200B110D2 /* MasterViewController.m */; };
/* End PBXBuildFile section */
/* Begin PBXFileReference section */
69BB74F616B2D0C500EC6AF4 /* Default-568h@2x.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "Default-568h@2x.png"; sourceTree = "<group>"; };
6F4DFB9914BA2B2200B110D2 /* Inventory.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Inventory.app; sourceTree = BUILT_PRODUCTS_DIR; };
6F4DFB9D14BA2B2200B110D2 /* UIKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UIKit.framework; path = System/Library/Frameworks/UIKit.framework; sourceTree = SDKROOT; };
6F4DFB9F14BA2B2200B110D2 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = System/Library/Frameworks/Foundation.framework; sourceTree = SDKROOT; };
6F4DFBA114BA2B2200B110D2 /* CoreGraphics.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreGraphics.framework; path = System/Library/Frameworks/CoreGraphics.framework; sourceTree = SDKROOT; };
6F4DFBA514BA2B2200B110D2 /* Inventory-Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = "Inventory-Info.plist"; sourceTree = "<group>"; };
6F4DFBA714BA2B2200B110D2 /* en */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = en; path = en.lproj/InfoPlist.strings; sourceTree = "<group>"; };
6F4DFBA914BA2B2200B110D2 /* main.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = "<group>"; };
6F4DFBAB14BA2B2200B110D2 /* Inventory-Prefix.pch */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Inventory-Prefix.pch"; sourceTree = "<group>"; };
6F4DFBAC14BA2B2200B110D2 /* AppDelegate.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = AppDelegate.h; sourceTree = "<group>"; };
6F4DFBAD14BA2B2200B110D2 /* AppDelegate.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AppDelegate.m; sourceTree = "<group>"; };
6F4DFBB014BA2B2200B110D2 /* en */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = en; path = en.lproj/MainStoryboard.storyboard; sourceTree = "<group>"; };
6F4DFBB214BA2B2200B110D2 /* MasterViewController.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MasterViewController.h; sourceTree = "<group>"; };
6F4DFBB314BA2B2200B110D2 /* MasterViewController.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = MasterViewController.m; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
6F4DFB9614BA2B2200B110D2 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
6F4DFB9E14BA2B2200B110D2 /* UIKit.framework in Frameworks */,
6F4DFBA014BA2B2200B110D2 /* Foundation.framework in Frameworks */,
6F4DFBA214BA2B2200B110D2 /* CoreGraphics.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
6F4DFB8E14BA2B2200B110D2 = {
isa = PBXGroup;
children = (
69BB74F616B2D0C500EC6AF4 /* Default-568h@2x.png */,
6F4DFBA314BA2B2200B110D2 /* InventorySample */,
6F4DFB9C14BA2B2200B110D2 /* Frameworks */,
6F4DFB9A14BA2B2200B110D2 /* Products */,
);
sourceTree = "<group>";
};
6F4DFB9A14BA2B2200B110D2 /* Products */ = {
isa = PBXGroup;
children = (
6F4DFB9914BA2B2200B110D2 /* Inventory.app */,
);
name = Products;
sourceTree = "<group>";
};
6F4DFB9C14BA2B2200B110D2 /* Frameworks */ = {
isa = PBXGroup;
children = (
6F4DFB9D14BA2B2200B110D2 /* UIKit.framework */,
6F4DFB9F14BA2B2200B110D2 /* Foundation.framework */,
6F4DFBA114BA2B2200B110D2 /* CoreGraphics.framework */,
);
name = Frameworks;
sourceTree = "<group>";
};
6F4DFBA314BA2B2200B110D2 /* InventorySample */ = {
isa = PBXGroup;
children = (
6F4DFBAC14BA2B2200B110D2 /* AppDelegate.h */,
6F4DFBAD14BA2B2200B110D2 /* AppDelegate.m */,
6F4DFBAF14BA2B2200B110D2 /* MainStoryboard.storyboard */,
6F4DFBB214BA2B2200B110D2 /* MasterViewController.h */,
6F4DFBB314BA2B2200B110D2 /* MasterViewController.m */,
6F4DFBA414BA2B2200B110D2 /* Supporting Files */,
);
name = InventorySample;
path = Inventory;
sourceTree = "<group>";
};
6F4DFBA414BA2B2200B110D2 /* Supporting Files */ = {
isa = PBXGroup;
children = (
6F4DFBA514BA2B2200B110D2 /* Inventory-Info.plist */,
6F4DFBA614BA2B2200B110D2 /* InfoPlist.strings */,
6F4DFBA914BA2B2200B110D2 /* main.m */,
6F4DFBAB14BA2B2200B110D2 /* Inventory-Prefix.pch */,
);
name = "Supporting Files";
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
6F4DFB9814BA2B2200B110D2 /* Inventory */ = {
isa = PBXNativeTarget;
buildConfigurationList = 6F4DFBBA14BA2B2200B110D2 /* Build configuration list for PBXNativeTarget "Inventory" */;
buildPhases = (
6F4DFB9514BA2B2200B110D2 /* Sources */,
6F4DFB9614BA2B2200B110D2 /* Frameworks */,
6F4DFB9714BA2B2200B110D2 /* Resources */,
);
buildRules = (
);
dependencies = (
);
name = Inventory;
productName = "Twitter Test";
productReference = 6F4DFB9914BA2B2200B110D2 /* Inventory.app */;
productType = "com.apple.product-type.application";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
6F4DFB9014BA2B2200B110D2 /* Project object */ = {
isa = PBXProject;
attributes = {
LastUpgradeCheck = 0420;
};
buildConfigurationList = 6F4DFB9314BA2B2200B110D2 /* Build configuration list for PBXProject "Inventory" */;
compatibilityVersion = "Xcode 3.2";
developmentRegion = English;
hasScannedForEncodings = 0;
knownRegions = (
en,
);
mainGroup = 6F4DFB8E14BA2B2200B110D2;
productRefGroup = 6F4DFB9A14BA2B2200B110D2 /* Products */;
projectDirPath = "";
projectRoot = "";
targets = (
6F4DFB9814BA2B2200B110D2 /* Inventory */,
);
};
/* End PBXProject section */
/* Begin PBXResourcesBuildPhase section */
6F4DFB9714BA2B2200B110D2 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
6F4DFBA814BA2B2200B110D2 /* InfoPlist.strings in Resources */,
6F4DFBB114BA2B2200B110D2 /* MainStoryboard.storyboard in Resources */,
69BB74F716B2D0C500EC6AF4 /* Default-568h@2x.png in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
6F4DFB9514BA2B2200B110D2 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
6F4DFBAA14BA2B2200B110D2 /* main.m in Sources */,
6F4DFBAE14BA2B2200B110D2 /* AppDelegate.m in Sources */,
6F4DFBB414BA2B2200B110D2 /* MasterViewController.m in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin PBXVariantGroup section */
6F4DFBA614BA2B2200B110D2 /* InfoPlist.strings */ = {
isa = PBXVariantGroup;
children = (
6F4DFBA714BA2B2200B110D2 /* en */,
);
name = InfoPlist.strings;
sourceTree = "<group>";
};
6F4DFBAF14BA2B2200B110D2 /* MainStoryboard.storyboard */ = {
isa = PBXVariantGroup;
children = (
6F4DFBB014BA2B2200B110D2 /* en */,
);
name = MainStoryboard.storyboard;
sourceTree = "<group>";
};
/* End PBXVariantGroup section */
/* Begin XCBuildConfiguration section */
6F4DFBB814BA2B2200B110D2 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
ARCHS = "$(ARCHS_STANDARD_32_BIT)";
CLANG_ENABLE_OBJC_ARC = YES;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
COPY_PHASE_STRIP = NO;
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_DYNAMIC_NO_PIC = NO;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
"$(inherited)",
);
GCC_SYMBOLS_PRIVATE_EXTERN = NO;
GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
GCC_WARN_ABOUT_MISSING_PROTOTYPES = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 5.0;
SDKROOT = iphoneos;
};
name = Debug;
};
6F4DFBB914BA2B2200B110D2 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
ARCHS = "$(ARCHS_STANDARD_32_BIT)";
CLANG_ENABLE_OBJC_ARC = YES;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
COPY_PHASE_STRIP = YES;
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
GCC_WARN_ABOUT_MISSING_PROTOTYPES = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 5.0;
OTHER_CFLAGS = "-DNS_BLOCK_ASSERTIONS=1";
SDKROOT = iphoneos;
VALIDATE_PRODUCT = YES;
};
name = Release;
};
6F4DFBBB14BA2B2200B110D2 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
GCC_PRECOMPILE_PREFIX_HEADER = YES;
GCC_PREFIX_HEADER = "Inventory/Inventory-Prefix.pch";
INFOPLIST_FILE = "$(SRCROOT)/Inventory/Inventory-Info.plist";
PRODUCT_NAME = Inventory;
WRAPPER_EXTENSION = app;
};
name = Debug;
};
6F4DFBBC14BA2B2200B110D2 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
GCC_PRECOMPILE_PREFIX_HEADER = YES;
GCC_PREFIX_HEADER = "Inventory/Inventory-Prefix.pch";
INFOPLIST_FILE = "$(SRCROOT)/Inventory/Inventory-Info.plist";
PRODUCT_NAME = Inventory;
WRAPPER_EXTENSION = app;
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
6F4DFB9314BA2B2200B110D2 /* Build configuration list for PBXProject "Inventory" */ = {
isa = XCConfigurationList;
buildConfigurations = (
6F4DFBB814BA2B2200B110D2 /* Debug */,
6F4DFBB914BA2B2200B110D2 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
6F4DFBBA14BA2B2200B110D2 /* Build configuration list for PBXNativeTarget "Inventory" */ = {
isa = XCConfigurationList;
buildConfigurations = (
6F4DFBBB14BA2B2200B110D2 /* Debug */,
6F4DFBBC14BA2B2200B110D2 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
};
rootObject = 6F4DFB9014BA2B2200B110D2 /* Project object */;
}
================================================
FILE: ContentService/Inventory-JSON-API-iOS/Inventory-iOS/Inventory.xcodeproj/project.xcworkspace/contents.xcworkspacedata
================================================
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "self:Inventory.xcodeproj">
</FileRef>
</Workspace>
================================================
FILE: ContentService/Inventory-JSON-API-iOS/Inventory-iOS/Inventory.xcodeproj/project.xcworkspace/xcuserdata/anagarajan.xcuserdatad/WorkspaceSettings.xcsettings
================================================
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>HasAskedToTakeAutomaticSnapshotBeforeSignificantChanges</key>
<true/>
<key>SnapshotAutomaticallyBeforeSignificantChanges</key>
<true/>
</dict>
</plist>
================================================
FILE: ContentService/Inventory-JSON-API-iOS/Inventory-iOS/Inventory.xcodeproj/xcuserdata/anagarajan.xcuserdatad/xcdebugger/Breakpoints.xcbkptlist
================================================
<?xml version="1.0" encoding="UTF-8"?>
<Bucket
type = "1"
version = "1.0">
</Bucket>
================================================
FILE: ContentService/Inventory-JSON-API-iOS/Inventory-iOS/Inventory.xcodeproj/xcuserdata/anagarajan.xcuserdatad/xcschemes/InventorySample.xcscheme
================================================
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0450"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "6F4DFB9814BA2B2200B110D2"
BuildableName = "Inventory.app"
BlueprintName = "Inventory"
ReferencedContainer = "container:Inventory.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"
buildConfiguration = "Debug">
<Testables>
</Testables>
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "6F4DFB9814BA2B2200B110D2"
BuildableName = "Inventory.app"
BlueprintName = "Inventory"
ReferencedContainer = "container:Inventory.xcodeproj">
</BuildableReference>
</MacroExpansion>
</TestAction>
<LaunchAction
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
buildConfiguration = "Debug"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
allowLocationSimulation = "YES">
<BuildableProductRunnable>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "6F4DFB9814BA2B2200B110D2"
BuildableName = "Inventory.app"
BlueprintName = "Inventory"
ReferencedContainer = "container:Inventory.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
buildConfiguration = "Release"
debugDocumentVersioning = "YES">
<BuildableProductRunnable>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "6F4DFB9814BA2B2200B110D2"
BuildableName = "Inventory.app"
BlueprintName = "Inventory"
ReferencedContainer = "container:Inventory.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
================================================
FILE: ContentService/Inventory-JSON-API-iOS/Inventory-iOS/Inventory.xcodeproj/xcuserdata/anagarajan.xcuserdatad/xcschemes/xcschememanagement.plist
================================================
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>SchemeUserState</key>
<dict>
<key>InventorySample.xcscheme</key>
<dict>
<key>orderHint</key>
<integer>0</integer>
</dict>
</dict>
<key>SuppressBuildableAutocreation</key>
<dict>
<key>6F4DFB9814BA2B2200B110D2</key>
<dict>
<key>primary</key>
<true/>
</dict>
</dict>
</dict>
</plist>
================================================
FILE: ContentService/Inventory-JSON-API-iOS/code.gs
================================================
function doGet() {
var ss = SpreadsheetApp.openById('0AiFUpEyZ-UKzdElxM3NpbFI4QUJwdmxqSXVlSjJmNmc');
var sheet = ss.getSheets()[0];
// Get the range of cells that store employee data.
var employeeDataRange = ss.getRangeByName("inventoryData");
// For every row of employee data, generate an employee object.
var employeeObjects = getRowsData(sheet, employeeDataRange);
return ContentService.createTextOutput(JSON.stringify(employeeObjects)).setMimeType(ContentService.MimeType.JSON);
}
// getRowsData iterates row by row in the input range and returns an array of objects.
// Each object contains all the data for a given row, indexed by its normalized column name.
// Arguments:
// - sheet: the sheet object that contains the data to be processed
// - range: the exact range of cells where the data is stored
// - columnHeadersRowIndex: specifies the row number where the column names are stored.
// This argument is optional and it defaults to the row immediately above range;
// Returns an Array of objects.
function getRowsData(sheet, range, columnHeadersRowIndex) {
columnHeadersRowIndex = columnHeadersRowIndex || range.getRowIndex() - 1;
var numColumns = range.getLastColumn() - range.getColumn() + 1;
var headersRange = sheet.getRange(columnHeadersRowIndex, range.getColumn(), 1, numColumns);
var headers = headersRange.getValues()[0];
return getObjects(range.getValues(), normalizeHeaders(headers));
}
// For every row of data in data, generates an object that contains the data. Names of
// object fields are defined in keys.
// Arguments:
// - data: JavaScript 2d array
// - keys: Array of Strings that define the property names for the objects to create
function getObjects(data, keys) {
var objects = [];
for (var i = 0; i < data.length; ++i) {
var object = {};
var hasData = false;
for (var j = 0; j < data[i].length; ++j) {
var cellData = data[i][j];
if (isCellEmpty(cellData)) {
continue;
}
object[keys[j]] = cellData;
hasData = true;
}
if (hasData) {
objects.push(object);
}
}
return objects;
}
// Returns an Array of normalized Strings.
// Arguments:
// - headers: Array of Strings to normalize
function normalizeHeaders(headers) {
var keys = [];
for (var i = 0; i < headers.length; ++i) {
var key = normalizeHeader(headers[i]);
if (key.length > 0) {
keys.push(key);
}
}
return keys;
}
// Normalizes a string, by removing all alphanumeric characters and using mixed case
// to separate words. The output will always start with a lower case letter.
// This function is designed to produce JavaScript object property names.
// Arguments:
// - header: string to normalize
// Examples:
// "First Name" -> "firstName"
// "Market Cap (millions) -> "marketCapMillions
// "1 number at the beginning is ignored" -> "numberAtTheBeginningIsIgnored"
function normalizeHeader(header) {
var key = "";
var upperCase = false;
for (var i = 0; i < header.length; ++i) {
var letter = header[i];
if (letter == " " && key.length > 0) {
upperCase = true;
continue;
}
if (!isAlnum(letter)) {
continue;
}
if (key.length == 0 && isDigit(letter)) {
continue; // first character must be a letter
}
if (upperCase) {
upperCase = false;
key += letter.toUpperCase();
} else {
key += letter.toLowerCase();
}
}
return key;
}
// Returns true if the cell where cellData was read from is empty.
// Arguments:
// - cellData: string
function isCellEmpty(cellData) {
return typeof(cellData) == "string" && cellData == "";
}
// Returns true if the character char is alphabetical, false otherwise.
function isAlnum(char) {
return char >= 'A' && char <= 'Z' ||
char >= 'a' && char <= 'z' ||
isDigit(char);
}
// Returns true if the character char is a digit, false otherwise.
function isDigit(char) {
return char >= '0' && char <= '9';
}
// Given a JavaScript 2d Array, this function returns the transposed table.
// Arguments:
// - data: JavaScript 2d Array
// Returns a JavaScript 2d Array
// Example: arrayTranspose([[1,2,3],[4,5,6]]) returns [[1,4],[2,5],[3,6]].
function arrayTranspose(data) {
if (data.length == 0 || data[0].length == 0) {
return null;
}
var ret = [];
for (var i = 0; i < data[0].length; ++i) {
ret.push([]);
}
for (var i = 0; i < data.length; ++i) {
for (var j = 0; j < data[i].length; ++j) {
ret[j][i] = data[i][j];
}
}
return ret;
}
// Exercise:
function runExercise() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[1];
// Get the range of cells that store employee data.
var employeeDataRange = sheet.getRange("B1:F5");
// For every row of employee data, generate an employee object.
var employeeObjects = getColumnsData(sheet, employeeDataRange);
var thirdEmployee = employeeObjects[2];
var stringToDisplay = "The third column is: " + thirdEmployee.firstName + " " + thirdEmployee.lastName;
stringToDisplay += " (id #" + thirdEmployee.employeeId + ") working in the ";
stringToDisplay += thirdEmployee.department + " department and with phone number ";
stringToDisplay += thirdEmployee.phoneNumber;
ss.msgBox(stringToDisplay);
}
// Given a JavaScript 2d Array, this function returns the transposed table.
// Arguments:
// - data: JavaScript 2d Array
// Returns a JavaScript 2d Array
// Example: arrayTranspose([[1,2,3],[4,5,6]]) returns [[1,4],[2,5],[3,6]].
function arrayTranspose(data) {
if (data.length == 0 || data[0].length == 0) {
return null;
}
var ret = [];
for (var i = 0; i < data[0].length; ++i) {
ret.push([]);
}
for (var i = 0; i < data.length; ++i) {
for (var j = 0; j < data[i].length; ++j) {
ret[j][i] = data[i][j];
}
}
return ret;
}
// getColumnsData iterates column by column in the input range and returns an array of objects.
// Each object contains all the data for a given column, indexed by its normalized row name.
// Arguments:
// - sheet: the sheet object that contains the data to be processed
// - range: the exact range of cells where the data is stored
// - rowHeadersColumnIndex: specifies the column number where the row names are stored.
// This argument is optional and it defaults to the column immediately left of the range;
// Returns an Array of objects.
function getColumnsData(sheet, range, rowHeadersColumnIndex) {
rowHeadersColumnIndex = rowHeadersColumnIndex || range.getColumnIndex() - 1;
var headersTmp = sheet.getRange(range.getRow(), rowHeadersColumnIndex, range.getNumRows(), 1).getValues();
var headers = normalizeHeaders(arrayTranspose(headersTmp)[0]);
return getObjects(arrayTranspose(range.getValues()), headers);
}
================================================
FILE: ContentService/Simple-JSONP/SimpleHtml-JSFiddle.html
================================================
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script>
$(document).ready(function () {
$.getJSON('https://script.google.com/macros/s/AKfycbzhzyGY5nCLdho3RBmWDLzDX6Rvdv6Uj4qpe83vTNnxICSILbfk/exec?prefix=?', null, function (results) {
$('h1').html(results);
});
});
</script>
</head>
<body>
<h1>welcome<h1>
</body>
</html>
================================================
FILE: ContentService/Simple-JSONP/code.gs
================================================
function doGet(request) {
var result = 'hello world';
var content = request.parameters.prefix + '(' +JSON.stringify(result) + ')';
return ContentService.createTextOutput(content)
.setMimeType(ContentService.MimeType.JSON);
}
================================================
FILE: ContentService/readme.md
================================================
Click the image below for video with more details -
[](http://www.youtube.com/watch?v=JRGzVdliQOQ&list=PL68F511F6E3C122EB)
================================================
FILE: DriveSDK/AppsScript.gs
================================================
//look for the first mtg right now in the user's calendar from now till next 2 hours
function createMeetingNotes() {
var lowerBound = new Date();
var upperBound = new Date();
upperBound.setHours(lowerBound.getHours()+2);
var appts = CalendarApp.getEvents(lowerBound, upperBound);
if(!appts || appts.length ==0){
Logger.log('No current appointments!');
return '';
}
//naive implementation for demo - ideally we'll provide a picker if double booked
var appt = appts[0];
var doc = DocumentApp.create('Meeting notes for ' + appt.getTitle());
doc.appendParagraph('Time: ' + appt.getStartTime());
doc.appendParagraph('Location: ' + appt.getLocation());
doc.appendParagraph('Attendees: ' + getEmails(appt));
doc.appendHorizontalRule();
doc.appendParagraph(appt.getDescription());
return doc.getUrl();
}
function getEmails(appt){
var guests = appt.getGuestList(true);
var emails = '';
for(var i=0;i<guests.length;i++){
emails += guests[i].getEmail() + ', ';
}
return emails.slice(0,-2);
}
function zipAndSend(fileIds,emailAddress){
var names = {};
var zipFile = Utilities.zip(fileIds.map(function(i){
var f = DocsList.getFileById(i);
Logger.log(f.getName());
var n = f.getName() + '.pdf';
while (names[n]) { n = '_' + n }
names[n] = true;
return f.getAs('application/pdf').setName(n);
}), 'FilesForYou.zip')
MailApp.sendEmail(emailAddress, 'Files you requested', 'Attached is the ZIP of the pdf documents we discussed', {attachments: [zipFile]});
}
================================================
FILE: DriveSDK/ChromeWebStoreVersion/SimpleZipAndSend.gs
================================================
//this is the source code for "Zip and send" app on the Chrome Web Store you can install into your Google Drive
function doGet(e) {
var state = JSON.parse(e.parameters.state);
zipAndSend(state.exportIds,Session.getEffectiveUser().getEmail());
return HtmlService.createHtmlOutput("<html><h1>Email sent. Check your inbox!</h1></html>");
}
function zipAndSend(fileIds,emailAddress){
var names = {};
var zipFile = Utilities.zip(fileIds.map(function(i){
var f = DocsList.getFileById(i);
Logger.log(f.getName());
var n = f.getName() + '.pdf';
while (names[n]) { n = '_' + n }
names[n] = true;
return f.getAs('application/pdf').setName(n);
}), 'FilesForYou.zip')
MailApp.sendEmail(emailAddress, 'Files you requested', 'Attached is the ZIP of the pdf documents we discussed', {attachments: [zipFile]});
}
================================================
FILE: DriveSDK/FlowManager.gs
================================================
var AUTHORIZE_URL = 'https://accounts.google.com/o/oauth2/auth';
var TOKEN_URL = 'https://accounts.google.com/o/oauth2/token';
var REDIRECT_URL= 'YOUR_REDIRECT_URL';//ScriptApp.getService().getUrl();
var tokenPropertyName = 'GOOGLE_OAUTH_TOKEN';
var CLIENT_ID = 'YOUR_CLIENT_ID';
var CLIENT_SECRET = 'YOUR_CLIENT_SECRET';
function doGet(e) {
var HTMLToOutput;
if(e.parameters.state){
var state = JSON.parse(e.parameters.state);
if(state.action === 'create'){
var meetingURL = createMeetingNotes();
HTMLToOutput = "<html><h1>Meeting notes document created!</h1><a href='"+meetingURL+"'>click here to open</a></html>";
}
else {
zipAndSend(state.exportIds,Session.getEffectiveUser().getEmail());
HTMLToOutput = "<html><h1>Email sent. Check your inbox!</h1></html>";
}
}
else if(e.parameters.code){//if we get "code" as a parameter in, then this is a callback. we can make this more explicit
getAndStoreAccessToken(e.parameters.code);
HTMLToOutput = '<html><h1>App is installed, you can close this window now or navigate to your <a href="https://drive.google.com">Google Drive</a>.</h1></html>';
}
else {//we are starting from scratch or resetting
HTMLToOutput = "<html><h1>Install this App into your Google Drive!</h1><a href='"+getURLForAuthorization()+"'>click here to start</a></html>";
}
return HtmlService.createHtmlOutput(HTMLToOutput);
}
function getURLForAuthorization(){
return AUTHORIZE_URL + '?response_type=code&client_id='+CLIENT_ID+'&redirect_uri='+REDIRECT_URL +
'&scope=https://www.googleapis.com/auth/drive.install https://www.googleapis.com/auth/userinfo.email';
}
function getAndStoreAccessToken(code){
var parameters = { method : 'post',
payload : 'client_id='+CLIENT_ID+'&client_secret='+CLIENT_SECRET+'&grant_type=authorization_code&redirect_uri='+REDIRECT_URL+'&code=' + code};
var response = UrlFetchApp.fetch(TOKEN_URL,parameters).getContentText();
var tokenResponse = JSON.parse(response);
UserProperties.setProperty(tokenPropertyName, tokenResponse.access_token);
}
function getUrlFetchOptions() {
return {'contentType' : 'application/json',
'headers' : {'Authorization' : 'Bearer ' + UserProperties.getProperty(tokenPropertyName),
'Accept' : 'application/json'}};
}
//naive check, not using for now, use refresh tokens and add proper checking
function isTokenValid() {
return UserProperties.getProperty(tokenPropertyName);
}
================================================
FILE: DriveSDK/readme.md
================================================
Click the image below for video with more details -
[](http://www.youtube.com/watch?v=R71oo-5NmPE&list=PL68F511F6E3C122EB)
================================================
FILE: FusionTables/RowUtilities.gs
================================================
// getRowsData iterates row by row in the input range and returns an array of objects.
// Each object contains all the data for a given row, indexed by its normalized column name.
// Arguments:
// - sheet: the sheet object that contains the data to be processed
// - range: the exact range of cells where the data is stored
// - columnHeadersRowIndex: specifies the row number where the column names are stored.
// This argument is optional and it defaults to the row immediately above range;
// Returns an Array of objects.
function getRowsData(sheet, range, columnHeadersRowIndex) {
columnHeadersRowIndex = columnHeadersRowIndex || range.getRowIndex() - 1;
var numColumns = range.getEndColumn() - range.getColumn() + 1;
var headersRange = sheet.getRange(columnHeadersRowIndex, range.getColumn(), 1, numColumns);
var headers = headersRange.getValues()[0];
return getObjects(range.getValues(), normalizeHeaders(headers));
}
// getColumnsData iterates column by column in the input range and returns an array of objects.
// Each object contains all the data for a given column, indexed by its normalized row name.
// Arguments:
// - sheet: the sheet object that contains the data to be processed
// - range: the exact range of cells where the data is stored
// - rowHeadersColumnIndex: specifies the column number where the row names are stored.
// This argument is optional and it defaults to the column immediately left of the range;
// Returns an Array of objects.
function getColumnsData(sheet, range, rowHeadersColumnIndex) {
rowHeadersColumnIndex = rowHeadersColumnIndex || range.getColumnIndex() - 1;
var headersTmp = sheet.getRange(range.getRow(), rowHeadersColumnIndex, range.getNumRows(), 1).getValues();
var headers = normalizeHeaders(arrayTranspose(headersTmp)[0]);
return getObjects(arrayTranspose(range.getValues()), headers);
}
// For every row of data in data, generates an object that contains the data. Names of
// object fields are defined in keys.
// Arguments:
// - data: JavaScript 2d array
// - keys: Array of Strings that define the property names for the objects to create
function getObjects(data, keys) {
var objects = [];
for (var i = 0; i < data.length; ++i) {
var object = {};
var hasData = false;
for (var j = 0; j < data[i].length; ++j) {
var cellData = data[i][j];
if (isCellEmpty(cellData)) {
continue;
}
object[keys[j]] = cellData;
hasData = true;
}
if (hasData) {
objects.push(object);
}
}
return objects;
}
// Returns an Array of normalized Strings.
// Arguments:
// - headers: Array of Strings to normalize
function normalizeHeaders(headers) {
var keys = [];
for (var i = 0; i < headers.length; ++i) {
var key = normalizeHeader(headers[i]);
if (key.length > 0) {
keys.push(key);
}
}
return keys;
}
// Normalizes a string, by removing all alphanumeric characters and using mixed case
// to separate words. The output will always start with a lower case letter.
// This function is designed to produce JavaScript object property names.
// Arguments:
// - header: string to normalize
// Examples:
// "First Name" -> "firstName"
// "Market Cap (millions) -> "marketCapMillions
// "1 number at the beginning is ignored" -> "numberAtTheBeginningIsIgnored"
function normalizeHeader(header) {
var key = "";
var upperCase = false;
for (var i = 0; i < header.length; ++i) {
var letter = header[i];
if (letter == " " && key.length > 0) {
upperCase = true;
continue;
}
if (!isAlnum(letter)) {
continue;
}
if (key.length == 0 && isDigit(letter)) {
continue; // first character must be a letter
}
if (upperCase) {
upperCase = false;
key += letter.toUpperCase();
} else {
key += letter.toLowerCase();
}
}
return key;
}
// Returns true if the cell where cellData was read from is empty.
// Arguments:
// - cellData: string
function isCellEmpty(cellData) {
return typeof(cellData) == "string" && cellData == "";
}
// Returns true if the character char is alphabetical, false otherwise.
function isAlnum(char) {
return char >= 'A' && char <= 'Z' ||
char >= 'a' && char <= 'z' ||
isDigit(char);
}
// Returns true if the character char is a digit, false otherwise.
function isDigit(char) {
return char >= '0' && char <= '9';
}
// Given a JavaScript 2d Array, this function returns the transposed table.
// Arguments:
// - data: JavaScript 2d Array
// Returns a JavaScript 2d Array
// Example: arrayTranspose([[1,2,3],[4,5,6]]) returns [[1,4],[2,5],[3,6]].
function arrayTranspose(data) {
if (data.length == 0 || data[0].length == 0) {
return null;
}
var ret = [];
for (var i = 0; i < data[0].length; ++i) {
ret.push([]);
}
for (var i = 0; i < data.length; ++i) {
for (var j = 0; j < data[i].length; ++j) {
ret[j][i] = data[i][j];
}
}
return ret;
}
================================================
FILE: FusionTables/SampleDataExchange.gs
================================================
function onInstall(){
onOpen();
}
var ss = SpreadsheetApp.getActiveSpreadsheet();
function onOpen() {
var menuEntries = [{name: "Login", functionName: "login"},
{name: "Download from Fusion Tables", functionName: "downloadFromFusionTables"},
{name: "Upload to Fusion Tables", functionName: "uploadToFusionTables"},
{name: "Reset credentials", functionName: "clearCreds"}];
ss.addMenu("Fusion Tables", menuEntries);
}
function login(){
if(isTokenValid()){
HTMLToOutput = '<html><h1>Already have token</h1></html>';
}
else {//we are starting from scratch or resetting
HTMLToOutput = "<html><h1>You need to login</h1><a href='"+getURLForAuthorization()+"'>click here to start</a><br>Re-open this window when you return.</html>";
}
ss.show(HtmlService.createHtmlOutput(HTMLToOutput));
}
function doGet(e) {
var HTMLToOutput;
if(e.parameters.code){//if we get "code" as a parameter in, then this is a callback. we can make this more explicit
getAndStoreAccessToken(e.parameters.code);
HTMLToOutput = '<html><h1>Finished with oAuth</h1>You can close this window.</html>';
}
return HtmlService.createHtmlOutput(HTMLToOutput);
}
var tableName = '1ETYzpkpTm4SfOMFTWHYgT9q1s4mSIE87yQCnQ04';
function downloadFromFusionTables(){
var schoolName = lookupSchoolName();
var dataResponse = runSQL("select ROWID,StudentID,Subject,Grade,School from "+tableName+" where School = '"+schoolName+"'");
var respObject = JSON.parse(dataResponse);
ss.appendRow(respObject.columns);
for(var i in respObject.rows){
ss.appendRow(respObject.rows[i]);
}
ss.getActiveSheet().clearNotes();
}
function runSQL(sql){
var getDataURL = 'https://www.googleapis.com/fusiontables/v1/query?sql='+sql;
var dataResponse = UrlFetchApp.fetch(getDataURL,getUrlFetchOptions()).getContentText();
return dataResponse;
}
var tempEditedProperty = 'CURRENT_EDITED';
//simple tracker to see what changed. need to add more validation logic and safety checks here.
function onEdit(e){
e.range.setComment("Edited at: " + new Date().toTimeString());
var rowid = ss.getActiveSheet().getRange(e.range.getRow(),1).getValue();
var currentEditedItems = UserProperties.getProperty(tempEditedProperty) || '';
currentEditedItems += rowid+',';
UserProperties.setProperty(tempEditedProperty,currentEditedItems);
}
function uploadToFusionTables() {
var currentEditedItems = UserProperties.getProperty(tempEditedProperty) || '';
var rowIdsEdited = currentEditedItems.split(',');
var rowObjects = getRowsData(ss.getActiveSheet(), ss.getDataRange(),1);
var runningLog = '';
for(var i = 1;i<rowObjects.length;i++){
if(rowIdsEdited.indexOf(String(rowObjects[i].rowid))>-1){
runningLog += 'updating rowid = ' + rowObjects[i].rowid + ' with grade of ' + rowObjects[i].grade + '. ';
runSQL("update "+tableName+" SET Grade = "+rowObjects[i].grade+" WHERE ROWID = '"+String(rowObjects[i].rowid)+"'");
}
}
UserProperties.deleteProperty(tempEditedProperty);
ss.getActiveSheet().clearNotes();
if(runningLog){
Browser.msgBox(runningLog);
}
}
var AUTHORIZE_URL = 'https://accounts.google.com/o/oauth2/auth'; //step 1. we can actually start directly here if that is necessary
var TOKEN_URL = 'https://accounts.google.com/o/oauth2/token'; //step 2. after we get the callback, go get token
//PUT YOUR OWN SETTINGS HERE
var CLIENT_ID = 'YOUR_CLIENT_ID';
var CLIENT_SECRET='YOUR_CLIENT_SECRET';
var REDIRECT_URL= 'YOUR_REDIRECT_URL';
var tokenPropertyName = 'FUSIONTABLES_OAUTH_TOKEN';
function getURLForAuthorization(){
return AUTHORIZE_URL + '?response_type=code&client_id='+CLIENT_ID+'&redirect_uri='+REDIRECT_URL +
'&scope=https://www.googleapis.com/auth/fusiontables&state=/profile';
}
function getAndStoreAccessToken(code){
var parameters = {
method : 'post',
payload : 'client_id='+CLIENT_ID+'&client_secret='+CLIENT_SECRET+'&grant_type=authorization_code&redirect_uri='+REDIRECT_URL+'&code=' + code
};
var response = UrlFetchApp.fetch(TOKEN_URL,parameters).getContentText();
var tokenResponse = JSON.parse(response);
//store the token for later retrival
UserProperties.setProperty(tokenPropertyName, tokenResponse.access_token);
}
function getUrlFetchOptions() {
var token = UserProperties.getProperty(tokenPropertyName);
return {
"method" : "post",
"contentType" : "application/json",
"headers" : {
"Authorization" : "Bearer " + token,
"Accept" : "application/json"
}
};
}
// we don't have a logout option here. for now, manually clear out the token under File->Project->User Properties
function isTokenValid() {
var token = UserProperties.getProperty(tokenPropertyName);
if(!token){ //if its empty or undefined
return false;
}
return true; //naive check
}
function clearCreds(){
UserProperties.deleteProperty(tokenPropertyName);
Browser.msgBox('Tokens cleared. Please login again from the menu before using Fusion tables');
}
var schoolName = {
"tom.principal@acmemiddleschool.edu":'Acme Middle School',
"arun.at.pyxis@gmail.com":'Short Hills Prep',
"arun.appsscript@gmail.com":'PK Middle School'
}
var user = Session.getEffectiveUser().getEmail();
function lookupSchoolName(){
return schoolName[user] || schoolName[0];
}
================================================
FILE: FusionTables/readme.md
================================================
Click the image below for video with more details -
[](http://www.youtube.com/watch?v=eHM0zbUE5A0&list=PL68F511F6E3C122EB)
================================================
FILE: GoogleAppsAdminAudit.gs
================================================
function doGet(e) {
var HTMLToOutput;
if(e.parameters.code){//if we get "code" as a parameter in, then this is a callback. we can make this more explicit
getAndStoreAccessToken(e.parameters.code);
HTMLToOutput = '<html><h1>Finished with oAuth</h1></html>';
}
else if(isTokenValid()){//if we already have a valid token, go off and start working with data
HTMLToOutput = '<html><h1>Already have token</h1></html>';
}
else {//we are starting from scratch or resetting
return HtmlService.createHtmlOutput("<html><h1>Lets start with oAuth</h1><a href='"+getURLForAuthorization()+"'>click here to start</a></html>");
}
HTMLToOutput += getData();
return HtmlService.createHtmlOutput(HTMLToOutput);
}
//see docs here - https://developers.google.com/google-apps/admin-audit/
function getData(){
var getCustomerIdUrl = 'https://apps-apis.google.com/a/feeds/customer/2.0/customerId?alt=json';
var getCustomeerIdData = UrlFetchApp.fetch(getCustomerIdUrl,getUrlFetchOptions()).getContentText();
var responseObject = JSON.parse(getCustomeerIdData);
//customerId is the 2nd item. make this more robust!
var customerId = responseObject.entry.apps$property[1].value;
//cpanel app ID is always the same.
var activityUrl = 'https://www.googleapis.com/apps/reporting/audit/v1/'+customerId+'/207535951991';
var dataResponse = UrlFetchApp.fetch(activityUrl,getUrlFetchOptions()).getContentText();
var dataObject = JSON.parse(dataResponse);
var ss = SpreadsheetApp.create('Audit Log');
for(var i = 0;i<dataObject.items.length;i++){
var row = [];
var item = dataObject.items[i];
if(item.actor){
row.push(item.actor.callerType);
row.push(item.actor.email);
}
for(var j=0;item.events&&j<item.events.length;j++){
row.push(item.events[j].eventType);
row.push(item.events[j].name);
}
if(item.id){
row.push(item.id.time);
}
row.push(item.ipAddress);
ss.appendRow(row);
}
SpreadsheetApp.flush();
return "<a href='"+ss.getUrl()+"'>Open Spreadsheet here</a>";
}
//hardcoded here for easily tweaking this. should move this to ScriptProperties or better parameterize them
var AUTHORIZE_URL = 'https://accounts.google.com/o/oauth2/auth'; //step 1. we can actually start directly here if that is necessary
var TOKEN_URL = 'https://accounts.google.com/o/oauth2/token'; //step 2. after we get the callback, go get token
var CLIENT_ID = 'YOUR_CLIENT_ID';
var CLIENT_SECRET = 'YOUR_CLIENT_SECRET';
var REDIRECT_URL= 'YOUR_DEPLOYED_URL';//safer than ScriptApp.getService().getUrl() for domain accounts
//this is the user propety where we'll store the token, make sure this is unique across all user properties across all scripts
var tokenPropertyName = 'GOOGLE_OAUTH_TOKEN';
var baseURLPropertyName = 'GOOGLE_INSTANCE_URL';
function getURLForAuthorization(){
return AUTHORIZE_URL + '?response_type=code&client_id='+CLIENT_ID+'&redirect_uri='+REDIRECT_URL +
'&scope=https://apps-apis.google.com/a/feeds/policies/ https://www.googleapis.com/auth/apps/reporting/audit.readonly&state=/profile';
}
//Google requires POST, salesforce and slc worked with GET
function getAndStoreAccessToken(code){
var parameters = {
method : 'post',
payload : 'client_id='+CLIENT_ID+'&client_secret='+CLIENT_SECRET+'&grant_type=authorization_code&redirect_uri='+REDIRECT_URL+'&code=' + code
};
var response = UrlFetchApp.fetch(TOKEN_URL,parameters).getContentText();
var tokenResponse = JSON.parse(response);
//store the token for later retrieval
UserProperties.setProperty(tokenPropertyName, tokenResponse.access_token);
}
function getUrlFetchOptions() {
var token = UserProperties.getProperty(tokenPropertyName);
return {"contentType" : "application/json",
"headers" : {"Authorization" : "Bearer " + token,
"Accept" : "application/json"}
};
}
//naive check, add checking freshness or refreshing oauth tokens. also needs logout
function isTokenValid() {
var token = UserProperties.getProperty(tokenPropertyName);
if(!token){ //if its empty or undefined
return false;
}
return true;
}
================================================
FILE: IO2013/Drive/Code.gs
================================================
function doGet(e) {
var HTMLToOutput;
if(e.parameter.state){
var state = JSON.parse(e.parameter.state);
if(state.action === 'create'){
var newFolder = DriveApp.createFolder('New Assignment');
var templateQuiz = DriveApp.getFileById(QUIZ_TEMPLATE);
var templateRoster = DriveApp.getFileById(ROSTER_TEMPLATE);
var newQuiz = templateQuiz.makeCopy('Quiz Questions');
newFolder.addFile(newQuiz);
DriveApp.getRootFolder().removeFile(newQuiz);
var newRoster = templateRoster.makeCopy('Roster');
newFolder.addFile(newRoster);
DriveApp.getRootFolder().removeFile(newRoster);
var objectToSaveForClose = { type: 'close',
rosterID : newRoster.getId()}
var objectToSaveForPublish = { type: 'publish',
assignmentFolderID : newFolder.getId(),
rosterID : newRoster.getId(),
quizID : newQuiz.getId()}
var closeBlob = Utilities.newBlob(JSON.stringify(objectToSaveForClose), 'application/drive-assignment-creator', 'Close Quiz');
var publishBlob = Utilities.newBlob(JSON.stringify(objectToSaveForPublish), 'application/drive-assignment-creator', 'Publish Quiz');
newFolder.createFile(closeBlob);
newFolder.createFile(publishBlob);
HTMLToOutput = 'Assignment folder created with necessary template. Please update the Roster, fill in the quiz questions and click on the Publish icon in the folder. ';
} else {
var fileID = state.ids[0];
var content = DriveApp.getFileById(fileID).getBlob().getDataAsString();
var contentObject = JSON.parse(content);
var ssID = contentObject.rosterID;
var ss = SpreadsheetApp.openById(ssID);
var sheet = ss.getSheets()[0];
var rosterRange = ss.getRangeByName('RosterRange');
var rosterObjects = getRowsData(sheet, rosterRange);
if(contentObject.type === 'close'){
for(var i in rosterObjects){
var rosterItem = rosterObjects[i];
var quickCopy = DriveApp.getFileById(rosterItem.fileid);
quickCopy.removeEditor(rosterItem.studentEmailAddress);
quickCopy.addViewer(rosterItem.studentEmailAddress);
}
HTMLToOutput = 'Quiz is now closed. Your students will no longer be able to save any changes. They wil be able to view your notes on their quizes. ';
}else if(contentObject.type === 'publish'){
var quizFileID = contentObject.quizID;
var quiz = DriveApp.getFileById(quizFileID);
var folderID = contentObject.assignmentFolderID;
var folder = DriveApp.getFolderById(folderID);
for(var i in rosterObjects){
var rosterItem = rosterObjects[i];
var quizCopy = quiz.makeCopy('Quiz - ' + rosterItem.studentName);
folder.addFile(quizCopy);
DriveApp.getRootFolder().removeFile(quizCopy);
quizCopy.addEditor(rosterItem.studentEmailAddress);
rosterItem.fileid = quizCopy.getId();
}
setRowsData(sheet,rosterObjects);
HTMLToOutput = 'Completed publishing your quizes. Your students should be able to see the files in their "Shared with me" view.';
}
}
}
else if(e.parameter.code){//if we get "code" as a parameter in, then this is a callback. we can make this more explicit
getAndStoreAccessToken(e.parameter.code);
HTMLToOutput = 'App is installed, you can close this window now or open up Google Drive.';
}
else {//we are starting from scratch or resetting
}
var t = HtmlService.createTemplateFromFile('ui')
t.message = HTMLToOutput;
return t.evaluate().setSandboxMode(HtmlService.SandboxMode.NATIVE)
}
function getURLForAuthorization(){
return AUTHORIZE_URL + '?response_type=code&client_id='+CLIENT_ID+'&redirect_uri='+REDIRECT_URL +'&scope=https://www.googleapis.com/auth/drive.install';
}
function getAndStoreAccessToken(code){
var parameters = { method : 'post',
payload : 'client_id='+CLIENT_ID+'&client_secret='+CLIENT_SECRET+'&grant_type=authorization_code&redirect_uri='+REDIRECT_URL+'&code=' + code};
//no need to do anything with the token going forward.
var response = UrlFetchApp.fetch(TOKEN_URL,parameters).getContentText();
}
//replace with any template files you want -
var ROSTER_TEMPLATE = '0AkJNj_IM2wiPdEZzbFUxMjQteGtQS1JadHg5VmFMdGc';
var QUIZ_TEMPLATE = '1_LIZp1lahFhNouXsZNI1s6UluBskt_LOwQGlJIj2ftY';
var AUTHORIZE_URL = 'https://accounts.google.com/o/oauth2/auth';
var TOKEN_URL = 'https://accounts.google.com/o/oauth2/token';
//put your URL below or use ScriptApp.getService().getUrl();
var REDIRECT_URL= 'https://script.google.com/macros/s/AKfycbxK6aULLp8CL47aiUM_tHZCX9-2YNOK0yrp-ujnUQV8CrUQkUGk/exec';
var CLIENT_ID = ScriptProperties.getProperty('CLIENT_ID')
var CLIENT_SECRET = ScriptProperties.getProperty('CLIENT_SECRET');
================================================
FILE: IO2013/Drive/README.md
================================================
Companion code for Google IO 2013 session - Integrate Google Drive with Google Apps Script
https://developers.google.com/events/io/sessions/325412094
For setup -
You'll need to create OAuth 2 client ID/secret at http://developers.google.com/console and store it in the right ScriptProperties.
================================================
FILE: IO2013/Drive/SpreadsheetUtils.gs
================================================
//https://developers.google.com/apps-script/storing_data_spreadsheets#reading
// getRowsData iterates row by row in the input range and returns an array of objects.
// Each object contains all the data for a given row, indexed by its normalized column name.
// Arguments:
// - sheet: the sheet object that contains the data to be processed
// - range: the exact range of cells where the data is stored
// - columnHeadersRowIndex: specifies the row number where the column names are stored.
// This argument is optional and it defaults to the row immediately above range;
// Returns an Array of objects.
function getRowsData(sheet, range, columnHeadersRowIndex) {
columnHeadersRowIndex = columnHeadersRowIndex || range.getRowIndex() - 1;
var numColumns = range.getLastColumn() - range.getColumn() + 1;
var headersRange = sheet.getRange(columnHeadersRowIndex, range.getColumn(), 1, numColumns);
var headers = headersRange.getValues()[0];
return getObjects(range.getValues(), normalizeHeaders(headers));
}
// setRowsData fills in one row of data per object defined in the objects Array.
// For every Column, it checks if data objects define a value for it.
// Arguments:
// - sheet: the Sheet Object where the data will be written
// - objects: an Array of Objects, each of which contains data for a row
// - optHeadersRange: a Range of cells where the column headers are defined. This
// defaults to the entire first row in sheet.
// - optFirstDataRowIndex: index of the first row where data should be written. This
// defaults to the row immediately below the headers.
function setRowsData(sheet, objects, optHeadersRange, optFirstDataRowIndex) {
var headersRange = optHeadersRange || sheet.getRange(1, 1, 1, sheet.getMaxColumns());
var firstDataRowIndex = optFirstDataRowIndex || headersRange.getRowIndex() + 1;
var headers = normalizeHeaders(headersRange.getValues()[0]);
var data = [];
for (var i = 0; i < objects.length; ++i) {
var values = []
for (j = 0; j < headers.length; ++j) {
var header = headers[j];
// If the header is non-empty and the object value is 0...
if ((header.length > 0) && (objects[i][header] == 0)) {
values.push(0);
}
// If the header is empty or the object value is empty...
else if ((!(header.length > 0)) || (objects[i][header]=='')) {
values.push('');
}
else {
values.push(objects[i][header]);
}
}
data.push(values);
}
var destinationRange = sheet.getRange(firstDataRowIndex, headersRange.getColumnIndex(),
objects.length, headers.length);
destinationRange.setValues(data);
}
// getColumnsData iterates column by column in the input range and returns an array of objects.
// Each object contains all the data for a given column, indexed by its normalized row name.
// Arguments:
// - sheet: the sheet object that contains the data to be processed
// - range: the exact range of cells where the data is stored
// - rowHeadersColumnIndex: specifies the column number where the row names are stored.
// This argument is optional and it defaults to the column immediately left of the range;
// Returns an Array of objects.
function getColumnsData(sheet, range, rowHeadersColumnIndex) {
rowHeadersColumnIndex = rowHeadersColumnIndex || range.getColumnIndex() - 1;
var headersTmp = sheet.getRange(range.getRow(), rowHeadersColumnIndex, range.getNumRows(), 1).getValues();
var headers = normalizeHeaders(arrayTranspose(headersTmp)[0]);
return getObjects(arrayTranspose(range.getValues()), headers);
}
// For every row of data in data, generates an object that contains the data. Names of
// object fields are defined in keys.
// Arguments:
// - data: JavaScript 2d array
// - keys: Array of Strings that define the property names for the objects to create
function getObjects(data, keys) {
var objects = [];
for (var i = 0; i < data.length; ++i) {
var object = {};
var hasData = false;
for (var j = 0; j < data[i].length; ++j) {
var cellData = data[i][j];
if (isCellEmpty(cellData)) {
continue;
}
object[keys[j]] = cellData;
hasData = true;
}
if (hasData) {
objects.push(object);
}
}
return objects;
}
// Returns an Array of normalized Strings.
// Arguments:
// - headers: Array of Strings to normalize
function normalizeHeaders(headers) {
var keys = [];
for (var i = 0; i < headers.length; ++i) {
var key = normalizeHeader(headers[i]);
if (key.length > 0) {
keys.push(key);
}
}
return keys;
}
// Normalizes a string, by removing all alphanumeric characters and using mixed case
// to separate words. The output will always start with a lower case letter.
// This function is designed to produce JavaScript object property names.
// Arguments:
// - header: string to normalize
// Examples:
// "First Name" -> "firstName"
// "Market Cap (millions) -> "marketCapMillions
// "1 number at the beginning is ignored" -> "numberAtTheBeginningIsIgnored"
function normalizeHeader(header) {
var key = "";
var upperCase = false;
for (var i = 0; i < header.length; ++i) {
var letter = header[i];
if (letter == " " && key.length > 0) {
upperCase = true;
continue;
}
if (!isAlnum(letter)) {
continue;
}
if (key.length == 0 && isDigit(letter)) {
continue; // first character must be a letter
}
if (upperCase) {
upperCase = false;
key += letter.toUpperCase();
} else {
key += letter.toLowerCase();
}
}
return key;
}
// Returns true if the cell where cellData was read from is empty.
// Arguments:
// - cellData: string
function isCellEmpty(cellData) {
return typeof(cellData) == "string" && cellData == "";
}
// Returns true if the character char is alphabetical, false otherwise.
function isAlnum(char) {
return char >= 'A' && char <= 'Z' ||
char >= 'a' && char <= 'z' ||
isDigit(char);
}
// Returns true if the character char is a digit, false otherwise.
function isDigit(char) {
return char >= '0' && char <= '9';
}
// Given a JavaScript 2d Array, this function returns the transposed table.
// Arguments:
// - data: JavaScript 2d Array
// Returns a JavaScript 2d Array
// Example: arrayTranspose([[1,2,3],[4,5,6]]) returns [[1,4],[2,5],[3,6]].
function arrayTranspose(data) {
if (data.length == 0 || data[0].length == 0) {
return null;
}
var ret = [];
for (var i = 0; i < data[0].length; ++i) {
ret.push([]);
}
for (var i = 0; i < data.length; ++i) {
for (var j = 0; j < data[i].length; ++j) {
ret[j][i] = data[i][j];
}
}
return ret;
}
================================================
FILE: IO2013/Drive/ui.html
================================================
<!doctype html>
<title>Google Drive Quiz Manager</title>
<link rel=stylesheet
href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css">
<style>
#throbber {
left: 50%;
height: 48px;
margin-left: -24px;
margin-top: -24px;
position: absolute;
top: 50%;
width: 48px;
}
</style>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
});
</script>
<legend><center><img src='http://www.google.com/images/icons/product/drive-32.png'/> Google Drive Quiz Manager <img src='http://www.google.com/images/icons/product/script-32.png'/> </center></legend>
<?if(!this.message){?>
<div id=authsetup>
<p class=well>
<center><h3>Please click on the link below to install the Quiz Manager app to your Google Drive. You will be redirected to a standard Google authorization page.<h3></center>
<br><br>
<center>
<a href='<?=getURLForAuthorization()?>' id=authlink class="btn btn-primary">Install app!</a></center>
</p>
</div>
<?}else{?>
<div id=message>
<p class=well>
<center><h3><?=this.message?><h3></center>
<br><br>
<center>
<a href='#' id=authlink class="btn btn-primary">Close window</a></center>
</p>
</div>
<?}?>
<p class=well>
<center><img src = 'http://www.google.com/enterprise/apps/images/homepage/education_home_canvas.png'/></center>
</p>
================================================
FILE: IO2013/YouTubeAnalytics/Code.gs
================================================
function onOpen(){
SpreadsheetApp.getActiveSpreadsheet()
.addMenu('YouTube Analytics',[{name:'Ad hoc report', functionName:'showUI'},
{name: 'Twitter trending', functionName:'twitter'}]);
}
function showUI(){
var ui = HtmlService.createTemplateFromFile('ui').evaluate().setSandboxMode(HtmlService.SandboxMode.NATIVE).setHeight(350);
SpreadsheetApp.getActiveSpreadsheet().show(ui);
}
function sendNightlyEmail(){
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Published Dashboard');
var chart = sheet.getCharts()[0];
MailApp.sendEmail(Session.getActiveUser().getEmail(), 'Daily YouTube Sharing report', 'See attached image', {name:'Sharing chart',attachments:[chart.getBlob()]});
}
function alertOnViewsIncrease(){
//perform business logic here to compare against previously stored values/thresholds
}
function doGet(e) {
var HTMLToOutput;
if(e.parameter.code){//if we get "code" as a parameter in, then this is a callback. we can make this more explicit
getAndStoreAccessToken(e.parameters.code);
HTMLToOutput = HtmlService.createHtmlOutputFromFile('oauthsuccess').getContent();
}
else if(isTokenValid()){//we already have a valid token but this should never start here.
HTMLToOutput = '<html><h1>Invalid access</h1></html>';
}
else {//we are starting from scratch but this should never start here.
HTMLToOutput = "<html><h1>Invalid access</h1></html>";
}
return HtmlService.createHtmlOutput(HTMLToOutput).setSandboxMode(HtmlService.SandboxMode.NATIVE);
}
function getData(startdate,enddate,metrics,dimensions){
var ss = SpreadsheetApp.getActiveSpreadsheet();
//these are the channels and contentOwner settings we care for -
var ids = 'contentOwner==promo-pso-brazil';
var filters = 'channel==UCEN58iXQg82TXgsDCjWqIkg';
var sheet = ss.insertSheet();
ss.setActiveSheet(sheet);
var base_url = 'https://www.googleapis.com/youtube/analytics/v1/reports?';
var getDataURL = base_url + 'ids='+ids+'&start-date='+startdate+'&end-date='+enddate+'&metrics='+metrics+'&dimensions='+dimensions+'&filters='+filters;
Logger.log(getDataURL);
var dataResponse = UrlFetchApp.fetch(getDataURL,getUrlFetchOptions()).getContentText();
var dataObj = JSON.parse(dataResponse);
var headers = [];
for(var i = 0;dataObj.columnHeaders && i<dataObj.columnHeaders.length;i++){
headers.push(dataObj.columnHeaders[i].name);
}
ss.appendRow(headers);
for(var i = 0;dataObj.rows && i<dataObj.rows.length;i++){
ss.appendRow(dataObj.rows[i]);
}
}
================================================
FILE: IO2013/YouTubeAnalytics/README.md
================================================
Companion code for Google IO 2013 session - Ad Hoc Analysis with Google Apps Script and YouTube Analytics API
https://developers.google.com/events/io/sessions/328316141
For setup -
You'll need to create OAuth 2 client ID/secret at http://developers.google.com/console and store it in the right ScriptProperties.
Similarly for the Twitter sample, you'll need to create a Key/Secret with the Twitter API.
================================================
FILE: IO2013/YouTubeAnalytics/oauth2.gs
================================================
var AUTHORIZE_URL = 'https://accounts.google.com/o/oauth2/auth'; //step 1. we can actually start directly here if that is necessary
var TOKEN_URL = 'https://accounts.google.com/o/oauth2/token'; //step 2. after we get the callback, go get token
var CLIENT_ID = ScriptProperties.getProperty('GOOGLE_YTA_OAUTH_CLIENT_ID');
var CLIENT_SECRET = ScriptProperties.getProperty('GOOGLE_YTA_OAUTH_CLIENT_SECRET');
//PUT YOUR URL HERE -
var REDIRECT_URL= 'https://script.google.com/macros/s/AKfycbyFabJD1uUo3NNXAVVlFVapCRnJw7dJKBmCF3X9nzhgPmxZbRM/exec';
var oauthTokenPropertyName = 'GOOGLE_OAUTH_ACCESS_TOKEN';
var oauthTokenExpiresPropertyName = 'GOOGLE_OAUTH_ACCESS_TOKEN_EXPIRES';
var refreshTokenPropertyName = 'GOOGLE_OAUTH_REFRESH_TOKEN';
function getURLForAuthorization(){
return AUTHORIZE_URL + '?response_type=code&client_id='+CLIENT_ID+'&redirect_uri='+REDIRECT_URL +
'&scope=https://www.googleapis.com/auth/yt-analytics.readonly&approval_prompt=force&access_type=offline&state=/profile';
}
function getAndStoreAccessToken(code){
var parameters = {
method : 'post',
payload : 'client_id='+CLIENT_ID+'&client_secret='+CLIENT_SECRET+'&grant_type=authorization_code&redirect_uri='+REDIRECT_URL+'&code=' + code
};
var response = UrlFetchApp.fetch(TOKEN_URL,parameters).getContentText();
storeOAuthValues_(response);
}
function getUrlFetchOptions() {
var token = UserProperties.getProperty(oauthTokenPropertyName);
return {
"contentType" : "application/json",
"headers" : {
"Authorization" : "Bearer " + token,
"Accept" : "application/json"
}
};
}
function attemptTokenRefresh_() {
var refreshToken = UserProperties.getProperty(refreshTokenPropertyName);
if (!refreshToken) {
Logger.log('No refresh token available to refresh with ' + refreshTokenPropertyName);
return false;
}
var requestData = {
method: 'post',
payload: {
client_id: CLIENT_ID,
client_secret: CLIENT_SECRET,
refresh_token: refreshToken,
grant_type: 'refresh_token'
}
};
Logger.log('Attempting token refresh');
var response = UrlFetchApp.fetch(TOKEN_URL, requestData).getContentText();
storeOAuthValues_(response);
return true;
}
function storeOAuthValues_(response){
var tokenResponse = JSON.parse(response);
var accessToken = tokenResponse.access_token;
// expires_in is in seconds and Date.now is ms
var endMs = Date.now() + tokenResponse.expires_in * 1000;
var refreshToken = tokenResponse.refresh_token;
//store the token for later retrival
UserProperties.setProperty(oauthTokenPropertyName, accessToken);
if (refreshToken) { //on a refresh call we wont get a new refresh token, lets not wipe prev one out
UserProperties.setProperty(refreshTokenPropertyName, refreshToken);
}
UserProperties.setProperty(oauthTokenExpiresPropertyName, endMs);
}
function isOAuthed() {
if (hasValidToken_()) {
Logger.log('Valid oauth token found');
return true;
} else {
try {
return attemptTokenRefresh_();
} catch (e) {
Logger.log('Failed to refresh token with error: ' + e);
return false;
}
}
}
function hasValidToken_() {
if (!isTokenPresent_()) {
return false;
}
return (!isTokenExpired_());
}
function isTokenExpired_() {
var expirationTimeMs = UserProperties.getProperty(oauthTokenExpiresPropertyName);
if (!expirationTimeMs) {
return true;
}
expirationTimeMs = Number(expirationTimeMs);
var threshold = Date.now() + 30000;
return (expirationTimeMs < threshold);
}
function isTokenPresent_() {
var token = UserProperties.getProperty(oauthTokenPropertyName);
if(!token){ //if its empty or undefined
return false;
}
return true;
}
================================================
FILE: IO2013/YouTubeAnalytics/oauthsuccess.html
================================================
<!doctype html>
<title>YouTube Analytics</title>
<link rel=stylesheet href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css">
<legend><img src='http://www.youtube.com/yt/img/logo_hh.png'/> Ad hoc Report Generator</legend>
<p class=well>
Thank you for authorization the application. Please close this window and return to the spreadsheet.
<br/></br/>
<a href='#' id='closewindow' class="btn btn-primary">Close window</a>
</p>
================================================
FILE: IO2013/YouTubeAnalytics/twitter.gs
================================================
function twitter(){
var oauthCfg = UrlFetchApp.addOAuthService('twitter');
oauthCfg.setAccessTokenUrl('https://api.twitter.com/oauth/access_token');
oauthCfg.setRequestTokenUrl('https://api.twitter.com/oauth/request_token');
oauthCfg.setAuthorizationUrl('https://api.twitter.com/oauth/authorize');
oauthCfg.setConsumerKey(ScriptProperties.getProperty('TWITTER_CLIENT_ID'));
oauthCfg.setConsumerSecret(ScriptProperties.getProperty('TWITTER_CLIENT_SECRET'));
var options = {oAuthServiceName:'twitter',oAuthUseToken:'always'};
var WOEIDs = {};
WOEIDs['United States'] = '23424977';
WOEIDs['Brazil'] = '23424768'
WOEIDs['South Africa'] = '23424942'
WOEIDs['United Kindom'] = '23424975';
WOEIDs['Canada'] = '23424775'
var headers = [];
var ss = SpreadsheetApp.getActiveSpreadsheet();
for(var woe in WOEIDs){
var url = 'https://api.twitter.com/1.1/trends/place.json?id='+WOEIDs[woe]; //eg. all = 1, london = 44418
var response = UrlFetchApp.fetch(url, options).getContentText();
var myObject = JSON.parse(response)[0];
var trends = []
for(var i = 0;myObject.trends && i<myObject.trends.length;i++){
trends.push(myObject.trends[i].name);
}
ss.appendRow([myObject.as_of,woe,trends.join(', ')]);
}
}
================================================
FILE: IO2013/YouTubeAnalytics/ui.html
================================================
<!doctype html>
<title>YouTube Analytics</title>
<link rel=stylesheet
href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css">
<style>
#throbber {
left: 50%;
height: 48px;
margin-left: -24px;
margin-top: -24px;
position: absolute;
top: 50%;
width: 48px;
}
</style>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#throbber').hide();
<?if (!isOAuthed()){?>
$('#authsetup').show();
$('#configForm').hide();
<?} else {?>
$('#authsetup').hide();
$('#configForm').show();
<?}?>
$('#authlink').click(function(){
$('#authsetup').hide();
$('#throbber').show();
checkForOAuthKey();
});
$('#load').click(function(){
$('#configForm').hide();
$('#throbber').show();
google.script.run.withSuccessHandler(submissionSucceeded).withFailureHandler(alert).getData($('#start').val(),$('#end').val(),$('#metrics').val(),$('#dim').val());
});
});
function submissionSucceeded(){
$('#configForm').show();
$('#throbber').hide();
}
var timeoutId = null;
function checkForOAuthKey() {
//console.log(new Date() + 'checking for OAuth Key');
google.script.run.withSuccessHandler(gotOAuthCheckBack).isOAuthed();
timeoutId = window.setTimeout(checkForOAuthKey, 1500);
}
function gotOAuthCheckBack(e){
//console.log(new Date() + 'Got back ' + e + ' for oauth check');
if(e){
//console.log(new Date() + 'Clearing timeout');
window.clearTimeout(timeoutId);
timeoutId = null;
$('#throbber').hide();
$('#configForm').show();
}
}
</script>
<img id=throbber src="//ssl.gstatic.com/music/ap/cec6433ac17a57a5ad3264da7b23e565/Spinner_48.gif"
alt="Loading...">
<legend><img src='http://www.youtube.com/yt/img/logo_hh.png'/> Ad hoc Report Generator</legend>
<div id=authsetup>
<p class=well>
Please click on the link below to authorize application to the YouTube Analytics API. This page will automatically refresh when you return.
<center>
<a href='<?=getURLForAuthorization()?>' id=authlink class="btn btn-primary">Authorize app</a></center>
</p>
</div>
<form id=configForm class=form-horizontal><fieldset>
<div class=control-group>
<label class=control-label for=start>Start date:</label>
<div class=controls><input id="start" class=input-large name=start type=text value="2013-04-01"></div>
</div>
<div class=control-group>
<label class=control-label for=end>End date:</label>
<div class=controls><input id="end" class=input-large name=end type=text value="2013-04-30"></div>
</div>
<div class=control-group>
<label class=control-label for=metrics>Metrics:</label>
<div class=controls><select id="metrics" class=input-large name=metrics>
<option value="viewerPercentage">Viewer Percentage</option>
<option value="estimatedMinutesWatched,averageViewDuration,averageViewPercentage">Watch time</option>
<option value="views,likes">Engagement - Views, Likes</option>
<option value="shares">Engagement - Shares</option>
</select></div>
</div>
<div class=control-group>
<label class=control-label for=dim>Dimensions:</label>
<div class=controls><select id="dim" class=input-large name=dim>
<option value="ageGroup,gender">Demography</option>
<option value="day">Day</option>
<option value="country">Country</option>
<option value="sharingService">Sharing service</option>
</select></div>
</div>
<div class=form-actions>
<button id=load class="btn btn-primary" type=submit>Load</button>
<button id=cancel class="btn btn-info" type=button>Cancel</button>
</div>
</fieldset></form>
================================================
FILE: NYTimesCampaignContribution.gs
================================================
function getData(){
var API_KEY = 'YOUR_API_KEY_HERE';
var url = 'http://api.nytimes.com/svc/elections/us/v3/finances/2012/president/states/NY.json?api-key='+API_KEY;
var response = UrlFetchApp.fetch(url).getContentText();
var respObj = JSON.parse(response);
var ss = SpreadsheetApp.create('NY Presidential Campaign')
//add a simple header
ss.appendRow(['Candidate','Number of Contributions','Total $ Contributions']);
for(var i in respObj.results){
ss.appendRow([respObj.results[i].full_name,respObj.results[i].contribution_count,respObj.results[i].total]);
}
}
================================================
FILE: README.md
================================================
GoogleAppsScript
================
Sample code for Google Apps Script.
These are not official Google samples. These are more of proof of concepts to support demos and other presentations.
Please use this code as a guidline and not as production ready code.
http://developers.google.com/apps-script
http://script.google.com
All code in this folder released under [Apache 2.0 license](http://www.apache.org/licenses/LICENSE-2.0).
================================================
FILE: SAP/Forms/Code.gs
================================================
function onFormSubmit(e) {
var myObject = {};
var itemResponses = e.response.getItemResponses();
for (var j = 0; j < itemResponses.length; j++) {
var itemResponse = itemResponses[j];
myObject[itemResponse.getItem().getTitle()] = itemResponse.getResponse();
//Logger.log('"%s" was "%s"',itemResponse.getItem().getTitle(), itemResponse.getResponse());
}
Logger.log(myObject);
var t = HtmlService.createTemplateFromFile('product_template');
t.data = myObject;
var postPayload = t.evaluate().getContent();
Logger.log(postPayload);
var base_url = "https://sapes1.sapdevcenter.com/sap/opu/odata/IWBEP/GWDEMO/ProductCollection";
var additionParams = "$format=json";
var user = 'YOUR_USERNAME';
var password = 'YOUR_PASSWORD';
var header = 'Basic '+Utilities.base64Encode(user+':'+password);
var headers = {
Authorization: header,
'X-CSRF-Token' : 'Fetch',
"Content-Type": "application/atom+xml"
}
//Logger.log(headers);
var response = UrlFetchApp.fetch(base_url,{headers: headers, muteHttpExceptions: true});
var csrf_token = response.getAllHeaders()['x-csrf-token'];
var cookie = response.getAllHeaders()['set-cookie'];
//Logger.log(response.getAllHeaders());
headers['X-CSRF-Token'] = csrf_token;
headers['Cookie'] = cookie.join('; ');
Logger.log(headers);
//var deleteResponse = UrlFetchApp.fetch(id,{headers: headers, method : 'DELETE', muteHttpExceptions: true});
var createResponse = UrlFetchApp.fetch(base_url,{headers: headers, method : 'POST', contentType : "application/atom+xml", payload: postPayload, muteHttpExceptions: true});
Logger.log(createResponse.getContentText());
}
================================================
FILE: SAP/Forms/product_template.html
================================================
<atom:entry xmlns:atom="http://www.w3.org/2005/Atom" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xml:base="https://sapes1.sapdevcenter.com:443/sap/opu/odata/IWBEP/GWDEMO/">
<atom:content type="application/xml">
<m:properties>
<d:ProductName><?=data['Product Name']?></d:ProductName>
<d:TaxTariffText>Regular VAT</d:TaxTariffText>
<d:ProductID>ARUN-<?=Math.random().toString(36).substring(2, 4)?></d:ProductID>
<d:DimensionUnit>MTR</d:DimensionUnit>
<d:UnitPrice>500.00</d:UnitPrice>
<d:WeightMeasure>4.200</d:WeightMeasure>
<d:ProductWidth>0.320</d:ProductWidth>
<d:SupplierID>0100000000</d:SupplierID>
<d:ProductDescription><?=data['Product Description']?></d:ProductDescription>
<d:ProductCategory>Notebooks</d:ProductCategory>
<d:TaxTariffCode>1</d:TaxTariffCode>
<d:QuantityUnit>EA</d:QuantityUnit>
<d:ProductTypeCode>PR</d:ProductTypeCode>
<d:WeightUnitCode>KGM</d:WeightUnitCode>
<d:SupplierName>SAP</d:SupplierName>
<d:CurrencyCode>EUR</d:CurrencyCode>
<d:ProductHeight>0.040</d:ProductHeight>
<d:ProductDepth>0.210</d:ProductDepth>
</m:properties>
</atom:content>
</atom:entry>
================================================
FILE: SAP/Gmail Schemas/Code.gs
================================================
function testSchemas() {
var htmlBody = HtmlService.createHtmlOutputFromFile('mail_template').getContent();
GmailApp.sendEmail(Session.getEffectiveUser().getEmail(),'Alert for SAP - ' + new Date(),'',
{htmlBody: htmlBody});
}
================================================
FILE: SAP/Gmail Schemas/mail_template.html
================================================
<html>
<head>
<script type="application/ld+json">
{
"@context": "http://schema.org",
"@type": "ParcelDelivery",
"deliveryAddress": {
"@type": "PostalAddress",
"streetAddress": "24 Willie Mays Plaza",
"addressLocality": "San Francisco",
"addressRegion": "CA",
"addressCountry": "US",
"postalCode": "94107"
},
"expectedArrival": "2013-03-12T12:00:00-08:00",
"carrier": {
"@type": "Organization",
"name": "SAP"
},
"itemShipped": {
"@type": "Product",
"name": "iPod Mini"
},
"partOfOrder": {
"@type": "Order",
"orderNumber": "176057",
"seller": {
"@type": "Person",
"name": "Bob Dole"
}
},
"action": {
"@type": "TrackAction",
"name": "Track Order in SAP",
"url": "https://www.package-shipments.com/track?package=abc"
}
}
</script>
</head>
<body>
<p>
This a test for a Go-To action in Gmail.
</p>
</body>
</html>
================================================
FILE: SAP/README.md
================================================
SAP Demos
================
Sample SAP integrations. You'll need to create a [sample SAP account](http://scn.sap.com/docs/DOC-40986) at the SCN.
You can watch the video of the [sample demos here](http://www.slideshare.net/SAPAppsPartner/tehcnical-webinar-technical-webinar-building-mashups-with-google-apps-and-sap-using-sap-netweaver-gateway) (start at about 1 hr in for Google Apps demos)
These are not official Google samples. These are more of proof of concepts to support demos and other presentations.
Please use this code as a guidline and not as production ready code.
http://developers.google.com/apps-script
http://script.google.com
All code in this folder released under [Apache 2.0 license](http://www.apache.org/licenses/LICENSE-2.0).
================================================
FILE: SAP/Sheets/Code.gs
================================================
//sample instance
//http://scn.sap.com/docs/DOC-40986
function onOpen(){
SpreadsheetApp.getActiveSpreadsheet()
.addMenu('SAP NetWeaver',[{name:'SAP Data Wizard', functionName:'showUI'},
null,
{name:'Load Business Partners', functionName:'getBusinessPartnerData'},
{name:'Load Sales Orders', functionName:'getSalesOrderData'},
null,
{name:'Load Items for Sales Order', functionName:'loadSalesItems'},
null,
{name: 'Post to Google+', functionName:'googleplus'}]);//future ideas
}
function showUI(){
var ui = HtmlService.createTemplateFromFile('ui').evaluate().setSandboxMode(HtmlService.SandboxMode.NATIVE).setHeight(550);
SpreadsheetApp.getActiveSpreadsheet().show(ui);
}
function returnDate(unix_timestamp){
//var unix_timestamp = '1370025951';
var date = new Date(unix_timestamp*1000);
//Logger.log(date);
return date;
}
function returnUnixtimestamp(dateString){
//var dateString = '2013-04-01';
var parts = dateString.match(/(\d+)/g);
var date = new Date(parts[0], parts[1]-1, parts[2]); // months are 0-based
var timestamp = date.getTime()/1000 + '';
return timestamp;
}
function createOrSetActiveSheet(sheetName){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheets = ss.getSheets();
var sheet;
for(var i = 0;i<sheets.length;i++){
sheet = sheets[i];
var currentSheetName = sheet.getSheetName();
if(sheetName===currentSheetName){
ss.setActiveSheet(sheet);
sheet.clear();
return sheet;
}
}
sheet = ss.insertSheet();
sheet.setName(sheetName);
ss.setActiveSheet(sheet);
return sheet;
}
//future ideas
function sendNightlyEmail(){
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Published Dashboard');
var chart = sheet.getCharts()[0];
MailApp.sendEmail(Session.getActiveUser().getEmail(), 'Daily petition report', 'See attached image', {name:'Sharing chart',attachments:[chart.getBlob()]});
}
function getBusinessPartnerData(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
sheet.clear();
var base_url = "https://sapes1.sapdevcenter.com/sap/opu/odata/IWBEP/GWDEMO/BusinessPartnerCollection/?";
var additionParams = "$format=json";
var user = 'YOUR_USERNAME';
var password = 'YOUR_PASSWORD';
var header = 'Basic '+Utilities.base64Encode(user+':'+password);
var getDataURL = base_url + additionParams;
Logger.log(getDataURL);
var dataResponse = UrlFetchApp.fetch(getDataURL,{headers: {Authorization: header}, muteHttpExceptions: true}).getContentText();
var dataObj = JSON.parse(dataResponse);
var headers = ['Key','Name','Role','Website','Email','Address'];
var maxLetter = String.fromCharCode(64 + headers.length);
sheet.appendRow(headers);
sheet.getRange('A1:'+maxLetter+'1').setBackground('Grey').setFontStyle('oblique');
ss.setColumnWidth(2, 220);
ss.setColumnWidth(3, 89);
var rows = [];
for(var i = 0;dataObj.d.results && i<dataObj.d.results.length;i++){
var row = dataObj.d.results[i];
rows.push([row.BusinessPartnerKey,row.Company,row.BusinessPartnerRoleText,row.WebAddress, row.EmailAddress, 'street address']);
}
var rowsCount = rows.length+1;
ss.getRange('A2:'+maxLetter+rowsCount).setValues(rows);
}
function getSalesOrderData(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
sheet.clear();
var base_url = "https://sapes1.sapdevcenter.com/sap/opu/odata/IWBEP/GWDEMO/SalesOrderCollection/?";
var additionParams = "$format=json";
var user = 'YOUR_USERNAME';
var password = 'YOUR_PASSWORD';
var header = 'Basic '+Utilities.base64Encode(user+':'+password);
var getDataURL = base_url + additionParams;
Logger.log(getDataURL);
var dataResponse = UrlFetchApp.fetch(getDataURL,{headers: {Authorization: header}, muteHttpExceptions: true}).getContentText();
var dataObj = JSON.parse(dataResponse);
var headers = ['Sales Order Key','Customer Name','Status','Currency','Total Amt','Tax Amt','Note','Created By','Changed By'];
var maxLetter = String.fromCharCode(64 + headers.length);
sheet.appendRow(headers);
sheet.getRange('A1:'+maxLetter+'1').setBackground('Grey').setFontStyle('oblique');
ss.setColumnWidth(2, 220);
ss.setColumnWidth(3, 89);
var rows = [];
for(var i = 0;dataObj.d.results && i<dataObj.d.results.length;i++){
var row = dataObj.d.results[i];
rows.push([row.SalesOrderKey,row.CustomerName,row.StatusDescription,row.Currency,row.TotalSum,row.Tax,row.Note,row.CreatedByEmployeeLastName,row.ChangedByEmployeeLastName]);
}
var rowsCount = rows.length+1;
ss.getRange('A2:'+maxLetter+rowsCount).setValues(rows);
}
function loadSalesItems(){
var salesOrderKey = SpreadsheetApp.getActiveRange().getValue();
var initialPageCount = 99; //because a default sheet has only 100 rows to start
var sheet = createOrSetActiveSheet(salesOrderKey);
var base_url = "https://sapes1.sapdevcenter.com/sap/opu/odata/IWBEP/GWDEMO/SalesOrderCollection('"+salesOrderKey+"')/salesorderlineitems?";
var getDataURL = base_url + '$format=json';
var user = 'YOUR_USERNAME';
var password = 'YOUR_PASSWORD';
var header = 'Basic '+Utilities.base64Encode(user+':'+password);
Logger.log(getDataURL);
var dataResponse = UrlFetchApp.fetch(getDataURL,{headers: {Authorization: header}, muteHttpExceptions: true}).getContentText();
Logger.log(dataResponse);
var dataObj = JSON.parse(dataResponse);
var headers = ['SalesOrderItemKey','ProductName','Availability','Note','Currency','NetSum','Tax','TotalSum'];
var maxLetter = String.fromCharCode(64 + headers.length);
sheet.appendRow(headers);
sheet.getRange('A1:'+maxLetter+'1').setBackground('Grey').setFontStyle('oblique');
var rows = [];
for(var i = 0;dataObj.d.results && i<dataObj.d.results.length;i++){
var row = dataObj.d.results[i];
rows.push([row.SalesOrderItemKey,row.ProductName,row.Availability,row.Note,row.Currency,row.NetSum,row.Tax,row.TotalSum]);
}
var rowsCount = rows.length+1;
sheet.getRange('A2:'+maxLetter+rowsCount).setValues(rows);
}
================================================
FILE: SAP/Sheets/ui.html
================================================
<!--
This is an incomplete place holder for just showing the UI
-->
<link rel=stylesheet
href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css">
<style>
#throbber {
left: 50%;
height: 48px;
margin-left: -24px;
margin-top: -24px;
position: absolute;
top: 50%;
width: 48px;
}
</style>
<img id=throbber src="//ssl.gstatic.com/music/ap/cec6433ac17a57a5ad3264da7b23e565/Spinner_48.gif"
alt="Loading...">
<legend><img src='http://www.sap.com/global/ui/images/global/sap-logo.png'/>SAP NetWeaver</legend>
<form id=configForm class=form-horizontal><fieldset>
<div class=control-group>
<label class=control-label for=title_keyword>Title keyword:</label>
<div class=controls><input id="title_keyword" class=input-large name=title_keyword type=text value=""></div>
</div>
<div class=control-group>
<label class=control-label for=body_keyword>Body Keyword:</label>
<div class=controls><input id="body_keyword" class=input-large name=body_keyword type=text value=""></div>
</div>
<div class=control-group>
<label class=control-label for=start>Start date:</label>
<div class=controls><input id="start" class=input-large name=start type=date value="2013-04-01"></div>
</div>
<div class=control-group>
<label class=control-label for=end>End date:</label>
<div class=controls><input id="end" class=input-large name=end type=date value="2013-04-30"></div>
</div>
<div class=control-group>
<label class=control-label for=sig_floor>Minumum Signatures:</label>
<div class=controls><input id="sig_floor" class=input-large name=sig_floor type=text value="0"></div>
</div>
<div class=control-group>
<label class=control-label for=metrics>Priority:</label>
<div class=controls><select id="issues" class=input-large name=issues>
<option value=""></option>
<option value="1">High</option>
<option value="2">Medium</option>
<option value="3">Low</option>
</select></div>
</div>
<div class=control-group>
<label class=control-label for=dim>Status:</label>
<div class=controls><select id="status" class=input-large name=status>
<option value=""></option>
<option value="open">Open</option>
<option value="closed">Closed</option>
<option value="pending response">Pending Response</option>
<option value="responded">Responded</option>
</select></div>
</div>
<div class=form-actions>
<button id=load class="btn btn-primary" type=submit>Load</button>
<button id=cancel class="btn btn-info" type=button onclick='google.script.host.close()'>Close</button>
</div>
</fieldset></form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#throbber').hide();
$('#load').click(function(){
$('#configForm').hide();
$('#throbber').show();
google.script.run.withSuccessHandler(submissionSucceeded).withFailureHandler(alert).getData($('#title_keyword').val(),
$('#body_keyword').val(),
$('#start').val(),
$('#end').val(),
$('#sig_floor').val(),
$('#status').val());
});
});
function submissionSucceeded(){
$('#configForm').show();
$('#throbber').hide();
}
</script>
================================================
FILE: Salesforce.com/OAuthAndUploadContactsToSalesforce.gs
================================================
function onInstall(){
onOpen();
}
function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var menuEntries = [ {name: "Upload to SalesForce", functionName: "salesforceEntryPoint"}];
ss.addMenu("Salesforce.com", menuEntries);
}
function salesforceEntryPoint(){
if(isTokenValid()){
HTMLToOutput = '<html><h1>Already have token</h1></html>';
//HTMLToOutput += getData();
HTMLToOutput += uploadData();
}
else {//we are starting from scratch or resetting
HTMLToOutput = "<html><h1>You need to login</h1><a href='"+getURLForAuthorization()+"'>click here to start</a><br>Re-open this window when you return.</html>";
}
SpreadsheetApp.getActiveSpreadsheet().show(HtmlService.createHtmlOutput(HTMLToOutput));
}
function doGet(e) {
var HTMLToOutput;
if(e.parameters.code){//if we get "code" as a parameter in, then this is a callback. we can make this more explicit
getAndStoreAccessToken(e.parameters.code);
HTMLToOutput = '<html><h1>Finished with oAuth</h1>You can close this window.</html>';
}
return HtmlService.createHtmlOutput(HTMLToOutput);
}
//do meaningful salesforce access here
function getData(){
return runSOQL('SELECT+name+from+Account');
}
function runSOQL(soql){
var getDataURL = UserProperties.getProperty(baseURLPropertyName) + '/services/data/v26.0/query/?q='+soql;
var dataResponse = UrlFetchApp.fetch(getDataURL,getUrlFetchOptions()).getContentText();
return dataResponse;
}
function uploadData() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var contactDataRange = ss.getDataRange();
var contactObjects = getRowsData(sheet, contactDataRange,1);
var runningLog = '<br>Uploaded following:<br><br>';
for(var i = 1;i<contactObjects.length;i++){
var payload = Utilities.jsonStringify(
{"FirstName" : contactObjects[i].firstname,
"LastName" : contactObjects[i].lastname,
"Email" : contactObjects[i].email,
"Phone" : contactObjects[i].phone
}
);
Logger.log('trying ' + payload);
var getDataURL = UserProperties.getProperty(baseURLPropertyName) + '/services/data/v26.0/sobjects/Contact/';
runningLog += UrlFetchApp.fetch(getDataURL,getUrlFetchPOSTOptions(payload)).getContentText() + '<br>';
}
return runningLog;
}
////oAuth related code
//hardcoded here for easily tweaking this. should move this to ScriptProperties or better parameterize them
//step 1. we can actually start directly here if that is necessary
var AUTHORIZE_URL = 'https://login.salesforce.com/services/oauth2/authorize';
//step 2. after we get the callback, go get token
var TOKEN_URL = 'https://login.salesforce.com/services/oauth2/token';
//PUT YOUR OWN SETTINGS HERE
var CLIENT_ID = '3MVG9y6x0357HlefXsMa7Fg0tYH0SLtBZwLWyhSP4hBGExVuUjoWLJ8rfZ1jyyw0ZRQt7H28rByHHJjRQlqMs';
var CLIENT_SECRET='SECRET_HERE';
var REDIRECT_URL= ScriptApp.getService().getUrl();
//this is the user propety where we'll store the token, make sure this is unique across all user properties across all scripts
var tokenPropertyName = 'SALESFORCE_OAUTH_TOKEN';
var baseURLPropertyName = 'SALESFORCE_INSTANCE_URL';
//this is the URL where they'll authorize with salesforce.com
//may need to add a "scope" param here. like &scope=full for salesforce
function getURLForAuthorization(){
return AUTHORIZE_URL + '?response_type=code&client_id='+CLIENT_ID+'&redirect_uri='+REDIRECT_URL
}
function getAndStoreAccessToken(code){
var nextURL = TOKEN_URL + '?client_id='+CLIENT_ID+'&client_secret='+CLIENT_SECRET+'&grant_type=authorization_code&redirect_uri='+REDIRECT_URL+'&code=' + code;
var response = UrlFetchApp.fetch(nextURL).getContentText();
var tokenResponse = JSON.parse(response);
//salesforce requires you to call against the instance URL that is against the token (eg. https://na9.salesforce.com/)
UserProperties.setProperty(baseURLPropertyName, tokenResponse.instance_url);
//store the token for later retrival
UserProperties.setProperty(tokenPropertyName, tokenResponse.access_token);
}
function getUrlFetchOptions() {
var token = UserProperties.getProperty(tokenPropertyName);
return {
"contentType" : "application/json",
"headers" : {
"Authorization" : "Bearer " + token,
"Accept" : "application/json"
}
};
}
function getUrlFetchPOSTOptions(payload){
var token = UserProperties.getProperty(tokenPropertyName);
return {
"method": "post",
"contentType" : "application/json",
"payload" : payload,
"headers" : {
"Authorization" : "Bearer " + token
}
}
}
function isTokenValid() {
var token = UserProperties.getProperty(tokenPropertyName);
if(!token){ //if its empty or undefined
return false;
}
return true; //naive check
}
================================================
FILE: Salesforce.com/RowUtilities.gs
================================================
// getRowsData iterates row by row in the input range and returns an array of objects.
// Each object contains all the data for a given row, indexed by its normalized column name.
// Arguments:
// - sheet: the sheet object that contains the data to be processed
// - range: the exact range of cells where the data is stored
// - columnHeadersRowIndex: specifies the row number where the column names are stored.
// This argument is optional and it defaults to the row immediately above range;
// Returns an Array of objects.
function getRowsData(sheet, range, columnHeadersRowIndex) {
columnHeadersRowIndex = columnHeadersRowIndex || range.getRowIndex() - 1;
var numColumns = range.getEndColumn() - range.getColumn() + 1;
var headersRange = sheet.getRange(columnHeadersRowIndex, range.getColumn(), 1, numColumns);
var headers = headersRange.getValues()[0];
return getObjects(range.getValues(), normalizeHeaders(headers));
}
// getColumnsData iterates column by column in the input range and returns an array of objects.
// Each object contains all the data for a given column, indexed by its normalized row name.
// Arguments:
// - sheet: the sheet object that contains the data to be processed
// - range: the exact range of cells where the data is stored
// - rowHeadersColumnIndex: specifies the column number where the row names are stored.
// This argument is optional and it defaults to the column immediately left of the range;
// Returns an Array of objects.
function getColumnsData(sheet, range, rowHeadersColumnIndex) {
rowHeadersColumnIndex = rowHeadersColumnIndex || range.getColumnIndex() - 1;
var headersTmp = sheet.getRange(range.getRow(), rowHeadersColumnIndex, range.getNumRows(), 1).getValues();
var headers = normalizeHeaders(arrayTranspose(headersTmp)[0]);
return getObjects(arrayTranspose(range.getValues()), headers);
}
// For every row of data in data, generates an object that contains the data. Names of
// object fields are defined in keys.
// Arguments:
// - data: JavaScript 2d array
// - keys: Array of Strings that define the property names for the objects to create
function getObjects(data, keys) {
var objects = [];
for (var i = 0; i < data.length; ++i) {
var object = {};
var hasData = false;
for (var j = 0; j < data[i].length; ++j) {
var cellData = data[i][j];
if (isCellEmpty(cellData)) {
continue;
}
object[keys[j]] = cellData;
hasData = true;
}
if (hasData) {
objects.push(object);
}
}
return objects;
}
// Returns an Array of normalized Strings.
// Arguments:
// - headers: Array of Strings to normalize
function normalizeHeaders(headers) {
var keys = [];
for (var i = 0; i < headers.length; ++i) {
var key = normalizeHeader(headers[i]);
if (key.length > 0) {
keys.push(key);
}
}
return keys;
}
// Normalizes a string, by removing all alphanumeric characters and using mixed case
// to separate words. The output will always start with a lower case letter.
// This function is designed to produce JavaScript object property names.
// Arguments:
// - header: string to normalize
// Examples:
// "First Name" -> "firstName"
// "Market Cap (millions) -> "marketCapMillions
// "1 number at the beginning is ignored" -> "numberAtTheBeginningIsIgnored"
function normalizeHeader(header) {
var key = "";
var upperCase = false;
for (var i = 0; i < header.length; ++i) {
var letter = header[i];
if (letter == " " && key.length > 0) {
upperCase = true;
continue;
}
if (!isAlnum(letter)) {
continue;
}
if (key.length == 0 && isDigit(letter)) {
continue; // first character must be a letter
}
if (upperCase) {
upperCase = false;
key += letter.toUpperCase();
} else {
key += letter.toLowerCase();
}
}
return key;
}
// Returns true if the cell where cellData was read from is empty.
// Arguments:
// - cellData: string
function isCellEmpty(cellData) {
return typeof(cellData) == "string" && cellData == "";
}
// Returns true if the character char is alphabetical, false otherwise.
function isAlnum(char) {
return char >= 'A' && char <= 'Z' ||
char >= 'a' && char <= 'z' ||
isDigit(char);
}
// Returns true if the character char is a digit, false otherwise.
function isDigit(char) {
return char >= '0' && char <= '9';
}
// Given a JavaScript 2d Array, this function returns the transposed table.
// Arguments:
// - data: JavaScript 2d Array
// Returns a JavaScript 2d Array
// Example: arrayTranspose([[1,2,3],[4,5,6]]) returns [[1,4],[2,5],[3,6]].
function arrayTranspose(data) {
if (data.length == 0 || data[0].length == 0) {
return null;
}
var ret = [];
for (var i = 0; i < data[0].length; ++i) {
ret.push([]);
}
for (var i = 0; i < data.length; ++i) {
for (var j = 0; j < data[i].length; ++j) {
ret[j][i] = data[i][j];
}
}
return ret;
}
================================================
FILE: Salesforce.com/ScanEmailToSalesforce.gs
================================================
function scanEmail(){
//for performance sake, we'll scan top 3 threads for now.
//a more intelligent trigger would know it last left off and then pick it up from there
var threads = GmailApp.getInboxThreads(0, 5);
for (var i = 0; i < threads.length; i++) {
var message = threads[i].getMessages()[0]; //for now, only scan first message
if(message.getAttachments().length < 1)
continue;
var attachment = message.getAttachments()[0]; //for now, only first attachment
Logger.log(attachment.getName());
var base64content = Utilities.base64Encode(attachment.getAs('application/pdf').getBytes());
var fromAddress = message.getFrom();
//this will return of the the format - Arun Nagarajan <arun.appsscript@gmail.com>
var actualAddress = /<(.*?)>/.exec(fromAddress)[1];
var soql = encodeURIComponent("select Id from contact where Email='"+actualAddress+"'");
//Logger.log(actualAddress);
var responseObject = Utilities.jsonParse(runSOQL(soql));
if(responseObject.totalSize !== 0){
var contactId = responseObject.records[0].Id;
var payload = Utilities.jsonStringify(
{
'Name' : attachment.getName() + '_GmailAttachment.pdf',
'ParentId' : contactId,
'body' : base64content
});
Logger.log(contactId);
var getDataURL = UserProperties.getProperty(baseURLPropertyName) + '/services/data/v26.0/sobjects/Attachment/';
var response = UrlFetchApp.fetch(getDataURL,getUrlFetchPOSTOptions(payload)).getContentText();
Logger.log(response);
}
}
}
================================================
FILE: Salesforce.com/readme.md
================================================
Click the image below for video with more details -
[](http://www.youtube.com/watch?v=9SEAmNDtlcA&list=PL68F511F6E3C122EB)
================================================
FILE: ScriptDbVisualizer/Code.gs
================================================
var db = ScriptDb.getMyDb();
function doGet() {
return HtmlService.createHtmlOutputFromFile('ScriptDbConsole');
}
function saveObjToDb(obj){
try{
var savedObj = db.save(obj);
return "Saved ID - " + savedObj.getId();
}catch(e){
log(e);
throw(e);
}
}
function getCount(query){
try{
return "Current count for query is - " + db.count(query);
}catch(e){
log(e);
throw(e);
}
}
function loadIDsFromDb(idlist){
try{
return db.load(idlist);
}catch(e){
log(e);
throw(e);
}
}
function deleteByIds(idlist){
var obs_to_remove = loadIDsFromDb(idlist);
var results = db.removeBatch(obs_to_remove, false);
if (db.allOk(results)) {
return "Delete by IDs successfull!";
}
var failedObs = [];
for (var i = 0; i < results.length; i++) {
if (!results[i].successful()) {
failedObs.push(obs_to_remove[i]);
}
}
return "Failed to delete " + failedObs.length + " item(s) out of " + results.length;
}
function queryFromDb(query){
try{
var result = db.query(query);
var response = {};
while (result.hasNext()) {
var current = result.next();
response[current.getId()] = current;
}
return response;
}catch(e){
log(e);
throw(e);
}
}
function deleteAll(query) {
try{
while (true) {
var result = db.query(query);
if (result.getSize() == 0) {
break;
}
while (result.hasNext()) {
db.remove(result.next());
}
}
return "Delete for specified query successful!";
}catch(e){
log(e);
throw(e);
}
}
function log(msg){
//write to a logger here
//DocsList.getFileById('0B0JNj_IM2wiPMS1lZTFhZjVjNC0yZTBjLTRiOWItYWVhMy0yYTU1ZjdkMGVkMGE').append(msg+'\n');
}
================================================
FILE: ScriptDbVisualizer/ScriptDbConsole.html
================================================
<html>
<style>
pre {outline: 1px solid #ccc; padding: 5px; margin: 5px; }
.string { color: green; }
.number { color: darkorange; }
.boolean { color: blue; }
.null { color: magenta; }
.key { color: red; }
</style>
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script>
function output(inp) {
$('#results').prepend(inp);
}
//courtesy of http://stackoverflow.com/a/7220510/662551
function syntaxHighlight(json) {
json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
var cls = 'number';
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = 'key';
} else {
cls = 'string';
}
} else if (/true|false/.test(match)) {
cls = 'boolean';
} else if (/null/.test(match)) {
cls = 'null';
}
return '<span class="' + cls + '">' + match + '</span>';
});
}
$(document).ready(function() {
$('#saveItem').click(function(){
var input = $('#textarea').val();
input = JSON.parse(input);
google.script.run.withSuccessHandler(handleMessageResponse).withFailureHandler(addToLog).saveObjToDb(input);
});
$('#runQuery').click(function(){
var input = $('#textarea').val();
input = JSON.parse(input);
google.script.run.withSuccessHandler(handleQueryResponse).withFailureHandler(addToLog).queryFromDb(input);
});
$('#deleteAll').click(function(){
var input = $('#textarea').val();
input = JSON.parse(input);
google.script.run.withSuccessHandler(handleMessageResponse).withFailureHandler(addToLog).deleteAll(input);
});
$('#loadId').click(function(){
var input = $('#textarea').val();
var re = /\s*,\s*/;
var idList = input.split(re);
google.script.run.withSuccessHandler(handleQueryResponse).withFailureHandler(addToLog).loadIDsFromDb(idList);
});
$('#deleteByIds').click(function(){
var input = $('#textarea').val();
var re = /\s*,\s*/;
var idList = input.split(re);
google.script.run.withSuccessHandler(handleMessageResponse).withFailureHandler(addToLog).deleteByIds(idList);
});
$('#count').click(function(){
var input = $('#textarea').val();
input = JSON.parse(input);
google.script.run.withSuccessHandler(handleMessageResponse).withFailureHandler(addToLog).getCount(input);
});
});
function handleQueryResponse(responseObj){
$('#results').prepend('<hr><hr>');
if(Object.keys(responseObj).length==0){
output("No results found for query!");
}
//TODO: for load by IDs, this will print index, not object IDs
for (var prop in responseObj) {
if (responseObj.hasOwnProperty(prop)) {
output('<pre>ID: ' + prop+'\n'+syntaxHighlight(JSON.stringify(responseObj[prop], undefined, 4))+'</pre>');
}
}
}
function handleMessageResponse(response){
$('#results').prepend('<hr><hr>');
output(response);
}
function addToLog(error){
$('#results').prepend('<hr><hr>');
output("Error " + JSON.stringify(error));
}
</script>
<body>
<h2>Simple ScriptDb tester</h2>
<b>Enter a JavaScript Object to store, a ScriptDb query to run or IDs to lookup and press the appropriate button below</b><br>
<textarea id="textarea" rows="10" cols="100"></textarea><br>
<button id="count">Get Count</button>
<button id="saveItem">Save Object</button>
<button id="runQuery">Run Query</button>
<button id="loadId">Load by ID</button>
<button id="deleteByIds">Delete by ID</button>
<button id="deleteAll">Delete for Query</button>
<br><br>
<div id="results"></div>
<br><br>
By <a href="https://plus.google.com/117678608428606781684/posts">Arun Nagarajan</a>
</body>
</html>
================================================
FILE: ScriptDbVisualizer/readme.md
================================================
Click the image below for video with more details -
[](http://www.youtube.com/watch?v=aShR3R8--wU&list=PL68F511F6E3C122EB)
================================================
FILE: Twilio/MakePhoneCall/MakePhoneCall.gs
================================================
var ACCOUNT_SID = 'ACd4e8e6872e581bf4cf560d37fb9059db';
var ACCOUNT_TOKEN = 'YOUR_TOKEN_HERE';
//This is a spreadsheet bound script that is also deployed as a web app
//Have a menu or a button point this function to kick things off
function readRows() {
var sheet = SpreadsheetApp.getActiveSheet();
var rows = sheet.getDataRange();
var numRows = rows.getNumRows();
var values = rows.getValues();
//for testing purposes just make call against first row
//expecting columns in this order - name, number, message -
for (var i = 1; i <= 1/*numRows - 1*/; i++) {
makePhoneCall(values[i][0],values[i][1],values[i][2]);
}
}
function makePhoneCall(name,number, message){
//URL is the callback to the current service with the message
var url = ScriptApp.getService().getUrl() + '?MSG'+message.replace(/ /g,'+'); //can't seem to send = in here
Logger.log(url);
var payload = {
"From" : "2246773902"
,"To" : number
,"Url": url
,"Method" : "GET"
};
var headers = {
"Authorization" : "Basic " + Utilities.base64Encode(ACCOUNT_SID + ':' + ACCOUNT_TOKEN)
};
// Because payload is a JavaScript object, it will be interpreted as
// an HTML form. (We do not need to specify contentType; it will
// automatically default to either 'application/x-www-form-urlencoded'
// or 'multipart/form-data')
var options =
{
"method" : "post",
"payload" : payload,
"headers" : headers
};
Logger.log("calling " + name + " at " + number + " with messsage - " + message);
var url = 'https://api.twilio.com/2010-04-01/Accounts/'+ACCOUNT_SID+'/Calls.json';
var response = UrlFetchApp.fetch(url, options);
//Logger.log(response.getResponseCode());
//Logger.log(response.getContentText());
}
//entry point to the call back
function doGet(args){
var msg = '';
for (var p in args.parameters) {
//there are many incoming query params. lets find ours starting with a MSG
if(p.indexOf('MSG') > -1){
msg += p.replace('MSG','');
break;
}
// there HAS to tbe a better way to get the entire query string!
}
var t = HtmlService.createTemplateFromFile("twiml.html");
t.msg = msg;
var content = t.evaluate().getContent();
return ContentService.createTextOutput(content).setMimeType(ContentService.MimeType.XML);
}
================================================
FILE: Twilio/MakePhoneCall/twiml.html
================================================
<Response>
<Say voice="woman" language="en-us"><?=msg?></Say>
<Play loop="1">https://api.twilio.com/cowbell.mp3</Play>
</Response>
================================================
FILE: Twilio/RecieveSMS/RecieveSMS.gs
================================================
//This is deployed as a web app and in the Twilio interface you'll point incoming SMS to the deployed URL
//deploy it to run as you and allow anyone (even anonymous) can access it
function doGet(args) {
var spreadsheetID = 'YOUR_SPREAD_SHEETID';
//Incoming params are documented here - https://www.twilio.com/docs/api/twiml/sms/twilio_request
var vote = args.parameter.Body;
var from = args.parameter.From;
//sample poll here for favorite football team in NYC
var actualVote;
switch (vote.toLowerCase()) {
case "a":
actualVote = 'Giants';
break;
case "b":
actualVote = 'Jets';
break;
default:
actualVote = 'Dont care';
}
SpreadsheetApp.openById(spreadsheetID).appendRow([from,actualVote,vote]);
return ContentService.createTextOutput('').setMimeType(ContentService.MimeType.TEXT);
//empty message sends no response. save a penny!
//other funn stuff - quickly translate
//return ContentService.createTextOutput(LanguageApp.translate(args.parameter.Body, "en", "es")).setMimeType(ContentService.MimeType.TEXT);
};
================================================
FILE: Twilio/readme.md
================================================
Click the image below for video with more details -
[](http://www.youtube.com/watch?v=j0wjM1Ds3lc&list=PL68F511F6E3C122EB)
================================================
FILE: WhiteHouseHackday/Code.gs
================================================
function onOpen(){
SpreadsheetApp.getActiveSpreadsheet()
.addMenu('We the people',[{name:'Search Petitions', functionName:'showUI'},
{name:'Load Signatures', functionName:'loadSignatures'},
null,
{name: 'Twitter trending', functionName:'twitter'}]);//future ideas
}
function showUI(){
var ui = HtmlService.createTemplateFromFile('ui').evaluate().setSandboxMode(HtmlService.SandboxMode.NATIVE).setHeight(550);
SpreadsheetApp.getActiveSpreadsheet().show(ui);
}
function returnDate(unix_timestamp){
//var unix_timestamp = '1370025951';
var date = new Date(unix_timestamp*1000);
//Logger.log(date);
return date;
}
function returnUnixtimestamp(dateString){
//var dateString = '2013-04-01';
var parts = dateString.match(/(\d+)/g);
var date = new Date(parts[0], parts[1]-1, parts[2]); // months are 0-based
var timestamp = date.getTime()/1000 + '';
return timestamp;
}
function createOrSetActiveSheet(sheetName){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheets = ss.getSheets();
var sheet;
for(var i = 0;i<sheets.length;i++){
sheet = sheets[i];
var currentSheetName = sheet.getSheetName();
if(sheetName===currentSheetName){
ss.setActiveSheet(sheet);
sheet.clear();
return sheet;
}
}
sheet = ss.insertSheet();
sheet.setName(sheetName);
ss.setActiveSheet(sheet);
return sheet;
}
//future ideas
function sendNightlyEmail(){
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Published Dashboard');
var chart = sheet.getCharts()[0];
MailApp.sendEmail(Session.getActiveUser().getEmail(), 'Daily petition report', 'See attached image', {name:'Sharing chart',attachments:[chart.getBlob()]});
}
/*
id: "51a8efdfa9a0b1c82c000006",
type: "petition",
title: "Condemn the actions taken against peaceful protesters in Istanbul Turkey.",
body: "There are gross human rights violations occurring in Istanbul, Turkey. Police have fired water cannons and smoke bombs into peaceful protests against the plans to put a development in the park Gezi in Taksim. http://www.bbc.co.uk/news/world-europe-22732139 http://www.nytimes.com/2013/06/01/world/europe/police-attack-protesters-in-istanbuls-taksim-square.html?pagewanted=all&_r=0 Signing this petition would help draw international attention to the issue. ",
issues: [
{
id: "20",
name: "Environment"
},
{
id: "28",
name: "Human Rights"
},
{
id: "175",
name: "Urban Policy"
}
],
signatureThreshold: 100000,
signatureCount: 2012,
signaturesNeeded: 97988,
url: "https://petitions.whitehouse.gov/petition/condemn-actions-taken-against-peaceful-protesters-istanbul-turkey/zDGtGCDZ",
deadline: 1372617951,
status: "open",
response: null,
created: 1370025951
*/
function getData(title,body,startdate,enddate,sig,status){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
sheet.clear();
var base_url = 'https://api.whitehouse.gov/v1/petitions.json?';
var additionParams = Utilities.formatString('title=%s&body=%s&signatureCountFloor=%s&status=%s&createdAfter=%s&createdBefore=%s'
,title,body,sig,status,returnUnixtimestamp(startdate),returnUnixtimestamp(enddate));
var getDataURL = base_url + 'limit=99&offset=0&'+additionParams;
Logger.log(getDataURL);
var dataResponse = UrlFetchApp.fetch(getDataURL).getContentText();
var dataObj = JSON.parse(dataResponse);
var headers = ['ID','Title','Body','Deadline','Status','Response','Created','Signature Count'];
var maxLetter = String.fromCharCode(64 + headers.length);
sheet.appendRow(headers);
sheet.getRange('A1:'+maxLetter+'1').setBackground('Grey').setFontStyle('oblique');
ss.setColumnWidth(2, 220);
ss.setColumnWidth(3, 625);
var rows = [];
for(var i = 0;dataObj.results && i<dataObj.results.length;i++){
var row = dataObj.results[i];
var responseFormula = "";
if (row.response) {
responseFormula = row.response.url;
}
rows.push(['=hyperlink("'+row.url+'","'+row.id+'")',row.title,row.body,returnDate(row.deadline),row.status,responseFormula,returnDate(row.created),row.signatureCount]);
}
var rowsCount = rows.length+1;
ss.getRange('A2:'+maxLetter+rowsCount).setValues(rows);
}
/*
{
id: "50d43ea16ce61c5910000008",
type: "signature",
name: "D. S.",
city: "Bethel",
state: "VT",
zip: "05032",
created: 1356086945
}
*/
function loadSignatures(){
var petitionId = SpreadsheetApp.getActiveRange().getValue();
var initialPageCount = 99; //because a default sheet has only 100 rows to start
var sheet = createOrSetActiveSheet(petitionId);
var base_url = 'https://api.whitehouse.gov/v1/petitions/'+petitionId+'/signatures.json?';
var getDataURL = base_url + 'limit='+initialPageCount+'&offset=0';
var dataResponse = UrlFetchApp.fetch(getDataURL).getContentText();
var dataObj = JSON.parse(dataResponse);
var headers = ['ID','Name','City','State','ZIP','Created'];
var maxLetter = String.fromCharCode(64 + headers.length);
sheet.appendRow(headers);
sheet.getRange('A1:'+maxLetter+'1').setBackground('Grey').setFontStyle('oblique');
var rows = [];
for(var i = 0;dataObj.results && i<dataObj.results.length;i++){
var row = dataObj.results[i];
rows.push([row.id,row.name,row.city,row.state,row.zip,returnDate(row.created)]);
}
var rowsCount = rows.length+1;
sheet.getRange('A2:'+maxLetter+rowsCount).setValues(rows);
}
================================================
FILE: WhiteHouseHackday/README.md
================================================
Title: Google Spreadsheet Integration
Developers: Arun Nagarajan from Google and Daniel McLaughlin from the Boston Globe
Description: Easily search and process petition data directly through Google Spreadsheets. This tool could be a framework to exploring other open APIs within an environment familiar to many researchers and journalists.
Code is very early and cleanup/refactoring needed ;)

================================================
FILE: WhiteHouseHackday/ui.html
================================================
<!doctype html>
<title>We the People</title>
<link rel=stylesheet
href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css">
<style>
#throbber {
left: 50%;
height: 48px;
margin-left: -24px;
margin-top: -24px;
position: absolute;
top: 50%;
width: 48px;
}
</style>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#throbber').hide();
$('#load').click(function(){
$('#configForm').hide();
$('#throbber').show();
google.script.run.withSuccessHandler(submissionSucceeded).withFailureHandler(alert).getData($('#title_keyword').val(),
$('#body_keyword').val(),
$('#start').val(),
$('#end').val(),
$('#sig_floor').val(),
$('#status').val());
});
});
function submissionSucceeded(){
$('#configForm').show();
$('#throbber').hide();
}
</script>
<img id=throbber src="//ssl.gstatic.com/music/ap/cec6433ac17a57a5ad3264da7b23e565/Spinner_48.gif"
alt="Loading...">
<legend><img src='https://petitions.whitehouse.gov/profiles/petitions/themes/fortyfour/images/featured_petitions.jpg'/> Search Petitions</legend>
<form id=configForm class=form-horizontal><fieldset>
<div class=control-group>
<label class=control-label for=title_keyword>Title keyword:</label>
<div class=controls><input id="title_keyword" class=input-large name=title_keyword type=text value=""></div>
</div>
<div class=control-group>
<label class=control-label for=body_keyword>Body Keyword:</label>
<div class=controls><input id="body_keyword" class=input-large name=body_keyword type=text value=""></div>
</div>
<div class=control-group>
<label class=control-label for=start>Start date:</label>
<div class=controls><input id="start" class=input-large name=start type=date value="2013-04-01"></div>
</div>
<div class=control-group>
<label class=control-label for=end>End date:</label>
<div class=controls><input id="end" class=input-large name=end type=date value="2013-04-30"></div>
</div>
<div class=control-group>
<label class=control-label for=sig_floor>Minumum Signatures:</label>
<div class=controls><input id="sig_floor" class=input-large name=sig_floor type=text value="0"></div>
</div>
<div class=control-group>
<label class=control-label for=metrics>Issue:</label>
<div class=controls><select id="issues" class=input-large name=issues>
<option value=""></option>
<option value="1">Agriculture</option>
<option value="2">Arts and Humanities</option>
<option value="3">Budget and Taxes</option>
<option value="4">Civil Rights and Liberties</option>
<option value="8">Climate Change</option>
<option value="9">Consumer Protections</option>
<option value="10">Criminal Justice and Law Enforcement</option>
<option value="12">Defense</option>
<option value="13">Disabilities</option>
<option value="16">Economy</option>
<option value="18">Education</option>
<option value="19">Energy</option>
<option value="20">Environment</option>
<option value="21">Family</option>
<option value="22">Firearms</option>
<option value="24">Foreign Policy</option>
<option value="25">Health Care</option>
<option value="26">Homeland Security and Disaster Relief</option>
<option value="27">Housing</option>
<option value="28">Human Rights</option>
<option value="29">Immigration</option>
<option value="30">Innovation</option>
<option value="97">Job Creation</option>
<option value="103">Labor</option>
<option value="109">Natural Resources</option>
<option value="115">Postal Service</option>
<option value="121">Poverty</option>
<option value="127">Regulatory Reform</option>
<option value="133">Rural Policy</option>
<option value="139">Science and Space Policy</option>
<option value="145">Social Security</option>
<option value="151">Small Business</option>
<option value="157">Technology and Telecommunications</option>
<option value="163">Trade</option>
<option value="169">Transportation and Infrastructure</option>
<option value="175">Urban Policy</option>
<option value="181">Veterans and Military Families</option>
<option value="187">Women's Issues</option>
<option value="193">Government Reform</option>
</select></div>
</div>
<div class=control-group>
<label class=control-label for=dim>Status:</label>
<div class=controls><select id="status" class=input-large name=status>
<option value=""></option>
<option value="open">Open</option>
<option value="closed">Closed</option>
<option value="pending response">Pending Response</option>
<option value="responded">Responded</option>
</select></div>
</div>
<div class=form-actions>
<button id=load class="btn btn-primary" type=submit>Load</button>
<button id=cancel class="btn btn-info" type=button onclick='google.script.host.close()'>Close</button>
</div>
</fieldset></form>
================================================
FILE: YouTube/CreateGDLCalendar.gs
================================================
function createCalendar(){
var API_KEY = 'YOU_API_KEY_HERE';
var cal = CalendarApp.createCalendar('GDL Calendar');
var url = 'https://www.googleapis.com/youtube/v3/activities?'
+'part=snippet&channelId=UC_x5XG1OV2P6uZZ5FSM9Ttw&maxResults=20&publishedBefore=2013-02-25T00:00:00.0Z'
+'&key='+API_KEY;
var response = UrlFetchApp.fetch(url).getContentText();
var responseObject = JSON.parse(response);
for(var i=0;responseObject.items && i<responseObject.items.length;i++){
var item = responseObject.items[i];
cal.createEvent(item.snippet.title, new Date(item.snippet.publishedAt), new Date(item.snippet.publishedAt));
}
Logger.log('https://www.google.com/calendar/embed?src='+cal.getId());
}
================================================
FILE: YouTube/YouTubeAnalytics.gs
================================================
/**
This is a spreadsheet bound script.
4 menus will be added. The first two show case one demo and the second two the other.
**/
//Import in Library ID = MGwgKN2Th03tJ5OdmlzB8KPxhMjh3Sh48
var _ = Underscore.load();
var API_KEY = 'YOU_API_KEY';
function onOpen() {
SpreadsheetApp.getActive().addMenu('YouTube', [
{name: 'Sync With Playlist', functionName: 'sync'},
{name: 'Update Views', functionName: 'update'},
{name: 'Do OAuth', functionName: 'getAuth'},
{name: 'Load Analytics', functionName: 'getData'}
]);
}
//Original Author - Eric Koleda
function sync() {
var ss = SpreadsheetApp.getActive();
var sheet = ss.getActiveSheet();
var existing = {};
var data = sheet.getDataRange().getValues();
var PLAYLIST_ID = Browser.inputBox('Please provide a playlist ID', 'Enter playlist ID here without quotes, eg - PLBC4C67EE5D2B46FB or EC3EF8DA2DEBF26B67', Browser.Buttons.OK);
_.each(data, function(row) {
existing[row[0]] = row;
});
var url = _.sprintf('https://www.googleapis.com/youtube/v3/playlistItems?key=%s&part=snippet&playlistId=%s&maxResults=50',
API_KEY, PLAYLIST_ID);
var result = JSON.parse(UrlFetchApp.fetch(url).getContentText());
_.each(result.items, function(item) {
var id = item.snippet.resourceId.videoId;
if (!existing[id]) {
sheet.appendRow([id, new Date(item.snippet.publishedAt), item.snippet.title, 'http://www.youtube.com/watch?v=' + id])
}
});
sheet.sort(2);
}
function update() {
var ss = SpreadsheetApp.getActive();
var sheet = ss.getActiveSheet();
var views = [];
var data = sheet.getDataRange().getValues();
var ids = _.map(data, function(row) {
return row[0];
});
var url = _.sprintf('https://www.googleapis.com/youtube/v3/videos?key=%s&part=statistics&id=%s',
API_KEY, ids.join(','));
var result = JSON.parse(UrlFetchApp.fetch(url).getContentText());
var viewCounts = {};
_.each(result.items, function(item) {
var id = item.id;
viewCounts[id] = item.statistics.viewCount;
});
var views = [];
_.each(data, function(row) {
views.push([viewCounts[row[0]]]);
});
sheet.getRange(1, 5, views.length).setValues(views);
}
function getAuth() {
var HTMLToOutput = '';
if(isTokenValid()){//if we already have a valid token, go off and start working with data
HTMLToOutput = '<html><h1>Already have token</h1></html>';
}
else {//we are starting from scratch or resetting
HTMLToOutput = "<html><h1>Lets start with oAuth</h1><a href='"+getURLForAuthorization()+"'>click here to start</a></html>";
}
SpreadsheetApp.getActiveSpreadsheet().show(HtmlService.createHtmlOutput(HTMLToOutput));
}
function doGet(e) {
var HTMLToOutput;
if(e.parameters.code){//if we get "code" as a parameter in, then this is a callback. we can make this more explicit
getAndStoreAccessToken(e.parameters.code);
HTMLToOutput
gitextract_o4r4wtx7/
├── .gitignore
├── Android/
│ ├── ClientCode/
│ │ ├── AndroidManifest.xml
│ │ ├── README
│ │ ├── gen/
│ │ │ └── com/
│ │ │ └── google/
│ │ │ └── android/
│ │ │ └── gcm/
│ │ │ └── demo/
│ │ │ └── app/
│ │ │ ├── BuildConfig.java
│ │ │ ├── Manifest.java
│ │ │ └── R.java
│ │ ├── libs/
│ │ │ ├── android-support-v4.jar
│ │ │ └── gcm.jar
│ │ ├── project.properties
│ │ ├── res/
│ │ │ ├── layout/
│ │ │ │ ├── main.xml
│ │ │ │ └── rowlayout.xml
│ │ │ ├── menu/
│ │ │ │ ├── inventory.xml
│ │ │ │ └── options_menu.xml
│ │ │ ├── values/
│ │ │ │ ├── dimens.xml
│ │ │ │ └── strings.xml
│ │ │ ├── values-sw600dp/
│ │ │ │ └── dimens.xml
│ │ │ └── values-sw720dp-land/
│ │ │ └── dimens.xml
│ │ └── src/
│ │ └── com/
│ │ └── google/
│ │ └── android/
│ │ └── gcm/
│ │ └── demo/
│ │ └── app/
│ │ ├── CommonUtilities.java
│ │ ├── DemoActivity.java
│ │ ├── GCMIntentService.java
│ │ ├── Item.java
│ │ ├── ServerUtilities.java
│ │ └── SimpleArrayAdapter.java
│ ├── GCM_Registrar_Script/
│ │ ├── code.gs
│ │ ├── scriptdb.gs
│ │ └── ui.html
│ ├── InventoryContentService.gs
│ ├── SharedDb.gs
│ ├── readme.md
│ └── track-and-notify.gs
├── ContentService/
│ ├── Addressbook-VCF/
│ │ ├── Code.gs
│ │ └── vcard_template.html
│ ├── Gmail-RSS/
│ │ ├── code.gs
│ │ └── rss.html
│ ├── Inventory-JSON-API-iOS/
│ │ ├── Inventory-iOS/
│ │ │ ├── Inventory/
│ │ │ │ ├── AppDelegate.h
│ │ │ │ ├── AppDelegate.m
│ │ │ │ ├── Inventory-Info.plist
│ │ │ │ ├── Inventory-Prefix.pch
│ │ │ │ ├── MasterViewController.h
│ │ │ │ ├── MasterViewController.m
│ │ │ │ ├── en.lproj/
│ │ │ │ │ ├── InfoPlist.strings
│ │ │ │ │ └── MainStoryboard.storyboard
│ │ │ │ └── main.m
│ │ │ └── Inventory.xcodeproj/
│ │ │ ├── project.pbxproj
│ │ │ ├── project.xcworkspace/
│ │ │ │ ├── contents.xcworkspacedata
│ │ │ │ └── xcuserdata/
│ │ │ │ └── anagarajan.xcuserdatad/
│ │ │ │ ├── UserInterfaceState.xcuserstate
│ │ │ │ └── WorkspaceSettings.xcsettings
│ │ │ └── xcuserdata/
│ │ │ └── anagarajan.xcuserdatad/
│ │ │ ├── xcdebugger/
│ │ │ │ └── Breakpoints.xcbkptlist
│ │ │ └── xcschemes/
│ │ │ ├── InventorySample.xcscheme
│ │ │ └── xcschememanagement.plist
│ │ └── code.gs
│ ├── Simple-JSONP/
│ │ ├── SimpleHtml-JSFiddle.html
│ │ └── code.gs
│ └── readme.md
├── DriveSDK/
│ ├── AppsScript.gs
│ ├── ChromeWebStoreVersion/
│ │ └── SimpleZipAndSend.gs
│ ├── FlowManager.gs
│ └── readme.md
├── FusionTables/
│ ├── RowUtilities.gs
│ ├── SampleDataExchange.gs
│ └── readme.md
├── GoogleAppsAdminAudit.gs
├── IO2013/
│ ├── Drive/
│ │ ├── Code.gs
│ │ ├── README.md
│ │ ├── SpreadsheetUtils.gs
│ │ └── ui.html
│ └── YouTubeAnalytics/
│ ├── Code.gs
│ ├── README.md
│ ├── oauth2.gs
│ ├── oauthsuccess.html
│ ├── twitter.gs
│ └── ui.html
├── NYTimesCampaignContribution.gs
├── README.md
├── SAP/
│ ├── Forms/
│ │ ├── Code.gs
│ │ └── product_template.html
│ ├── Gmail Schemas/
│ │ ├── Code.gs
│ │ └── mail_template.html
│ ├── README.md
│ └── Sheets/
│ ├── Code.gs
│ └── ui.html
├── Salesforce.com/
│ ├── OAuthAndUploadContactsToSalesforce.gs
│ ├── RowUtilities.gs
│ ├── ScanEmailToSalesforce.gs
│ └── readme.md
├── ScriptDbVisualizer/
│ ├── Code.gs
│ ├── ScriptDbConsole.html
│ └── readme.md
├── Twilio/
│ ├── MakePhoneCall/
│ │ ├── MakePhoneCall.gs
│ │ └── twiml.html
│ ├── RecieveSMS/
│ │ └── RecieveSMS.gs
│ └── readme.md
├── WhiteHouseHackday/
│ ├── Code.gs
│ ├── README.md
│ └── ui.html
└── YouTube/
├── CreateGDLCalendar.gs
├── YouTubeAnalytics.gs
└── readme.md
SYMBOL INDEX (41 symbols across 10 files)
FILE: Android/ClientCode/gen/com/google/android/gcm/demo/app/BuildConfig.java
class BuildConfig (line 4) | public final class BuildConfig {
FILE: Android/ClientCode/gen/com/google/android/gcm/demo/app/Manifest.java
class Manifest (line 10) | public final class Manifest {
class permission (line 11) | public static final class permission {
FILE: Android/ClientCode/gen/com/google/android/gcm/demo/app/R.java
class R (line 10) | public final class R {
class attr (line 11) | public static final class attr {
class dimen (line 13) | public static final class dimen {
class drawable (line 23) | public static final class drawable {
class id (line 27) | public static final class id {
class layout (line 39) | public static final class layout {
class menu (line 43) | public static final class menu {
class string (line 47) | public static final class string {
FILE: Android/ClientCode/src/com/google/android/gcm/demo/app/CommonUtilities.java
class CommonUtilities (line 25) | public final class CommonUtilities {
method displayMessage (line 62) | static void displayMessage(Context context, String message) {
FILE: Android/ClientCode/src/com/google/android/gcm/demo/app/DemoActivity.java
class DemoActivity (line 52) | public class DemoActivity extends ListActivity {
method onCreate (line 57) | @Override
class MyTask (line 119) | private class MyTask extends AsyncTask<Void, Void, Void> {
method doInBackground (line 121) | @Override
method onPostExecute (line 147) | @Override
method onCreateOptionsMenu (line 154) | @Override
method onOptionsItemSelected (line 161) | @Override
method onDestroy (line 193) | @Override
method checkNotNull (line 203) | private void checkNotNull(Object reference, String name) {
method onReceive (line 212) | @Override
FILE: Android/ClientCode/src/com/google/android/gcm/demo/app/GCMIntentService.java
class GCMIntentService (line 36) | public class GCMIntentService extends GCMBaseIntentService {
method GCMIntentService (line 41) | public GCMIntentService() {
method onRegistered (line 45) | @Override
method onUnregistered (line 52) | @Override
method onMessage (line 65) | @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
method onDeletedMessages (line 75) | @Override
method onError (line 84) | @Override
method onRecoverableError (line 90) | @Override
method generateNotification (line 102) | private static void generateNotification(Context context, String messa...
FILE: Android/ClientCode/src/com/google/android/gcm/demo/app/Item.java
class Item (line 3) | public class Item {
FILE: Android/ClientCode/src/com/google/android/gcm/demo/app/ServerUtilities.java
class ServerUtilities (line 41) | public final class ServerUtilities {
method register (line 52) | static boolean register(final Context context, final String regId) {
method unregister (line 102) | static void unregister(final Context context, final String regId) {
method post (line 133) | private static void post(String endpoint, Map<String, String> params)
FILE: Android/ClientCode/src/com/google/android/gcm/demo/app/SimpleArrayAdapter.java
class SimpleArrayAdapter (line 12) | public class SimpleArrayAdapter extends ArrayAdapter<Item> {
method SimpleArrayAdapter (line 16) | public SimpleArrayAdapter(Context context, ArrayList<Item> values) {
method getView (line 22) | @Override
FILE: ContentService/Inventory-JSON-API-iOS/Inventory-iOS/Inventory/MasterViewController.h
function interface (line 4) | interface MasterViewController : UITableViewController {
Condensed preview — 98 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (206K chars).
[
{
"path": ".gitignore",
"chars": 29,
"preview": "#ignore these files\n.DS_Store"
},
{
"path": "Android/ClientCode/AndroidManifest.xml",
"chars": 3950,
"preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<!--\n - Copyright 2012 Google Inc.\n -\n - Licensed under the Apache License, Ve"
},
{
"path": "Android/ClientCode/README",
"chars": 326,
"preview": "GCM demo app\n------------\n\n1.To create the project settings, type:\n\n android update project --name GCMDemo -p . --targe"
},
{
"path": "Android/ClientCode/gen/com/google/android/gcm/demo/app/BuildConfig.java",
"chars": 173,
"preview": "/** Automatically generated file. DO NOT MODIFY */\npackage com.google.android.gcm.demo.app;\n\npublic final class BuildCon"
},
{
"path": "Android/ClientCode/gen/com/google/android/gcm/demo/app/Manifest.java",
"chars": 652,
"preview": "/* AUTO-GENERATED FILE. DO NOT MODIFY.\n *\n * This class was automatically generated by the\n * aapt tool from the resour"
},
{
"path": "Android/ClientCode/gen/com/google/android/gcm/demo/app/R.java",
"chars": 3200,
"preview": "/* AUTO-GENERATED FILE. DO NOT MODIFY.\n *\n * This class was automatically generated by the\n * aapt tool from the resour"
},
{
"path": "Android/ClientCode/project.properties",
"chars": 563,
"preview": "# This file is automatically generated by Android Tools.\n# Do not modify this file -- YOUR CHANGES WILL BE ERASED!\n#\n# T"
},
{
"path": "Android/ClientCode/res/layout/main.xml",
"chars": 1169,
"preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<!--\n - Copyright 2012 Google Inc.\n -\n - Licensed under the Apache License, Ve"
},
{
"path": "Android/ClientCode/res/layout/rowlayout.xml",
"chars": 772,
"preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n andr"
},
{
"path": "Android/ClientCode/res/menu/inventory.xml",
"chars": 253,
"preview": "<menu xmlns:android=\"http://schemas.android.com/apk/res/android\" >\n\n <item\n android:id=\"@+id/action_settings\"\n"
},
{
"path": "Android/ClientCode/res/menu/options_menu.xml",
"chars": 1778,
"preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<!--\n - Copyright 2012 Google Inc.\n -\n - Licensed under the Apache License, Ve"
},
{
"path": "Android/ClientCode/res/values/dimens.xml",
"chars": 212,
"preview": "<resources>\n\n <!-- Default screen margins, per the Android Design guidelines. -->\n <dimen name=\"activity_horizonta"
},
{
"path": "Android/ClientCode/res/values/strings.xml",
"chars": 2328,
"preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<!--\n - Copyright 2012 Google Inc.\n -\n - Licensed under the Apache License, Ve"
},
{
"path": "Android/ClientCode/res/values-sw600dp/dimens.xml",
"chars": 195,
"preview": "<resources>\n\n <!--\n Customize dimensions originally defined in res/values/dimens.xml (such as\n screen"
},
{
"path": "Android/ClientCode/res/values-sw720dp-land/dimens.xml",
"chars": 268,
"preview": "<resources>\n\n <!--\n Customize dimensions originally defined in res/values/dimens.xml (such as\n screen"
},
{
"path": "Android/ClientCode/src/com/google/android/gcm/demo/app/CommonUtilities.java",
"chars": 1938,
"preview": "/*\n * Copyright 2012 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not us"
},
{
"path": "Android/ClientCode/src/com/google/android/gcm/demo/app/DemoActivity.java",
"chars": 6772,
"preview": "/*\n * Copyright 2012 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not us"
},
{
"path": "Android/ClientCode/src/com/google/android/gcm/demo/app/GCMIntentService.java",
"chars": 4702,
"preview": "/*\n * Copyright 2012 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not us"
},
{
"path": "Android/ClientCode/src/com/google/android/gcm/demo/app/Item.java",
"chars": 96,
"preview": "package com.google.android.gcm.demo.app;\n\npublic class Item {\n\tString name;\n String count;\n}\n"
},
{
"path": "Android/ClientCode/src/com/google/android/gcm/demo/app/ServerUtilities.java",
"chars": 6141,
"preview": "/*\n * Copyright 2012 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not us"
},
{
"path": "Android/ClientCode/src/com/google/android/gcm/demo/app/SimpleArrayAdapter.java",
"chars": 1117,
"preview": "package com.google.android.gcm.demo.app;\n\nimport java.util.ArrayList;\n\nimport android.content.Context;\nimport android.vi"
},
{
"path": "Android/GCM_Registrar_Script/code.gs",
"chars": 469,
"preview": "function doGet() {\n return HtmlService.createHtmlOutputFromFile('ui');\n}\n\n\n//import shared db library\n//used the shared"
},
{
"path": "Android/GCM_Registrar_Script/scriptdb.gs",
"chars": 1647,
"preview": "var db = SharedDb.getDb();\n\n\nfunction saveObjToDb(obj){\n try{\n var savedObj = db.save(obj);\n return \"Saved ID - \""
},
{
"path": "Android/GCM_Registrar_Script/ui.html",
"chars": 4126,
"preview": "<html>\n <style>\n pre {outline: 1px solid #ccc; padding: 5px; margin: 5px; }\n .string { color: green; }\n .numbe"
},
{
"path": "Android/InventoryContentService.gs",
"chars": 4516,
"preview": "function doGet() {\n var ss = SpreadsheetApp.openById('YOUR_SS_ID');\n var sheet = ss.getSheets()[0];\n\n // Get the rang"
},
{
"path": "Android/SharedDb.gs",
"chars": 935,
"preview": "var db = ScriptDb.getMyDb();\n\nfunction getDb(){\n return db;\n}\n\nfunction sendGCM(msg){\n msg = msg || 'hello world!'; /"
},
{
"path": "Android/readme.md",
"chars": 187,
"preview": "Click the image below for video with more details - \n\n[]("
},
{
"path": "Android/track-and-notify.gs",
"chars": 207,
"preview": "//create an onEdit trigger for this! in a spreadsheet bound script\n//import shared db library\nfunction sendNotification("
},
{
"path": "ContentService/Addressbook-VCF/Code.gs",
"chars": 305,
"preview": "function doGet() {\n var contact = ContactsApp.getContact('youremail@gmail.com'); \n \n var t = HtmlService.createTempl"
},
{
"path": "ContentService/Addressbook-VCF/vcard_template.html",
"chars": 809,
"preview": "BEGIN:VCARD\nFN:<?= contact.getFullName(); ?>\nTITLE:General Manager\nORG:<?= contact.getFullName(); ?>;North American Divi"
},
{
"path": "ContentService/Gmail-RSS/code.gs",
"chars": 198,
"preview": "function doGet() { \n var content = HtmlService.createTemplateFromFile('rss').evaluate().getContent();\n return Content"
},
{
"path": "ContentService/Gmail-RSS/rss.html",
"chars": 508,
"preview": "<rss version = \"2.0\">\n<channel>\n <title>Gmail Feed</title>\n <? var threads = GmailApp.getInboxThreads();\n var mess"
},
{
"path": "ContentService/Inventory-JSON-API-iOS/Inventory-iOS/Inventory/AppDelegate.h",
"chars": 141,
"preview": "#import <UIKit/UIKit.h>\n\n@interface AppDelegate : UIResponder <UIApplicationDelegate>\n\n@property (strong, nonatomic) UIW"
},
{
"path": "ContentService/Inventory-JSON-API-iOS/Inventory-iOS/Inventory/AppDelegate.m",
"chars": 1973,
"preview": "#import \"AppDelegate.h\"\n\n@implementation AppDelegate\n\n@synthesize window = _window;\n\n- (BOOL)application:(UIApplication "
},
{
"path": "ContentService/Inventory-JSON-API-iOS/Inventory-iOS/Inventory/Inventory-Info.plist",
"chars": 1268,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/P"
},
{
"path": "ContentService/Inventory-JSON-API-iOS/Inventory-iOS/Inventory/Inventory-Prefix.pch",
"chars": 223,
"preview": "#import <Availability.h>\n\n#ifndef __IPHONE_5_0\n#warning \"This project uses features only available in iOS SDK 5.0 and la"
},
{
"path": "ContentService/Inventory-JSON-API-iOS/Inventory-iOS/Inventory/MasterViewController.h",
"chars": 170,
"preview": "\n#import <UIKit/UIKit.h>\n\n@interface MasterViewController : UITableViewController {\n NSArray *Items;\n}\n\n- (void)fetch"
},
{
"path": "ContentService/Inventory-JSON-API-iOS/Inventory-iOS/Inventory/MasterViewController.m",
"chars": 2676,
"preview": "#import \"MasterViewController.h\"\n\n@implementation MasterViewController\n\n\n- (void)awakeFromNib\n{\n [super awakeFromNib]"
},
{
"path": "ContentService/Inventory-JSON-API-iOS/Inventory-iOS/Inventory/en.lproj/InfoPlist.strings",
"chars": 45,
"preview": "/* Localized versions of Info.plist keys */\n\n"
},
{
"path": "ContentService/Inventory-JSON-API-iOS/Inventory-iOS/Inventory/en.lproj/MainStoryboard.storyboard",
"chars": 6808,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n<document type=\"com.apple.InterfaceBuilder3.CocoaTouch.Storyboard"
},
{
"path": "ContentService/Inventory-JSON-API-iOS/Inventory-iOS/Inventory/main.m",
"chars": 207,
"preview": "#import <UIKit/UIKit.h>\n\n#import \"AppDelegate.h\"\n\nint main(int argc, char *argv[])\n{\n @autoreleasepool {\n retu"
},
{
"path": "ContentService/Inventory-JSON-API-iOS/Inventory-iOS/Inventory.xcodeproj/project.pbxproj",
"chars": 12102,
"preview": "// !$*UTF8*$!\n{\n\tarchiveVersion = 1;\n\tclasses = {\n\t};\n\tobjectVersion = 46;\n\tobjects = {\n\n/* Begin PBXBuildFile section *"
},
{
"path": "ContentService/Inventory-JSON-API-iOS/Inventory-iOS/Inventory.xcodeproj/project.xcworkspace/contents.xcworkspacedata",
"chars": 154,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Workspace\n version = \"1.0\">\n <FileRef\n location = \"self:Inventory.xcode"
},
{
"path": "ContentService/Inventory-JSON-API-iOS/Inventory-iOS/Inventory.xcodeproj/project.xcworkspace/xcuserdata/anagarajan.xcuserdatad/WorkspaceSettings.xcsettings",
"chars": 332,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/P"
},
{
"path": "ContentService/Inventory-JSON-API-iOS/Inventory-iOS/Inventory.xcodeproj/xcuserdata/anagarajan.xcuserdatad/xcdebugger/Breakpoints.xcbkptlist",
"chars": 91,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Bucket\n type = \"1\"\n version = \"1.0\">\n</Bucket>\n"
},
{
"path": "ContentService/Inventory-JSON-API-iOS/Inventory-iOS/Inventory.xcodeproj/xcuserdata/anagarajan.xcuserdatad/xcschemes/InventorySample.xcscheme",
"chars": 3159,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Scheme\n LastUpgradeVersion = \"0450\"\n version = \"1.3\">\n <BuildAction\n "
},
{
"path": "ContentService/Inventory-JSON-API-iOS/Inventory-iOS/Inventory.xcodeproj/xcuserdata/anagarajan.xcuserdatad/xcschemes/xcschememanagement.plist",
"chars": 487,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/P"
},
{
"path": "ContentService/Inventory-JSON-API-iOS/code.gs",
"chars": 6815,
"preview": "function doGet() {\n var ss = SpreadsheetApp.openById('0AiFUpEyZ-UKzdElxM3NpbFI4QUJwdmxqSXVlSjJmNmc');\n var sheet = ss."
},
{
"path": "ContentService/Simple-JSONP/SimpleHtml-JSFiddle.html",
"chars": 510,
"preview": "<!DOCTYPE html>\n<html>\n \t<head>\n \t<meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\"/>\n \t<script sr"
},
{
"path": "ContentService/Simple-JSONP/code.gs",
"chars": 235,
"preview": "function doGet(request) {\n var result = 'hello world';\n var content = request.parameters.prefix + '(' +JSON.stringify("
},
{
"path": "ContentService/readme.md",
"chars": 187,
"preview": "Click the image below for video with more details - \n\n[]("
},
{
"path": "DriveSDK/AppsScript.gs",
"chars": 1532,
"preview": "//look for the first mtg right now in the user's calendar from now till next 2 hours\nfunction createMeetingNotes() {\n v"
},
{
"path": "DriveSDK/ChromeWebStoreVersion/SimpleZipAndSend.gs",
"chars": 836,
"preview": "//this is the source code for \"Zip and send\" app on the Chrome Web Store you can install into your Google Drive\nfunction"
},
{
"path": "DriveSDK/FlowManager.gs",
"chars": 2517,
"preview": "var AUTHORIZE_URL = 'https://accounts.google.com/o/oauth2/auth'; \nvar TOKEN_URL = 'https://accounts.google.com/o/oauth2/"
},
{
"path": "DriveSDK/readme.md",
"chars": 187,
"preview": "Click the image below for video with more details - \n\n[]("
},
{
"path": "FusionTables/RowUtilities.gs",
"chars": 4982,
"preview": "// getRowsData iterates row by row in the input range and returns an array of objects.\n// Each object contains all the d"
},
{
"path": "FusionTables/SampleDataExchange.gs",
"chars": 5365,
"preview": "function onInstall(){\n onOpen();\n}\n\nvar ss = SpreadsheetApp.getActiveSpreadsheet();\n\nfunction onOpen() {\n var menuEntr"
},
{
"path": "FusionTables/readme.md",
"chars": 187,
"preview": "Click the image below for video with more details - \n\n[]("
},
{
"path": "GoogleAppsAdminAudit.gs",
"chars": 4182,
"preview": "function doGet(e) {\n var HTMLToOutput;\n if(e.parameters.code){//if we get \"code\" as a parameter in, then this is a cal"
},
{
"path": "IO2013/Drive/Code.gs",
"chars": 5035,
"preview": "function doGet(e) {\n var HTMLToOutput;\n if(e.parameter.state){\n var state = JSON.parse(e.parameter.state);\n if(s"
},
{
"path": "IO2013/Drive/README.md",
"chars": 296,
"preview": "Companion code for Google IO 2013 session - Integrate Google Drive with Google Apps Script\n\nhttps://developers.google.co"
},
{
"path": "IO2013/Drive/SpreadsheetUtils.gs",
"chars": 6735,
"preview": "//https://developers.google.com/apps-script/storing_data_spreadsheets#reading\n\n\n// getRowsData iterates row by row in th"
},
{
"path": "IO2013/Drive/ui.html",
"chars": 1359,
"preview": "<!doctype html>\n<title>Google Drive Quiz Manager</title>\n\n<link rel=stylesheet\nhref=\"//netdna.bootstrapcdn.com/twitter-b"
},
{
"path": "IO2013/YouTubeAnalytics/Code.gs",
"chars": 2574,
"preview": "function onOpen(){\n SpreadsheetApp.getActiveSpreadsheet()\n .addMenu('YouTube Analytics',[{name:'Ad hoc report', functi"
},
{
"path": "IO2013/YouTubeAnalytics/README.md",
"chars": 409,
"preview": "Companion code for Google IO 2013 session - Ad Hoc Analysis with Google Apps Script and YouTube Analytics API\n\nhttps://d"
},
{
"path": "IO2013/YouTubeAnalytics/oauth2.gs",
"chars": 3738,
"preview": "var AUTHORIZE_URL = 'https://accounts.google.com/o/oauth2/auth'; //step 1. we can actually start directly here if that i"
},
{
"path": "IO2013/YouTubeAnalytics/oauthsuccess.html",
"chars": 462,
"preview": "<!doctype html>\n<title>YouTube Analytics</title>\n\n<link rel=stylesheet href=\"//netdna.bootstrapcdn.com/twitter-bootstrap"
},
{
"path": "IO2013/YouTubeAnalytics/twitter.gs",
"chars": 1276,
"preview": "function twitter(){\n var oauthCfg = UrlFetchApp.addOAuthService('twitter');\n oauthCfg.setAccessTokenUrl('https://api.t"
},
{
"path": "IO2013/YouTubeAnalytics/ui.html",
"chars": 3594,
"preview": "<!doctype html>\n<title>YouTube Analytics</title>\n\n<link rel=stylesheet\nhref=\"//netdna.bootstrapcdn.com/twitter-bootstrap"
},
{
"path": "NYTimesCampaignContribution.gs",
"chars": 593,
"preview": "function getData(){\n var API_KEY = 'YOUR_API_KEY_HERE';\n var url = 'http://api.nytimes.com/svc/elections/us/v3/finance"
},
{
"path": "README.md",
"chars": 436,
"preview": "GoogleAppsScript\n================\n\nSample code for Google Apps Script. \nThese are not official Google samples. These are"
},
{
"path": "SAP/Forms/Code.gs",
"chars": 1791,
"preview": "function onFormSubmit(e) {\n var myObject = {};\n var itemResponses = e.response.getItemResponses();\n for (var j = 0; "
},
{
"path": "SAP/Forms/product_template.html",
"chars": 1179,
"preview": "<atom:entry xmlns:atom=\"http://www.w3.org/2005/Atom\" xmlns:m=\"http://schemas.microsoft.com/ado/2007/08/dataservices/meta"
},
{
"path": "SAP/Gmail Schemas/Code.gs",
"chars": 235,
"preview": "function testSchemas() {\n var htmlBody = HtmlService.createHtmlOutputFromFile('mail_template').getContent();\n\n GmailAp"
},
{
"path": "SAP/Gmail Schemas/mail_template.html",
"chars": 939,
"preview": "<html>\n <head>\n <script type=\"application/ld+json\">\n{\n \"@context\": \"http://schema.org\",\n \"@type\": \"ParcelDelivery\""
},
{
"path": "SAP/README.md",
"chars": 757,
"preview": "SAP Demos\n================\n\nSample SAP integrations. You'll need to create a [sample SAP account](http://scn.sap.com/doc"
},
{
"path": "SAP/Sheets/Code.gs",
"chars": 6322,
"preview": "//sample instance\n//http://scn.sap.com/docs/DOC-40986\n\n\nfunction onOpen(){\n SpreadsheetApp.getActiveSpreadsheet()\n .ad"
},
{
"path": "SAP/Sheets/ui.html",
"chars": 3592,
"preview": "<!--\nThis is an incomplete place holder for just showing the UI\n\n-->\n\n<link rel=stylesheet\nhref=\"//netdna.bootstrapcdn.c"
},
{
"path": "Salesforce.com/OAuthAndUploadContactsToSalesforce.gs",
"chars": 4774,
"preview": "function onInstall(){\n onOpen();\n}\n\nfunction onOpen() {\n var ss = SpreadsheetApp.getActiveSpreadsheet();\n var menuEnt"
},
{
"path": "Salesforce.com/RowUtilities.gs",
"chars": 4983,
"preview": "// getRowsData iterates row by row in the input range and returns an array of objects.\n// Each object contains all the d"
},
{
"path": "Salesforce.com/ScanEmailToSalesforce.gs",
"chars": 1601,
"preview": "\nfunction scanEmail(){\n //for performance sake, we'll scan top 3 threads for now. \n //a more intelligent trigger would"
},
{
"path": "Salesforce.com/readme.md",
"chars": 187,
"preview": "Click the image below for video with more details - \n\n[]("
},
{
"path": "ScriptDbVisualizer/Code.gs",
"chars": 1736,
"preview": "var db = ScriptDb.getMyDb();\n\nfunction doGet() {\n return HtmlService.createHtmlOutputFromFile('ScriptDbConsole');\n}\n\nfu"
},
{
"path": "ScriptDbVisualizer/ScriptDbConsole.html",
"chars": 4127,
"preview": "<html>\n <style>\n pre {outline: 1px solid #ccc; padding: 5px; margin: 5px; }\n .string { color: green; }\n .numbe"
},
{
"path": "ScriptDbVisualizer/readme.md",
"chars": 188,
"preview": "Click the image below for video with more details - \n\n[]("
},
{
"path": "Twilio/MakePhoneCall/MakePhoneCall.gs",
"chars": 2351,
"preview": "var ACCOUNT_SID = 'ACd4e8e6872e581bf4cf560d37fb9059db';\nvar ACCOUNT_TOKEN = 'YOUR_TOKEN_HERE';\n\n//This is a spreadsheet "
},
{
"path": "Twilio/MakePhoneCall/twiml.html",
"chars": 145,
"preview": "<Response>\n <Say voice=\"woman\" language=\"en-us\"><?=msg?></Say>\n <Play loop=\"1\">https://api.twilio.com/cowbell.mp"
},
{
"path": "Twilio/RecieveSMS/RecieveSMS.gs",
"chars": 1095,
"preview": "//This is deployed as a web app and in the Twilio interface you'll point incoming SMS to the deployed URL\n//deploy it to"
},
{
"path": "Twilio/readme.md",
"chars": 188,
"preview": "Click the image below for video with more details - \n\n[]("
},
{
"path": "WhiteHouseHackday/Code.gs",
"chars": 5497,
"preview": "function onOpen(){\n SpreadsheetApp.getActiveSpreadsheet()\n .addMenu('We the people',[{name:'Search Petitions', functio"
},
{
"path": "WhiteHouseHackday/README.md",
"chars": 527,
"preview": "Title: Google Spreadsheet Integration\n\nDevelopers: Arun Nagarajan from Google and Daniel McLaughlin from the Boston Glob"
},
{
"path": "WhiteHouseHackday/ui.html",
"chars": 5319,
"preview": "<!doctype html>\n<title>We the People</title>\n\n<link rel=stylesheet\nhref=\"//netdna.bootstrapcdn.com/twitter-bootstrap/2.3"
},
{
"path": "YouTube/CreateGDLCalendar.gs",
"chars": 749,
"preview": "function createCalendar(){\n var API_KEY = 'YOU_API_KEY_HERE';\n var cal = CalendarApp.createCalendar('GDL Calendar');\n "
},
{
"path": "YouTube/YouTubeAnalytics.gs",
"chars": 7122,
"preview": "/**\nThis is a spreadsheet bound script. \n4 menus will be added. The first two show case one demo and the second two the "
},
{
"path": "YouTube/readme.md",
"chars": 187,
"preview": "Click the image below for video with more details - \n\n[]("
}
]
// ... and 3 more files (download for full content)
About this extraction
This page contains the full source code of the entaq/GoogleAppsScript GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 98 files (185.6 KB), approximately 52.0k tokens, and a symbol index with 41 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.