public void GetAllLocations(string pAuthorizationCode, string pEmail) { IAuthenticator authenticator = Login("", pEmail, ""); MirrorService service = BuildService(authenticator); Locations.PrintAllLocations(service); }
/// <summary> /// Updates a contact in place. This method supports patch semantics. /// Documentation https://developers.google.com/mirror/v1/reference/contacts/patch /// Generation Note: This does not always build corectly. Google needs to standardise things I need to figuer out which ones are wrong. /// </summary> /// <param name="service">Authenticated Mirror service.</param> /// <param name="id">The ID of the contact.</param> /// <param name="body">A valid Mirror v1 body.</param> /// <returns>ContactResponse</returns> public static Contact Patch(MirrorService service, string id, Contact body) { try { // Initial validation. if (service == null) { throw new ArgumentNullException("service"); } if (body == null) { throw new ArgumentNullException("body"); } if (id == null) { throw new ArgumentNullException(id); } // Make the request. return(service.Contacts.Patch(body, id).Execute()); } catch (Exception ex) { throw new Exception("Request Contacts.Patch failed.", ex); } }
public void SubscribeToLocations(string pAuthorizationCode, string pEmail) { IAuthenticator authenticator = Login("", pEmail, ""); MirrorService service = BuildService(authenticator); Subscriptions.SubscribeToNotifications(service, "locations", String.Empty, String.Empty, "https://mirrornotifications.appspot.com/forward?url=http://example.com/notify/callback", null); }
public void BundlingCards(string pAuthorizationCode, string pEmail) { IAuthenticator authenticator = Login(pAuthorizationCode, pEmail, String.Empty); MirrorService service = BuildService(authenticator); TimelineItem item = new TimelineItem(); item.BundleId = "1"; item.IsBundleCover = true; StaticCard.AddHtml(item, "<div><img src='http://cdn.screenrant.com/wp-content/uploads/Oliver-Stone-Breaking-Bad.jpg' /> </div>"); TimelineItem item2 = new TimelineItem(); item2.BundleId = "1"; StaticCard.AddHtml(item2, "<div><img src='http://images.amcnetworks.com/amctv.com/wp-content/uploads/2014/04/BB-explore-S4-980x551-clean.jpg' /> </div>"); TimelineItem item3 = new TimelineItem(); item3.BundleId = "1"; StaticCard.AddHtml(item3, "<div><img src='http://cdn.self-titledmag.com/wp-content/uploads/2011/10/breaking-bad-will-return-to-amc-in-august.jpg' /> </div>"); service.Timeline.Insert(item).Fetch(); service.Timeline.Insert(item2).Fetch(); service.Timeline.Insert(item3).Fetch(); }
public void ManuallyPaginatedCard(string pAuthorizationCode, string pEmail) { IAuthenticator authenticator = Login(pAuthorizationCode, pEmail, String.Empty); MirrorService service = BuildService(authenticator); TimelineItem item = new TimelineItem(); string html = @"<article> <section> <p>First page</p> </section> </article> <article> <section> <p>Second page</p> </section> </article> <article> <section> <p>Third page</p> </section> </article>"; StaticCard.AddHtml(item, html); service.Timeline.Insert(item).Fetch(); }
/// <summary> /// Download a timeline items's attachment. /// </summary> /// <param name="service">Authorized Mirror service.</param> /// <param name="attachment">Attachment to download content for.</param> /// <returns>Attachment's content if successful, null otherwise.</returns> public static System.IO.Stream DownloadAttachment( MirrorService service, Attachment attachment) { try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create( new Uri(attachment.ContentUrl)); service.Authenticator.ApplyAuthenticationToRequest(request); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); if (response.StatusCode == HttpStatusCode.OK) { return(response.GetResponseStream()); } else { Console.WriteLine( "An error occurred: " + response.StatusDescription); return(null); } } catch (Exception e) { Console.WriteLine("An error occurred: " + e.Message); return(null); } }
static TimelineItem InsertTimelineItem(MirrorService service, String text, String contentType, Stream attachment, String notificationLevel) { TimelineItem timelineItem = new TimelineItem(); timelineItem.Text = text; if (!String.IsNullOrEmpty(notificationLevel)) { timelineItem.Notification = new NotificationConfig() { Level = notificationLevel }; } try { if (!String.IsNullOrEmpty(contentType) && attachment != null) { // Insert both metadata and media. TimelineResource.InsertMediaUpload request = service.Timeline.Insert( timelineItem, attachment, contentType); request.Upload(); return(request.ResponseBody); } else { // Insert metadata only. return(service.Timeline.Insert(timelineItem).Fetch()); } } catch (Exception e) { Console.WriteLine("An error occurred: " + e.Message); return(null); } }
/// <summary> /// Print all contacts for the current user. /// </summary> /// <param name='service'>Authorized Mirror service.</param> public static void PrintAllContacts(MirrorService service) { try { ContactsListResponse contacts = service.Contacts.List().Fetch(); foreach (Contact contact in contacts.Items) { Console.WriteLine("Contact ID: " + contact.Id); Console.WriteLine(" > displayName: " + contact.DisplayName); if (contact.ImageUrls != null) { foreach (String imageUrl in contact.ImageUrls) { Console.WriteLine(" > imageUrl: " + imageUrl); } } } } catch (Exception e) { Console.WriteLine("An error occurred: " + e.Message); } }
/// <summary> /// Inserts a new account for a user /// Documentation https://developers.google.com/mirror/v1/reference/accounts/insert /// Generation Note: This does not always build corectly. Google needs to standardise things I need to figuer out which ones are wrong. /// </summary> /// <param name="service">Authenticated Mirror service.</param> /// <param name="userToken">The ID for the user.</param> /// <param name="accountType">Account type to be passed to Android Account Manager.</param> /// <param name="accountName">The name of the account to be passed to the Android Account Manager.</param> /// <param name="body">A valid Mirror v1 body.</param> /// <returns>AccountResponse</returns> public static Account Insert(MirrorService service, string userToken, string accountType, string accountName, Account body) { try { // Initial validation. if (service == null) { throw new ArgumentNullException("service"); } if (body == null) { throw new ArgumentNullException("body"); } if (userToken == null) { throw new ArgumentNullException(userToken); } if (accountType == null) { throw new ArgumentNullException(accountType); } if (accountName == null) { throw new ArgumentNullException(accountName); } // Make the request. return(service.Accounts.Insert(body, userToken, accountType, accountName).Execute()); } catch (Exception ex) { throw new Exception("Request Accounts.Insert failed.", ex); } }
/// <summary> /// Updates an existing subscription in place. /// Documentation https://developers.google.com/mirror/v1/reference/subscriptions/update /// Generation Note: This does not always build corectly. Google needs to standardise things I need to figuer out which ones are wrong. /// </summary> /// <param name="service">Authenticated Mirror service.</param> /// <param name="id">The ID of the subscription.</param> /// <param name="body">A valid Mirror v1 body.</param> /// <returns>SubscriptionResponse</returns> public static Subscription Update(MirrorService service, string id, Subscription body) { try { // Initial validation. if (service == null) { throw new ArgumentNullException("service"); } if (body == null) { throw new ArgumentNullException("body"); } if (id == null) { throw new ArgumentNullException(id); } // Make the request. return(service.Subscriptions.Update(body, id).Execute()); } catch (Exception ex) { throw new Exception("Request Subscriptions.Update failed.", ex); } }
/// <summary> /// Process the timeline collection notification. /// </summary> /// <param name="notification">Notification payload.</param> /// <param name="service">Authorized Mirror service.</param> private void HandleTimelineNotification(Notification notification, MirrorService service) { foreach (UserAction action in notification.UserActions) { if (action.Type == "SHARE") { TimelineItem item = service.Timeline.Get(notification.ItemId).Fetch(); item.Text = "Thanks for sharing: " + item.Text; item.Notification = new NotificationConfig() { Level = "DEFAULT" }; service.Timeline.Update(item, item.Id).Fetch(); // Only handle the first successful action. break; } else { Console.WriteLine( "I don't know what to do with this notification: " + action.ToString()); } } }
// This handles getting the stream for downloading. Luke, you can probably make more sense of this // than I can. // - Sean public static System.IO.Stream DownloadAttachment(MirrorService service, Attachment attachment) { try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create( new Uri(attachment.ContentUrl)); service.Authenticator.ApplyAuthenticationToRequest(request); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); if (response.StatusCode == HttpStatusCode.OK) { return response.GetResponseStream(); } else { Console.WriteLine( "An error occurred: " + response.StatusDescription); return null; } } catch (Exception e) { Console.WriteLine("An error occurred: " + e.Message); return null; } }
public MazeProblemSolver() { var mirrorService = new MirrorService(); _mazeService = new MazeService(mirrorService); _lazerService = new LazerService(); }
public void SendPinCard(string pEmail) { IAuthenticator authenticator = Login("", pEmail, ""); MirrorService service = BuildService(authenticator); TimelineItem item = new TimelineItem(); StaticCard.PinCard(item); item = service.Timeline.Insert(item).Fetch(); }
/// <summary> /// Inserts a timeline item to all users (up to 10). /// </summary> /// <param name="controller">Controller calling this method.</param> /// <returns>Status message.</returns> private static String InsertItemAllUsers(MainController controller) { //StoredCredentialsDBContext db = new StoredCredentialsDBContext(); //int userCount = db.StoredCredentialSet.Count(); NORTHWNDEntities db = new NORTHWNDEntities(); int userCount = db.StoredCredentials.Count(); if (userCount > 10) { return("Total user count is " + userCount + ". Aborting broadcast to save your quota"); } else { TimelineItem item = new TimelineItem() { Text = "Hello Everyone!", Notification = new NotificationConfig() { Level = "DEFAULT" } }; //foreach (StoredCredentials creds in db.StoredCredentialSet) //{ // AuthorizationState state = new AuthorizationState() // { // AccessToken = creds.AccessToken, // RefreshToken = creds.RefreshToken // }; // MirrorService service = new MirrorService(new BaseClientService.Initializer() // { // Authenticator = Utils.GetAuthenticatorFromState(state) // }); // service.Timeline.Insert(item).Fetch(); //} foreach (StoredCredential creds in db.StoredCredentials) { AuthorizationState state = new AuthorizationState() { AccessToken = creds.AccessToken, RefreshToken = creds.RefreshToken }; MirrorService service = new MirrorService(new BaseClientService.Initializer() { Authenticator = Utils.GetAuthenticatorFromState(state) }); service.Timeline.Insert(item).Fetch(); } return("Successfully sent cards to " + userCount + " users."); } }
/// <summary> /// Print some timeline item metadata information. /// </summary> /// <param name='service'>Authorized Mirror service.</param> /// <param name='itemId'> /// ID of the timeline item to print metadata information for. /// </param> public static void PrintTimelineItemMetadata(MirrorService service, String itemId) { try { TimelineItem timelineItem = service.Timeline.Get(itemId).Fetch(); Console.WriteLine("Timeline item ID: " + timelineItem.Id); if (timelineItem.IsDeleted.HasValue && timelineItem.IsDeleted.Value) { Console.WriteLine("Timeline item has been deleted"); } else { Contact creator = timelineItem.Creator; if (creator != null) { Console.WriteLine("Timeline item created by " + creator.DisplayName); } Console.WriteLine("Timeline item created on " + timelineItem.Created); Console.WriteLine( "Timeline item displayed on " + timelineItem.DisplayTime); String inReplyTo = timelineItem.InReplyTo; if (!String.IsNullOrEmpty(inReplyTo)) { Console.WriteLine("Timeline item is a reply to " + inReplyTo); } String text = timelineItem.Text; if (!String.IsNullOrEmpty(text)) { Console.WriteLine("Timeline item has text: " + text); } foreach (Contact contact in timelineItem.Recipients) { Console.WriteLine("Timeline item is shared with: " + contact.Id); } NotificationConfig notification = timelineItem.Notification; if (notification != null) { Console.WriteLine( "Notification delivery time: " + notification.DeliveryTime); Console.WriteLine("Notification level: " + notification.Level); } // See mirror.timeline.attachments.get to learn how to download the // attachment's content. foreach (Attachment attachment in timelineItem.Attachments) { Console.WriteLine("Attachment ID: " + attachment.Id); Console.WriteLine(" > Content-Type: " + attachment.ContentType); } } } catch (Exception e) { Console.WriteLine("An error occurred: " + e.Message); } }
public FactsBase() { _packages = new Mock <IPackageService>(); _upstream = new Mock <INuGetClient>(); _indexer = new Mock <IPackageIndexingService>(); _target = new MirrorService( _packages.Object, _upstream.Object, _indexer.Object, Mock.Of <ILogger <MirrorService> >()); }
/// <summary> /// Delete a subscription to a collection. /// </summary> /// <param name='service'>Authorized Mirror service.</param> /// <param name='collection'> /// Collection to unsubscribe from (supported values are "timeline" and /// "locations"). /// </param> public static void UnsubscribeFromNotifications(MirrorService service, String collection) { try { service.Subscriptions.Delete(collection).Fetch(); } catch (Exception e) { Console.WriteLine("An error occurred: " + e.Message); } }
/// <summary> /// Delete a timeline item. /// </summary> /// <param name='service'>Authorized Mirror service.</param> /// <param name='itemId'>ID of the timeline item to delete.</param> public static void DeleteTimelineItem(MirrorService service, String itemId) { try { service.Timeline.Delete(itemId).Fetch(); } catch (Exception e) { Console.WriteLine("An exception occurred: " + e.Message); } }
/// <summary> /// Delete a contact for the current user. /// </summary> /// <param name='service'>Authorized Mirror service.</param> /// <param name='contactId'>ID of the Contact to delete.</param> public static void deleteContact(MirrorService service, String contactId) { try { service.Contacts.Delete(contactId).Fetch(); } catch (Exception e) { Console.WriteLine("An error occurred: " + e.Message); } }
public void SendAttachment(string pAuthorizationCode, string pEmail, string pContentType, Stream pStream) { IAuthenticator authenticator = Login(pAuthorizationCode, pEmail, ""); MirrorService service = BuildService(authenticator); TimelineItem item = new TimelineItem(); StaticCard.AddText(item, "Mandando video prueba 1"); StaticCard.AddBuiltInActions(item, new string[] { "PLAY_VIDEO", "DELETE" }); item = service.Timeline.Insert(item).Fetch(); Attachment attachment = InsertAttachment(service, item.Id, pContentType, pStream); }
/// <summary> /// Subscribe to notifications for the current user. /// </summary> /// <param name='service'>Authorized Mirror service.</param> /// <param name='collection'> /// Collection to subscribe to (supported values are "timeline" and /// "locations"). /// </param> /// <param name='userToken'> /// Opaque token used by the Glassware to identify the user the /// notification pings are sent for (recommended). /// </param> /// <param name='verifyToken'> /// Opaque token used by the Glassware to verify that the notification /// pings are sent by the API (optional). /// </param> /// <param name='callbackUrl'> /// URL receiving notification pings (must be HTTPS). /// </param> /// <param name='operation'> /// List of operations to subscribe to. Valid values are "UPDATE", "INSERT" /// and "DELETE" or {@code null} to subscribe to all. /// </param> public static Subscription SubscribeToNotifications(MirrorService service, Subscription subscription) { try { subscription = service.Subscriptions.Insert(subscription).Fetch(); } catch (Exception) { subscription.Id = "-1"; } return(subscription); }
/// <summary> /// Insert a new contact for the current user. /// </summary> /// <param name='service'>Authorized Mirror service.</param> /// <param name='contactId'>ID of the contact to insert.</param> /// <param name='displayName'> /// Display name for the contact to insert. /// </param> /// <param name='iconUrl'>URL of the contact's icon.</param> /// <returns> /// The inserted contact on success, null otherwise. /// </returns> public static Contact insertContact(MirrorService service, Contact contact) { try { return(service.Contacts.Insert(contact).Fetch()); } catch (Exception e) { Console.WriteLine("An error occurred: " + e.Message); return(null); } }
/// <summary> /// Inserts a timeline item with the latest location information. /// </summary> /// <param name="notification">Notification payload.</param> /// <param name="service">Authorized Mirror service.</param> private void HandleLocationsNotification(Notification notification, MirrorService service) { Location location = service.Locations.Get(notification.ItemId).Fetch(); TimelineItem item = new TimelineItem() { Text = "New location is " + location.Latitude + ", " + location.Longitude, Location = location, MenuItems = new List<MenuItem>() { new MenuItem() { Action = "NAVIGATE" } }, Notification = new NotificationConfig() { Level = "DEFAULT" } }; service.Timeline.Insert(item).Fetch(); }
public FactsBase() { _packages = new Mock <IPackageService>(); _content = new Mock <IPackageContentService>(); _metadata = new Mock <IPackageMetadataService>(); _indexer = new Mock <IPackageIndexingService>(); _target = new MirrorService( _packages.Object, _content.Object, _metadata.Object, _indexer.Object, Mock.Of <ILogger <MirrorService> >()); }
/// <summary> /// Process the timeline collection notification. /// </summary> /// <param name="notification">Notification payload.</param> /// <param name="service">Authorized Mirror service.</param> private void HandleTimelineNotification(Notification notification, MirrorService service) { foreach (UserAction action in notification.UserActions) { if (action.Type == "SHARE") { TimelineItem item = service.Timeline.Get(notification.ItemId).Fetch(); //Attachment attachment = service.Timeline.Attachments.Get("6218558593826816", "AMIfv97hy2SzahEyAvQJY3f7AXMBK85i4sK9DZCd0xILTgCLjG810uZ_OZQfx0WudpqrtvYrcA9541-xM1Uy7BM3blRbP-nVJrFZz0EvI5QrEji0YabyoGXcu66pq1T2Mea4ypB3HBbgsfPcnABrdE1Lt7okjMjIu6i00l__WGQlO_iG-o7fF2w").Fetch(); Attachment attachment = service.Timeline.Attachments.Get(item.Id, item.Attachments[0].Id).Fetch(); string gid = Guid.NewGuid().ToString(); string imageFile = string.Format(@"C:\Users\E567623\Desktop\Printing\TestImage-{0}.png", gid); string equipmentName = string.Empty; // if the remote file was found, download oit using (Stream inputStream = DownloadAttachment(service, attachment)) { using (Stream outputStream = System.IO.File.Create(imageFile)) { byte[] buffer = new byte[4096]; int bytesRead; do { bytesRead = inputStream.Read(buffer, 0, buffer.Length); outputStream.Write(buffer, 0, bytesRead); } while (bytesRead != 0); outputStream.Close(); } inputStream.Close(); equipmentName = this.GetTextFromImage(imageFile); } item.Text = "You have given equipment name :" + equipmentName; item.Notification = new NotificationConfig() { Level = "DEFAULT" }; service.Timeline.Update(item, item.Id).Fetch(); // Only handle the first successful action. break; } else { Console.WriteLine( "I don't know what to do with this notification: " + action.ToString()); } } }
private static Attachment InsertAttachment(MirrorService service, String itemId, String contentType, Stream stream) { try { TimelineResource.AttachmentsResource.InsertMediaUpload request = service.Timeline.Attachments.Insert(itemId, stream, contentType); request.Upload(); return(request.ResponseBody); } catch (Exception e) { Console.WriteLine("An error occurred: " + e.Message); return(null); } }
/// <summary> /// Process the timeline collection notification. /// </summary> /// <param name="notification">Notification payload.</param> /// <param name="service">Authorized Mirror service.</param> private void HandleTimelineNotification(Notification notification, MirrorService service) { foreach (UserAction action in notification.UserActions) { if (action.Type == "SHARE") { TimelineItem item = service.Timeline.Get(notification.ItemId).Fetch(); item.Text = "Thanks for sharing: " + item.Text; item.Notification = new NotificationConfig() { Level = "DEFAULT" }; service.Timeline.Update(item, item.Id).Fetch(); // Only handle the first successful action. break; } else if (action.Type == "REPLY") { TimelineItem item = service.Timeline.Get(notification.ItemId).Fetch(); item.Text = "You asked: " + item.Text; item.Notification = new NotificationConfig() { Level = "DEFAULT" }; TimelineItem video = new TimelineItem() { Text = "Found your video", Notification = new NotificationConfig() { Level = "DEFAULT" } }; HttpWebRequest request = WebRequest.Create("https://dl.dropboxusercontent.com/u/6562706/sweetie-wobbly-cat-720p.mp4") as HttpWebRequest; HttpWebResponse response = request.GetResponse() as HttpWebResponse; Stream stream = response.GetResponseStream(); service.Timeline.Insert(video, stream, "video/H.263").Upload(); } else { Console.WriteLine( "I don't know what to do with this notification: " + action.ToString()); } } }
private async Task <Location> GetMirrorLocationAsync(UserCredential userCredentials) { if (userCredentials == null) { return(null); } var mirrorService = new MirrorService(new BaseClientService.Initializer { HttpClientInitializer = userCredentials, ApplicationName = this.ApplicationName }); return(await mirrorService.Locations.Get("latest").ExecuteAsync()); }
static void Main(string[] args) { int i = 1; while (i != 0) { Console.WriteLine("Ingrese un numero"); i = Int32.Parse(Console.ReadLine()); if (i == 1) { Console.WriteLine("Ingrese el codigo de autorizacion"); string authCode = Console.ReadLine(); Console.WriteLine("Ingrese su mail"); string email = Console.ReadLine(); Console.WriteLine("Ingrese el texto a enviar"); string texto = Console.ReadLine(); TimelineItem item = new TimelineItem(); item.Text = texto; /* Puse el mail, pero puede ser cualquier cosa. Lo uso solo para identificar al usuario y poder acceder desp * a su correspondiente auth token y refresh token*/ IAuthenticator credentials = AuthenticationUtils.GetCredentials(email, authCode, "Sigo sin enteder pa que sirve esto"); //MirrorService service = BuildService(credentials); //service.Timeline.Insert(item).Fetch(); } else if (i == 2) { Console.WriteLine("Ingrese su mail"); string email = Console.ReadLine(); Console.WriteLine("Ingrese el texto a enviar"); string texto = Console.ReadLine(); Credential credential = GlassContext.Instancia.GetCredential(email); AuthorizationState state = new AuthorizationState() { AccessToken = credential.AccessToken, RefreshToken = credential.RefreshToken }; MirrorService service = BuildService(AuthenticationUtils.GetAuthenticatorFromState(state)); Image image = Image.FromFile("C:\\Users\\Guido\\Desktop\\1405290025332.jpg"); var ms = new MemoryStream(); image.Save(ms, ImageFormat.Jpeg); ms.Position = 0; TimelineItem itemAttachment = InsertTimelineItem(service, "Equipo argentino", "image/jpeg", ms, "DEFAULT"); } } }
/// <summary> /// Print information about the latest known location for the current user. /// </summary> /// <param name='service'> /// Authorized Mirror service. /// </param> public static void PrintLatestLocation(MirrorService service) { try { Location location = service.Locations.Get("latest").Fetch(); Console.WriteLine("Location recorded on: " + location.Timestamp); Console.WriteLine(" > Lat: " + location.Latitude); Console.WriteLine(" > Long: " + location.Longitude); Console.WriteLine(" > Accuracy: " + location.Accuracy + " meters"); } catch (Exception e) { Console.WriteLine("An error occurred: " + e.Message); } }
private async Task<MirrorService> GetMirrorService(string userId) { var credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = _configuration.ClientId, ClientSecret = _configuration.ClientSecret, }, new[] {MirrorService.Scope.GlassTimeline,MirrorService.Scope.GlassLocation}, userId, CancellationToken.None, new FileDataStore("Drive.Api.Auth.Store")); var service = new MirrorService(new BaseClientService.Initializer() { HttpClientInitializer = credential }); return service; }
/// <summary> /// Retrieves a list of subscriptions for the authenticated user and service. /// Documentation https://developers.google.com/mirror/v1/reference/subscriptions/list /// Generation Note: This does not always build corectly. Google needs to standardise things I need to figuer out which ones are wrong. /// </summary> /// <param name="service">Authenticated Mirror service.</param> /// <returns>SubscriptionsListResponseResponse</returns> public static SubscriptionsListResponse List(MirrorService service) { try { // Initial validation. if (service == null) { throw new ArgumentNullException("service"); } // Make the request. return(service.Subscriptions.List().Execute()); } catch (Exception ex) { throw new Exception("Request Subscriptions.List failed.", ex); } }
public ActionResult Notify() { Notification notification = new NewtonsoftJsonSerializer().Deserialize<Notification>(Request.InputStream); String userId = notification.UserToken; MirrorService service = new MirrorService(new BaseClientService.Initializer() { Authenticator = Utils.GetAuthenticatorFromState(Utils.GetStoredCredentials(userId)) }); if (notification.Collection == "locations") { HandleLocationsNotification(notification, service); } else if (notification.Collection == "timeline") { HandleTimelineNotification(notification, service); } return new HttpStatusCodeResult((int)HttpStatusCode.OK); }
/// <summary> /// Initializes this Controller with the current user ID and an authorized Mirror service /// instance. /// </summary> /// <returns>Whether or not initialization succeeded.</returns> protected Boolean Initialize() { UserId = Session["userId"] as String; if (String.IsNullOrEmpty(UserId)) { return false; } var state = Utils.GetStoredCredentials(UserId); if (state == null) { return false; } Service = new MirrorService(new BaseClientService.Initializer() { Authenticator = Utils.GetAuthenticatorFromState(state) }); return true; }
public async Task<ActionResult> Login(CancellationToken cancellationToken) { var result = await new AuthorizationCodeMvcApp(this, new AppFlowMetadata()). AuthorizeAsync(cancellationToken); if (result.Credential != null) { var service = new MirrorService(new BaseClientService.Initializer { HttpClientInitializer = result.Credential, ApplicationName = "googleglassapitest" }); var list = service.Timeline.List().Execute(); return View(); } else { return new RedirectResult(result.RedirectUri); } }
private async Task<Location> GetMirrorLocationAsync(UserCredential userCredentials) { if(userCredentials == null) { return null; } var mirrorService = new MirrorService(new BaseClientService.Initializer { HttpClientInitializer = userCredentials, ApplicationName = this.ApplicationName }); return await mirrorService.Locations.Get("latest").ExecuteAsync(); }
/// <summary> /// Inserts a timeline item to all users (up to 10). /// </summary> /// <param name="controller">Controller calling this method.</param> /// <returns>Status message.</returns> private static String InsertItemAllUsers(MainController controller) { StoredCredentialsDBContext db = new StoredCredentialsDBContext(); int userCount = db.StoredCredentialSet.Count(); if (userCount > 10) { return "Total user count is " + userCount + ". Aborting broadcast to save your quota"; } else { TimelineItem item = new TimelineItem() { Text = "Hello Everyone!", Notification = new NotificationConfig() { Level = "DEFAULT" } }; foreach (StoredCredentials creds in db.StoredCredentialSet) { AuthorizationState state = new AuthorizationState() { AccessToken = creds.AccessToken, RefreshToken = creds.RefreshToken }; MirrorService service = new MirrorService(new BaseClientService.Initializer() { Authenticator = Utils.GetAuthenticatorFromState(state) }); service.Timeline.Insert(item).Fetch(); } return "Successfully sent cards to " + userCount + " users."; } }
/// <summary> /// Bootstrap the user with a welcome message; if not running locally, this method also /// adds a sharing contact and subscribes to timeline notifications. /// </summary> /// <param name="mirrorService">Authorized Mirror service object</param> /// <param name="userId">ID of the user being bootstrapped.</param> private void BootstrapUser(MirrorService mirrorService, String userId) { if (Request.IsSecureConnection && !Request.IsLocal) { // Insert a subscription. Subscription subscription = new Subscription() { Collection = "timeline", UserToken = userId, CallbackUrl = Url.Action("notify", null, null, Request.Url.Scheme) }; mirrorService.Subscriptions.Insert(subscription).Fetch(); // Insert a sharing contact. UriBuilder builder = new UriBuilder(Request.Url); builder.Path = Url.Content("~/Content/img/dotnet.png"); Contact contact = new Contact() { Id = ".NET Quick Start", DisplayName = ".NET Quick Start", ImageUrls = new List<String>() { builder.ToString() } }; mirrorService.Contacts.Insert(contact).Fetch(); } else { Console.WriteLine("Post auth tasks are not supported on staging."); } TimelineItem item = new TimelineItem() { Text = "Welcome to the .NET Quick Start", Notification = new NotificationConfig() { Level = "DEFAULT" } }; mirrorService.Timeline.Insert(item).Fetch(); }
public static void PrintAttachmentMetadata(MirrorService service, String itemId, String attachmentId) { try { // Get the attachment from the API. Attachment attachment = service.Timeline.Attachments.Get(itemId, attachmentId).Fetch(); // Print some stuff about it. Meh. Console.WriteLine("Attachment content type: " + attachment.ContentType); Console.WriteLine("Attachment content URL: " + attachment.ContentUrl); // Only works for images at the moment. if (attachment.ContentType == "image/jpeg") { // I had this just download to my desktop for the moment. string filename = @"C:\Users\Sean\Desktop\" + attachment.Id.TrimStart("ps:".ToCharArray()) + @".jpeg"; Stream stream = DownloadAttachment(service, attachment); FileStream fs = System.IO.File.Create(filename); int count = 0; do { byte[] buf = new byte[1024]; count = stream.Read(buf, 0, 1024); fs.Write(buf, 0, count); } while (stream.CanRead && count > 0); stream.Close(); fs.Close(); } } catch (Exception e) { Console.WriteLine("An error occurred: " + e.Message); } }
public async Task<ActionResult> MirrorTimeline(MirrorTimeline mirrorTimeline) { var userCredentials = (Google.Apis.Auth.OAuth2.UserCredential)Session["UserCredentials"]; if(userCredentials != null) { if (ModelState.IsValid) { var mirrorService = new MirrorService(new BaseClientService.Initializer { HttpClientInitializer = userCredentials, ApplicationName = this.ApplicationName }); var timelineItem = new TimelineItem(); timelineItem.Html = string.Format(@"<article class='author'> <img src='http://www.w3walls.com/wp-content/uploads/2013/02/blue-lines-abstract-wallpaper.jpg' width='100%' height='100%'> <div class='overlay-full'/> <header> <img src='http://i.imgur.com/g98DNpD.jpg'/> <h1>@jamesduvall</h1> <h2>Oakdale, California</h2> </header> <section> <p class='text-auto-size'>{0}</p> </section> </article> ", mirrorTimeline.Message); var insertTask = mirrorService.Timeline.Insert(timelineItem).ExecuteAsync(); mirrorTimeline = new ViewModels.MirrorTimeline() { Message = string.Empty, Location = await this.GetMirrorLocationAsync(userCredentials) }; await insertTask; } } return View(mirrorTimeline); }