PageRenderTime 52ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/sample/flash/SampleApp.as

http://opensocial-actionscript-client.googlecode.com/
ActionScript | 465 lines | 320 code | 69 blank | 76 comment | 15 complexity | 23673d1af4653b29214487ba7c5fc949 MD5 | raw file
  1. /*
  2. * Licensed to the Apache Software Foundation (ASF) under one
  3. * or more contributor license agreements. See the NOTICE file
  4. * distributed with this work for additional information
  5. * regarding copyright ownership. The ASF licenses this file
  6. * to you under the Apache License, Version 2.0 (the
  7. * "License"); you may not use this file except in compliance
  8. * with the License. You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing,
  13. * software distributed under the License is distributed on an
  14. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15. * KIND, either express or implied. See the License for the
  16. * specific language governing permissions and limitations
  17. * under the License.
  18. */
  19. package {
  20. import flash.display.Loader;
  21. import flash.display.MovieClip;
  22. import flash.display.Sprite;
  23. import flash.events.Event;
  24. import flash.events.MouseEvent;
  25. import flash.net.URLRequest;
  26. import flash.text.TextField;
  27. import flash.text.TextFormat;
  28. import org.opensocial.client.base.*;
  29. import org.opensocial.client.core.*;
  30. import org.opensocial.client.features.*;
  31. import org.opensocial.client.jswrapper.*;
  32. import org.opensocial.client.util.*;
  33. /**
  34. * Sample Application using the OpenSocial AS3 Client Lirary in Adobe Flash IDE.
  35. * Build the SampleApp.fla in Adobe Flash IDE to swf file and it works with the gadget spec XML
  36. * (//sample/SampleApp.xml).
  37. *
  38. * <p>
  39. * Usage:<br>
  40. * 1. Create a JsWrapperClient instance.
  41. * <br>
  42. * 2. Add a eventhandler for READY event and call the start() method.
  43. * <br>
  44. * 3. When the client is ready, use the any of the <code>AsyncRequest</code> objects and
  45. * <code>SyncHelper</code> objects to interact with OpenSocial API. All these are located in
  46. * <code>org.opensocial.client.features</code> package.
  47. * <br>
  48. * </p>
  49. *
  50. * @author yiziwu@google.com (Yizi Wu)
  51. * @author chaowang@google.com (Jacky Wang)
  52. */
  53. public class SampleApp extends MovieClip {
  54. private var logger:Logger = new Logger(SampleApp);
  55. private var client:JsWrapperClient;
  56. private var helper:SyncHelper;
  57. public function SampleApp() {
  58. prepareBtns();
  59. // Create the output box for information displaying
  60. var printer:TextFieldPrinter = new TextFieldPrinter(2, 120, 500, 330);
  61. addChild(printer);
  62. Logger.initialize(printer);
  63. // Initialize Client and start
  64. client = new JsWrapperClient("opensocial.flash");
  65. client.addEventListener(OpenSocialClientEvent.CLIENT_READY, onReady);
  66. client.start();
  67. logger.log(new Date());
  68. helper = new SyncHelper(client);
  69. }
  70. private function onReady(event:OpenSocialClientEvent):void {
  71. logger.log("Domain: " + helper.getDomain());
  72. logger.log("ContainerDomain: " + helper.getContainerDomain());
  73. logger.log("CurrentView: " + helper.getCurrentView());
  74. logger.log("Client Ready.");
  75. }
  76. // -------------------------------------------------------------
  77. // Demo Actions
  78. // -------------------------------------------------------------
  79. // ----------------- Fetch Me ------------------
  80. private function fetchMe():void {
  81. var req:AsyncDataRequest = new AsyncDataRequest(
  82. Feature.PEOPLE_GET,
  83. new PeopleRequestOptions()
  84. .setUserId("@me")
  85. .setGroupId("@self"));
  86. req.addEventListener(ResponseItemEvent.COMPLETE, fetchMeEventHandler);
  87. req.send(client);
  88. }
  89. private function fetchMeEventHandler(event:ResponseItemEvent):void {
  90. var p:Person = event.response.getData();
  91. logger.log(p.getDisplayName());
  92. drawPerson(p, 0);
  93. }
  94. // ----------------- Fetch Friends ------------------
  95. private function fetchFriends():void {
  96. var req:AsyncDataRequest = new AsyncDataRequest(
  97. Feature.PEOPLE_GET,
  98. new PeopleRequestOptions()
  99. .setUserId("@me")
  100. .setGroupId("@friends")
  101. .setCount(5)
  102. .setStartIndex(0));
  103. req.addEventListener(ResponseItemEvent.COMPLETE, fetchFriendsEventHandler);
  104. req.send(client);
  105. }
  106. private function fetchFriendsEventHandler(event:ResponseItemEvent):void {
  107. var c:Collection = event.response.getData();
  108. logger.log(c.toDebugString());
  109. var arr:Array = c.getArray();
  110. for (var i:int = 0; i < arr.length; i++) {
  111. var p:Person = arr[i];
  112. logger.log(p.getDisplayName());
  113. drawPerson(p, i + 1);
  114. }
  115. if (c.getRemainingSize() > 0) {
  116. var req:AsyncDataRequest = event.target as AsyncDataRequest;
  117. (req.getOptions() as PeopleRequestOptions).setStartIndex(c.getNextOffset());
  118. req.send(client);
  119. }
  120. }
  121. // ----------------- Send Message ------------------
  122. private function sendMessage():void {
  123. // the change for myspace. myspace is not support Message object's type equal to null.
  124. var message:Message = Message.newInstance("Hello World...", "My new message.", Message.Type.NOTIFICATION);
  125. logger.log(message.toRawObject());
  126. var req:AsyncDataRequest = new AsyncDataRequest(
  127. Feature.REQUEST_SEND_MESSAGE,
  128. new UIRequestOptions()
  129. .setRecipientIds(["@viewer"])
  130. .setMessage(message));
  131. req.addEventListener(ResponseItemEvent.COMPLETE, sendMessageEventHandler);
  132. req.addEventListener(ResponseItemEvent.ERROR, sendMessageEventErrorHandler);
  133. req.send(client);
  134. }
  135. private function sendMessageEventHandler(event:ResponseItemEvent):void {
  136. logger.log("msg sent.");
  137. }
  138. private function sendMessageEventErrorHandler(event:ResponseItemEvent):void {
  139. logger.log("msg sending failed: " + event.response.getErrorMessage());
  140. }
  141. // ----------------- Create Activity ------------------
  142. private function createActivity():void {
  143. var activity:Activity = Activity.newInstance("My new activity!", "Hello World...");
  144. // the change for myspace. myspace's Activity object need set 'TITLE_ID'.
  145. logger.log(activity.toRawObject());
  146. var req:AsyncDataRequest = new AsyncDataRequest(
  147. Feature.REQUEST_CREATE_ACTIVITY,
  148. new UIRequestOptions()
  149. .setActivity(activity));
  150. req.addEventListener(ResponseItemEvent.COMPLETE, createActivityEventHandler);
  151. req.addEventListener(ResponseItemEvent.ERROR, createActivityEventErrorHandler);
  152. req.send(client);
  153. }
  154. private function createActivityEventHandler(event:ResponseItemEvent):void {
  155. logger.log("activity created");
  156. }
  157. private function createActivityEventErrorHandler(event:ResponseItemEvent):void {
  158. logger.log("activity creation failed: " + event.response.getErrorMessage());
  159. }
  160. // ----------------- Make Request ------------------
  161. private function makeRequest():void {
  162. var req:ProxiedRequest = new ProxiedRequest(
  163. "http://www.google.com/crossdomain.xml",
  164. new ProxiedRequestOptions()
  165. .setContentType(GadgetsIo.ContentType.TEXT));
  166. req.addEventListener(ProxiedRequestEvent.COMPLETE, makeRequestEventHandler);
  167. req.addEventListener(ProxiedRequestEvent.ERROR, makeRequestEventErrorHandler);
  168. req.send(client);
  169. }
  170. private function makeRequestEventHandler(event:ProxiedRequestEvent):void {
  171. logger.log(event.response.getData());
  172. }
  173. private function makeRequestEventErrorHandler(event:ProxiedRequestEvent):void {
  174. logger.log("make request failed: " + event.response.getRC() + "|" +
  175. event.response.getText());
  176. }
  177. // ----------------- Call RPC ------------------
  178. private function callRpc():void {
  179. // To use this, you need to first register the rpc service with name "srv-parent" on
  180. // container side. If you are using firefox+firebug and looking on a shindig container,
  181. // before clicking the "Call Rpc" button in the flash to call this method, copy+paste the
  182. // following codes to the console window:
  183. //
  184. // <code>
  185. // gadgets.rpc.register("srv-parent",function(){console.log(arguments);return "'srv-parent' returned."});
  186. // </code>
  187. var req:RPCRequest = new RPCRequest(null, "srv-parent", "abc", 123, {'xyz':456});
  188. req.addEventListener(RPCRequestEvent.RPC_CALLBACK, callRpcEventHandler);
  189. req.send(client);
  190. }
  191. private function callRpcEventHandler(event:RPCRequestEvent):void {
  192. logger.log("--- invoked by the returning of 'srv-parent' ---");
  193. logger.log(event.returnValue);
  194. }
  195. // ----------------- Register RPC Service ------------------
  196. private function registerService():void {
  197. // To use this, you need to make a rpc call to "srv-app" from container side. If you are
  198. // using firefox+firebug and shindig container, click the "Register Srv" button in the
  199. // flash to call this method, then copy+paste the following codes to the console window
  200. // to test the rpc.
  201. // ("remote_iframe_0" assumes this flash app is the first app on the page)
  202. //
  203. // <code>
  204. // gadgets.rpc.call("remote_iframe_0","srv-app",function(r){console.log(r);},"abc", 123, {'xyz':456});
  205. // </code>
  206. var srv:RPCService = new RPCService("srv-app");
  207. srv.register(client);
  208. srv.addEventListener(RPCServiceEvent.RPC_SERVICE, serviceEventHandler);
  209. }
  210. private function serviceEventHandler(event:RPCServiceEvent):void {
  211. logger.log("--- invoked by 'srv-app' get called ---");
  212. logger.log(event.params);
  213. event.callback("'srv-app' returned.");
  214. }
  215. // ----------------- Share App ------------------
  216. private function shareApp(p:Person):void {
  217. // To use this, you need First run "Fetch Friends" or "Fetch Me" and then click People.
  218. var message:Message = Message.newInstance("Hey [recipient]! [sender] wants you to add [app]. It's way awesome!", "A fun way to view your profile!");
  219. logger.log(message.toRawObject());
  220. var req:AsyncDataRequest = new AsyncDataRequest(
  221. Feature.REQUEST_SHARE_APP,
  222. new UIRequestOptions()
  223. .setRecipientIds([p.getId()])
  224. .setReason(message));
  225. req.addEventListener(ResponseItemEvent.COMPLETE, shareAppEventHandler);
  226. req.addEventListener(ResponseItemEvent.ERROR, shareAppEventErrorHandler);
  227. req.send(client);
  228. }
  229. private function shareAppEventHandler(event:ResponseItemEvent):void {
  230. logger.log("msg sent.");
  231. }
  232. private function shareAppEventErrorHandler(event:ResponseItemEvent):void {
  233. logger.log("msg sending failed: " + event.response.getErrorMessage());
  234. }
  235. // ----------------- Batch Request------------------
  236. private function batchRequest():void {
  237. var batch:BatchRequest = new BatchRequest();
  238. var req:AsyncDataRequest = new AsyncDataRequest(
  239. Feature.PEOPLE_GET,
  240. new PeopleRequestOptions()
  241. .setUserId("@me")
  242. .setGroupId("@self"));
  243. req.addEventListener(ResponseItemEvent.COMPLETE, batchFetchMeEventHandler);
  244. req.addEventListener(ResponseItemEvent.ERROR, batchFetchMeEventErrorHandler);
  245. batch.add(req, "meProfile");
  246. req = new AsyncDataRequest(
  247. Feature.PEOPLE_GET,
  248. new PeopleRequestOptions()
  249. .setUserId("@me")
  250. .setGroupId("@friends")
  251. .setCount(2)
  252. .setStartIndex(0));
  253. req.addEventListener(ResponseItemEvent.COMPLETE, batchFetchFriendsEventHandler);
  254. req.addEventListener(ResponseItemEvent.ERROR, batchFetchFriendsEventErrorHandler);
  255. batch.add(req, "friendList");
  256. batch.addEventListener(ResponseItemEvent.COMPLETE, batchDataRequestEventHandler);
  257. batch.addEventListener(ResponseItemEvent.ERROR, batchDataRequestErrorHandler);
  258. batch.send(client);
  259. }
  260. private function batchDataRequestEventHandler(event:ResponseItemEvent):void {
  261. logger.log("=============== Batch Success ================");
  262. var p:Person = event.response.getData("meProfile");
  263. logger.log("meProfile =============== " + p.getDisplayName());
  264. var c:Collection = event.response.getData("friendList");
  265. var arr:Array = c.getArray();
  266. for (var i:int = 0; i < arr.length; i++) {
  267. var person:Person = arr[i];
  268. logger.log("friendList =============== " + person.getDisplayName());
  269. }
  270. logger.log("=============== Batch Success ================");
  271. }
  272. private function batchDataRequestErrorHandler(event:ResponseItemEvent):void {
  273. logger.log("=============== Batch Error ================");
  274. logger.log(event.response.getErrorMessage());
  275. logger.log("=============== Batch Error ================");
  276. }
  277. private function batchFetchMeEventHandler(event:ResponseItemEvent):void {
  278. var p:Person = event.response.getData();
  279. logger.log(p.getDisplayName());
  280. drawPerson(p, 0);
  281. }
  282. private function batchFetchMeEventErrorHandler(event:ResponseItemEvent):void {
  283. logger.log("fetch me failed: " + event.response.getErrorMessage());
  284. }
  285. private function batchFetchFriendsEventHandler(event:ResponseItemEvent):void {
  286. var c:Collection = event.response.getData();
  287. logger.log(c.toDebugString());
  288. var arr:Array = c.getArray();
  289. for (var i:int = 0; i < arr.length; i++) {
  290. var p:Person = arr[i];
  291. logger.log(p.getDisplayName());
  292. drawPerson(p, i + 1);
  293. }
  294. if (c.getRemainingSize() > 0) {
  295. var req:AsyncDataRequest = event.target as AsyncDataRequest;
  296. (req.getOptions() as PeopleRequestOptions).setStartIndex(c.getNextOffset());
  297. req.send(client);
  298. }
  299. }
  300. private function batchFetchFriendsEventErrorHandler(event:ResponseItemEvent):void {
  301. logger.log("fetch friends failed: " + event.response.getErrorMessage());
  302. }
  303. // -------------------------------------------------------------
  304. // Helper functions for action and display
  305. // -------------------------------------------------------------
  306. private function prepareBtns():void {
  307. if (this['fetchMeBtn']) {
  308. var btn1:TextField = this['fetchMeBtn'] as TextField;
  309. btn1.addEventListener(MouseEvent.CLICK, function(event:MouseEvent):void {
  310. fetchMe();
  311. });
  312. }
  313. if (this['fetchFriendsBtn']) {
  314. var btn2:TextField = this['fetchFriendsBtn'] as TextField;
  315. btn2.addEventListener(MouseEvent.CLICK, function(event:MouseEvent):void {
  316. fetchFriends();
  317. });
  318. }
  319. if (this['sendMessageBtn']) {
  320. var btn3:TextField = this['sendMessageBtn'] as TextField;
  321. btn3.addEventListener(MouseEvent.CLICK, function(event:MouseEvent):void {
  322. sendMessage();
  323. });
  324. }
  325. if (this['createActivityBtn']) {
  326. var btn4:TextField = this['createActivityBtn'] as TextField;
  327. btn4.addEventListener(MouseEvent.CLICK, function(event:MouseEvent):void {
  328. createActivity();
  329. });
  330. }
  331. if (this['makeRequestBtn']) {
  332. var btn5:TextField = this['makeRequestBtn'] as TextField;
  333. btn5.addEventListener(MouseEvent.CLICK, function(event:MouseEvent):void {
  334. makeRequest();
  335. });
  336. }
  337. if (this['callRpcBtn']) {
  338. var btn6:TextField = this['callRpcBtn'] as TextField;
  339. btn6.addEventListener(MouseEvent.CLICK, function(event:MouseEvent):void {
  340. callRpc();
  341. });
  342. }
  343. if (this['registerSrvBtn']) {
  344. var btn7:TextField = this['registerSrvBtn'] as TextField;
  345. btn7.addEventListener(MouseEvent.CLICK, function(event:MouseEvent):void {
  346. registerService();
  347. });
  348. }
  349. if (this['batchRequestBtn']) {
  350. var btn8:TextField = this['batchRequestBtn'] as TextField;
  351. btn8.addEventListener(MouseEvent.CLICK, function(event:MouseEvent):void {
  352. batchRequest();
  353. });
  354. }
  355. }
  356. private function drawPerson(person:Person, index:int):void {
  357. var txtfmt:TextFormat = new TextFormat();
  358. txtfmt.size = 11;
  359. txtfmt.font = "arial";
  360. txtfmt.color = 0xFFFFFF;
  361. var name:TextField = new TextField();
  362. name.x = 2;
  363. name.y = 20;
  364. name.defaultTextFormat = txtfmt;
  365. name.text = person.getDisplayName();
  366. var box:Sprite = new Sprite();
  367. box.x = 2 + (index % 3) * 180;
  368. box.y = (Math.floor(index / 3)) * 70 + 20;
  369. box.addChild(name);
  370. addChild(box);
  371. try {
  372. var url:String = person.getThumbnailUrl();
  373. //logger.log(url);
  374. if (url != null) {
  375. var request:URLRequest = new URLRequest(url);
  376. var thumb:Loader = new Loader();
  377. box.addChild(thumb);
  378. thumb.x = 2;
  379. thumb.y = 20 + 2;
  380. thumb.load(request);
  381. thumb.contentLoaderInfo.addEventListener(Event.COMPLETE,
  382. function(event:Event):void {
  383. thumb.width = 32;
  384. thumb.height = 32;
  385. }, false, 0, true);
  386. box.addEventListener(MouseEvent.CLICK,
  387. function(event:Event):void {
  388. shareApp(person);
  389. }, false, 0, true);
  390. }
  391. } catch (e:Error) {
  392. logger.error(e);
  393. }
  394. }
  395. }
  396. }