Want more features on Pastebin? Sign Up, it's FREE!
Guest

OuyaTestFacade

By: a guest on Mar 19th, 2013  |  syntax: None  |  size: 13.28 KB  |  views: 48  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. /*
  2.  * Copyright (C) 2012 OUYA, Inc.
  3.  *
  4.  * Licensed under the Apache License, Version 2.0 (the "License");
  5.  * you may not use this file except in compliance with the License.
  6.  * You may obtain a copy of the License at
  7.  *
  8.  *     http://www.apache.org/licenses/LICENSE-2.0
  9.  *
  10.  * Unless required by applicable law or agreed to in writing, software
  11.  * distributed under the License is distributed on an "AS IS" BASIS,
  12.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13.  * See the License for the specific language governing permissions and
  14.  * limitations under the License.
  15.  */
  16.  
  17. package tv.ouya.sdk;
  18. import tv.ouya.console.api.*;
  19.  
  20. import android.accounts.AccountManager;
  21. import android.app.Activity;
  22. import android.app.AlertDialog;
  23. import android.content.BroadcastReceiver;
  24. import android.content.Context;
  25. import android.content.DialogInterface;
  26. import android.content.Intent;
  27. import android.content.IntentFilter;
  28. import android.os.Bundle;
  29. import android.util.Log;
  30. import android.view.View;
  31. import android.widget.ListView;
  32. import android.widget.Toast;
  33. import org.json.JSONException;
  34. import org.json.JSONObject;
  35. import tv.ouya.console.api.CancelIgnoringOuyaResponseListener;
  36. import tv.ouya.console.api.OuyaController;
  37. import tv.ouya.console.api.OuyaEncryptionHelper;
  38. import tv.ouya.console.api.OuyaFacade;
  39. import tv.ouya.console.api.OuyaResponseListener;
  40. import tv.ouya.console.api.Product;
  41. import tv.ouya.console.api.Purchasable;
  42. import tv.ouya.console.api.Receipt;
  43. import tv.ouya.console.internal.util.Strings;
  44.  
  45. import com.google.gson.Gson;
  46.  
  47. import java.io.IOException;
  48. import java.security.GeneralSecurityException;
  49. import java.util.ArrayList;
  50. import java.util.Arrays;
  51. import java.util.Collections;
  52. import java.util.Comparator;
  53. import java.util.List;
  54.  
  55. import com.unity3d.player.UnityPlayer;
  56.  
  57. public class TestOuyaFacade
  58. {
  59.     /*
  60.      * Log onto the developer website (you should have received a URL, a username and a password in email)
  61.      * and get your developer ID. Plug it in here. Use your developer ID, not your developer UUID.
  62.      * <p/>
  63.      * The current value is just a sample developer account. You should change it.
  64.      */
  65.     public static final String DEVELOPER_ID = "594d7108-0368-405b-ba72-c80c3de03eed";
  66.  
  67.     /*
  68.      * Before this app will run, you must define some purchasable items on the developer website. Once
  69.      * you have defined those items, put their Product IDs in the List below.
  70.      * <p/>
  71.      * The Product IDs below are those in our developer account. You should change them.
  72.      */
  73.     public static final List<Purchasable> PRODUCT_IDENTIFIER_LIST = Arrays.asList(new Purchasable("the_whole_darn_game"), new Purchasable("__DECLINED__THIS_PURCHASE"));
  74.  
  75.     /**
  76.      * The saved instance state key for products
  77.      */
  78.  
  79.     private static final String PRODUCTS_INSTANCE_STATE_KEY = "Products";
  80.  
  81.     /**
  82.      * The saved instance state key for receipts
  83.      */
  84.  
  85.     private static final String RECEIPTS_INSTANCE_STATE_KEY = "Receipts";
  86.  
  87.     /**
  88.      * The receipt adapter will display a previously-purchased item in a cell in a ListView. It's not part of the in-app
  89.      * purchase API. Neither is the ListView itself.
  90.      */
  91.     //private ListView receiptListView;
  92.     /**
  93.      * Your game talks to the OuyaFacade, which hides all the mechanics of doing an in-app purchase.
  94.      */
  95.     private OuyaFacade ouyaFacade;
  96.     private UserManager userManager;
  97.  
  98.     private List<Product> mProductList;
  99.     private List<Receipt> mReceiptList;
  100.  
  101.         //android context
  102.         private Context context;
  103.  
  104.         //abdriud bundle
  105.         Bundle savedInstanceState;
  106.  
  107.  
  108.     /**
  109.      * Broadcast listener to handle re-requesting the receipts when a user has re-authenticated
  110.      */
  111.     private BroadcastReceiver mAuthChangeReceiver = new BroadcastReceiver() {
  112.         @Override
  113.         public void onReceive(Context context, Intent intent) {
  114.             fetchReceipts();
  115.         }
  116.     };
  117.  
  118.         public TestOuyaFacade(Context context, Bundle savedInstanceState)
  119.         {
  120.                 this.context = context;
  121.  
  122.                 Log.i("TestOuyaFacade", "TestOuyaFacade.Init();");
  123.                 UnityPlayer.UnitySendMessage("OuyaGameObject", "DebugLog", "TestOuyaFacade.Init();");
  124.  
  125.         ouyaFacade = OuyaFacade.getInstance();
  126.  
  127.         userManager = UserManager.getInstance(context);
  128.  
  129.                 Init();
  130.         }
  131.  
  132.         private void setupSkuList() {
  133.         //skuAdapter = new SkuAdapter(this, new RequestPurchaseClickListener());
  134.         //skuListView = (ListView) findViewById(R.id.skus);
  135.         //skuListView.setAdapter(skuAdapter);
  136.     }
  137.  
  138.         private void Init()
  139.         {
  140.                 Log.i("TestOuyaFacade", "OuyaFacade.init(context, DEVELOPER_ID);");
  141.                 UnityPlayer.UnitySendMessage("OuyaGameObject", "DebugLog", "ouyaFacade.init(context, DEVELOPER_ID);");
  142.         ouyaFacade.init(context, DEVELOPER_ID);
  143.  
  144.         // Uncomment this line to test against the server using "fake" credits.
  145.         // This will also switch over to a separate "test" purchase history.
  146.                 ouyaFacade.setTestMode();
  147.                
  148.         //setupSkuList();
  149.  
  150.         //receiptAdapter = new ReceiptAdapter(this);
  151.         //receiptListView = (ListView) findViewById(R.id.receipts);
  152.         //receiptListView.setAdapter(receiptAdapter);
  153.  
  154.         /*
  155.          * In order to avoid "application not responding" popups, Android demands that long-running operations
  156.          * happen on a background thread. Listener objects provide a way for you to specify what ought to happen
  157.          * at the end of the long-running operation. Examples of this pattern in Android include
  158.          * android.os.AsyncTask.
  159.          */
  160.         Log.i("TestOuyaFacade", "OuyaResponseListener<ArrayList<Product>> productListListener = new CancelIgnoringOuyaResponseListener<ArrayList<Product>>() {");
  161.         UnityPlayer.UnitySendMessage("OuyaGameObject", "DebugLog", "OuyaResponseListener<ArrayList<Product>> productListListener = new CancelIgnoringOuyaResponseListener<ArrayList<Product>>() {");
  162.         m_productListListener = new CancelIgnoringOuyaResponseListener<ArrayList<Product>>() {
  163.             @Override
  164.             public void onSuccess(ArrayList<Product> products) {
  165.                 addProducts(products);
  166.             }
  167.  
  168.             @Override
  169.             public void onFailure(int errorCode, String errorMessage, Bundle optionalData)
  170.                         {
  171.                 // Your app probably wants to do something more sophisticated than popping a Toast. This is
  172.                 // here to tell you that your app needs to handle this case: if your app doesn't display
  173.                 // something, the user won't know of the failure.
  174.                 //Toast.makeText(OuyaSampleActivity.this, "Could not fetch product information (error " + errorCode + ": " + errorMessage + ")", Toast.LENGTH_LONG).show();
  175.                                 Log.i("TestOuyaFacade", "Could not fetch product information (error " + errorCode + ": " + errorMessage + ")");
  176.                                 UnityPlayer.UnitySendMessage("OuyaGameObject", "DebugLogError", "Could not fetch product information (error " + errorCode + ": " + errorMessage + ")");
  177.             }
  178.         };
  179.  
  180.                 /*
  181.         findViewById(R.id.gamer_uuid_button).setOnClickListener(new View.OnClickListener()
  182.                 {
  183.             @Override
  184.             public void onClick(View v) {
  185.                 ouyaFacade.requestGamerUuid(new CancelIgnoringOuyaResponseListener<String>() {
  186.                     @Override
  187.                     public void onSuccess(String result)
  188.                                         {
  189.                         // new AlertDialog.Builder(OuyaSampleActivity.this)
  190.                         //    .setTitle(getString(R.string.alert_title))
  191.                         //    .setMessage(result)
  192.                         //    .show();
  193.                     }
  194.  
  195.                     @Override
  196.                     public void onFailure(int errorCode, String errorMessage, Bundle optionalData)
  197.                                         {
  198.                         //Toast.makeText(OuyaSampleActivity.this, "Unable to fetch gamer UUID (error " + errorCode + ": " + errorMessage + ")", Toast.LENGTH_LONG).show();
  199.                     }
  200.                 });
  201.             }
  202.         });
  203.                 */
  204.  
  205.         //fetchReceipts();
  206.     }
  207.  
  208.         private OuyaResponseListener<ArrayList<Product>> m_productListListener = null;
  209.  
  210.     public void getProductsAsync()
  211.     {
  212.         Log.i("TestOuyaFacade", "ouyaFacade.requestProductList(SKU_LIST, productListListener);");
  213.                 UnityPlayer.UnitySendMessage("OuyaGameObject", "DebugLog", "ouyaFacade.requestProductList(SKU_LIST, productListListener);");
  214.         ouyaFacade.requestProductList(PRODUCT_IDENTIFIER_LIST, m_productListListener);
  215.     }
  216.  
  217.     private static final byte[] APPLICATION_KEY = { 0x00 };
  218.  
  219.     private void fetchReceipts()
  220.         {
  221.         ouyaFacade.requestReceipts(new CancelIgnoringOuyaResponseListener<String>()
  222.                 {
  223.             @Override
  224.             public void onSuccess(String receiptResponse)
  225.                         {
  226.                 OuyaEncryptionHelper helper = new OuyaEncryptionHelper();
  227.                 List<Receipt> receipts = null;
  228.                 try {
  229.                     receipts = helper.decryptReceiptResponse(receiptResponse, APPLICATION_KEY);
  230.                     } catch (GeneralSecurityException e) {
  231.                         throw new RuntimeException(e);
  232.                     } catch (IOException e) {
  233.                         throw new RuntimeException(e);
  234.                     }
  235.                 Collections.sort(receipts, new Comparator<Receipt>() {
  236.                     @Override
  237.                     public int compare(Receipt lhs, Receipt rhs) {
  238.                         return rhs.getPurchaseDate().compareTo(lhs.getPurchaseDate());
  239.                     }
  240.                 });
  241.                 //receiptAdapter.set(receipts);
  242.             }
  243.  
  244.             @Override
  245.             public void onFailure(int errorCode, String errorMessage, Bundle optionalData) {
  246.                 // Again, your game should do something more sophisticated.
  247.                 //Toast.makeText(OuyaSampleActivity.this, "Could not fetch receipts (error " + errorCode + ": " + errorMessage + ")", Toast.LENGTH_LONG).show();
  248.             }
  249.         });
  250.     }
  251.  
  252.         public void addProducts(List<Product> products)
  253.         {
  254.         //skuAdapter.add(products);
  255.                 for (Product p : products)
  256.                 {
  257.                         Gson gson = new Gson();
  258.                         String jsonData = gson.toJson(p);
  259.  
  260.                         Log.i("TestOuyaFacade", "AddProduct jsonData=" + jsonData);
  261.                         UnityPlayer.UnitySendMessage("OuyaGameObject", "ProductListListener", jsonData);
  262.                 }
  263.     }
  264.  
  265.         /*
  266.      * This will be called when the user clicks on an item in the ListView.
  267.      */
  268.     public void requestPurchase(final String productId)
  269.         {
  270.        
  271.         ouyaFacade.requestPurchase(new Purchasable(productId), new CancelIgnoringOuyaResponseListener<String>()
  272.                 {
  273.             @Override
  274.             public void onSuccess(String result)
  275.                         {
  276.                                 /*
  277.                 new AlertDialog.Builder(OuyaSampleActivity.this)
  278.                         .setTitle(getString(R.string.alert_title))
  279.                         .setMessage("You have successfully purchased a " + product.getName() + " for " + Strings.formatDollarAmount(product.getPriceInCents()))
  280.                         .show();
  281.                                 */
  282.                 //fetchReceipts();
  283.  
  284.                 try {
  285.                         Product product;
  286.                         if(result.contains("{")) {
  287.                        product = new Product(new JSONObject(result));
  288.                         } else {
  289.                         product = OuyaEncryptionHelper.decryptProductResponse(result, APPLICATION_KEY);
  290.                         }
  291.                         Log.i("OuyaGameObject", "requestPurchase onSuccess You have successfully purchased a " + product.getName() + " for " + Strings.formatDollarAmount(product.getPriceInCents()));
  292.  
  293.                                         Gson gson = new Gson();
  294.                                         String jsonData = gson.toJson(product);
  295.                                         UnityPlayer.UnitySendMessage("OuyaGameObject", "RequestPurchaseListener", jsonData);
  296.                                 } catch (JSONException e) {
  297.                         onFailure(OuyaErrorCodes.THROW_DURING_ON_SUCCESS, e.getMessage(), Bundle.EMPTY);
  298.                     } catch (IOException e) {
  299.                         onFailure(OuyaErrorCodes.THROW_DURING_ON_SUCCESS, e.getMessage(), Bundle.EMPTY);
  300.                 } catch (GeneralSecurityException e) {
  301.                         onFailure(OuyaErrorCodes.THROW_DURING_ON_SUCCESS, e.getMessage(), Bundle.EMPTY);
  302.                 }
  303.             }
  304.  
  305.             @Override
  306.             public void onFailure(int errorCode, String errorMessage, Bundle optionalData)
  307.                         {
  308.                                 /*
  309.                 new AlertDialog.Builder(OuyaSampleActivity.this)
  310.                         .setTitle(getString(R.string.alert_title))
  311.                         .setMessage("Unfortunately, your purchase failed [error code " + errorCode + " (" + errorMessage + ")]. Would you like to try again?")
  312.                         .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener()
  313.                                                 {
  314.                             @Override
  315.                             public void onClick(DialogInterface dialogInterface, int i)
  316.                                                         {
  317.                                 dialogInterface.dismiss();
  318.                                 requestPurchase(sku);
  319.                             }
  320.                         })
  321.                         .setNegativeButton(R.string.cancel, null)
  322.                         .show();
  323.                                 */
  324.  
  325.                 Log.i("OuyaGameObject", "requestPurchase onFailure errorMessage=" + errorMessage);
  326.                         UnityPlayer.UnitySendMessage("OuyaGameObject", "DebugLogError", "requestPurchase onFailure errorMessage=" + errorMessage);
  327.             }
  328.         });
  329.     }
  330. }
clone this paste RAW Paste Data