static async Task Main(string[] args) { UserCredential credential; using (var stream = new FileStream("client_id.json", FileMode.Open, FileAccess.Read)) { credential = await GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, new[] { FitnessService.Scope.FitnessBodyWrite }, "user", CancellationToken.None); } var service = new FitnessService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "Fit Cleanup" }); var dataSource = service.Users.DataSources.DataPointChanges.List("me", VeryfitWeight).Execute(); Console.WriteLine($"Got {dataSource.InsertedDataPoint.Count} points"); var startTime = dataSource.InsertedDataPoint.Min(p => p.StartTimeNanos); var endTime = dataSource.InsertedDataPoint.Max(p => p.EndTimeNanos); if (startTime.HasValue && endTime.HasValue) { Console.WriteLine("Deleting points"); var response = service.Users.DataSources.Datasets.Delete("me", VeryfitWeight, $"{startTime.Value}-{endTime.Value}").Execute(); } Console.WriteLine("Press enter to exit."); Console.ReadLine(); }
public IHttpActionResult GetId(int fitId) { FitnessService fitService = CreateFitService(); var fit = fitService.GetFitById(fitId); return(Ok(fit)); }
public IHttpActionResult GetId(int fitId) { FitnessService fitnessService = CreateFitnessService(); var plan = fitnessService.GetFitnessById(fitId); return(Ok(plan)); }
/// <summary> /// Authenticate to Google Using Oauth2 /// Documentation https://developers.google.com/accounts/docs/OAuth2 /// </summary> /// <param name="clientId">From Google Developer console https://console.developers.google.com</param> /// <param name="clientSecret">From Google Developer console https://console.developers.google.com</param> /// <param name="userName">A string used to identify a user.</param> /// <returns></returns> public static FitnessService AuthenticateOauth(string clientId, string clientSecret, string userName) { string[] scopes = new string[] { FitnessService.Scope.FitnessActivityRead, // view and manage your analytics data FitnessService.Scope.FitnessActivityWrite, // edit management actives FitnessService.Scope.FitnessBodyRead, // manage users FitnessService.Scope.FitnessBodyWrite, FitnessService.Scope.FitnessLocationRead, FitnessService.Scope.FitnessLocationWrite }; // View analytics data try { // here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData% UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = clientId, ClientSecret = clientSecret } , scopes , userName , CancellationToken.None , new FileDataStore("Daimto.GoogleFitness.Auth.Store")).Result; FitnessService service = new FitnessService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "Fitness API Sample", }); return(service); } catch (Exception ex) { Console.WriteLine(ex.InnerException); return(null); } }
public IHttpActionResult GetAll() { FitnessService fitnessService = CreateFitnessService(); var fitnessPlans = fitnessService.GetFitness(); return(Ok(fitnessPlans)); }
private async Task Run() { UserCredential credential; credential = await GoogleWebAuthorizationBroker.AuthorizeAsync( new ClientSecrets { ClientId = ConfigurationManager.AppSettings["ClientId"], ClientSecret = ConfigurationManager.AppSettings["ClientSecret"] }, new[] { FitnessService.Scope.FitnessBodyRead }, "user", CancellationToken.None, new FileDataStore("Fitness")); // Create the service. var service = new FitnessService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "Google Fit to Strava weight Sync", }); var start = UnixTime(int.Parse(ConfigurationManager.AppSettings["StartMonth"])); var end = UnixTime(int.Parse(ConfigurationManager.AppSettings["EndMonth"])); string mainUri = ConfigurationManager.AppSettings["mainUri"]; string uri = $"{mainUri}{start}-{end}"; var responseMessage = await service.HttpClient.GetAsync(uri); if (responseMessage.IsSuccessStatusCode) { var ds = responseMessage.Content.ReadAsAsync <Dataset>().Result; weight = ds.Point[ds.Point.Count - 1].Value[0].FpVal.Value; } }
private FitnessService CreateFitnessService() { var userId = User.Identity.GetUserId(); var fitnessService = new FitnessService(userId); return(fitnessService); }
public override void Load() { // ViewModels //Bind<SignInViewModel>().ToSelf(); Bind <MainViewModel>().ToSelf(); Bind <WorkoutDetailViewModel>().ToSelf(); Bind <NewWorkoutViewModel>().ToSelf(); Bind <NewExerciseViewModel>().ToSelf(); Bind <LandingViewModel>().ToSelf(); Bind <SignupViewModel>().ToSelf(); Bind <UserDetailViewModel>().ToSelf(); //var baseUrl = "https://jcmfitnessapi.herokuapp.com"; var baseUrl = "https://jcmfitness1.azurewebsites.net"; //var apiAuthToken = Preferences.Get("apitoken", ""); var settings = new RefitSettings(new NewtonsoftJsonContentSerializer()); JsonConvert.DefaultSettings = () => new JsonSerializerSettings() { ContractResolver = new CamelCasePropertyNamesContractResolver(), Converters = { new StringEnumConverter() } }; IFitApi refitInstance = RestService.For <IFitApi>(baseUrl, settings); var tripLogService = new FitnessService(refitInstance); var localDBService = new LocalDatabase(); var SyncService = new SyncService(tripLogService, localDBService); /*var fitApiService = new IFitApi(); * * containerBuilder.RegisterInstance(refitInstance) * .As<IFitApi>();*/ Bind <Akavache.IBlobCache>().ToConstant(Akavache.BlobCache.LocalMachine); //Bind<IAuthService>().To<AuthService>().InSingletonScope(); Bind <IFitnessService>() .ToMethod(x => tripLogService) .InSingletonScope(); Bind <ILocalDatabase>() .ToMethod(x => localDBService) .InSingletonScope(); Bind <ISyncService>() .ToMethod(x => SyncService) .InSingletonScope(); }
/// <summary> /// Gets the heart rate. /// </summary> /// <param name="startDate">The start date.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// Heartrate data in JSON format. /// </returns> public async Task <JsonResult> GetHeartRate(string startDate, CancellationToken cancellationToken) { var authResult = await new AuthorizationCodeMvcApp(this, new AppFlowMetadata()) .AuthorizeAsync(cancellationToken); if (authResult.Credential != null) { try { var service = new FitnessService(new BaseClientService.Initializer { ApiKey = GoogleClientSettings.ApiKey, ApplicationName = GoogleClientSettings.ApplicationName, HttpClientInitializer = authResult.Credential }); var date = DateTime.Parse(startDate).Date.ToUniversalTime(); var query = new HeartRateQuery(service); var data = query.QueryHeartRate(date, date.AddDays(1)); var dataTabe = new GoogleVisualizationDataTable(); dataTabe.AddColumn("Time", "string"); dataTabe.AddColumn("Heartrate", "number"); foreach (var dataPoint in data) { var values = new List <object> { dataPoint.TimeStamp.ToLocalTime().ToString("t"), dataPoint.BPM }; dataTabe.AddRow(values); } return(Json(dataTabe, JsonRequestBehavior.AllowGet)); } catch (Exception e) { Debug.WriteLine("e: " + e.Message); return(Json(string.Empty)); } } return(Json(string.Empty)); }
public async Task TestingUserWorkouts() { var newsMock = new Mock <IFitApi>(); var ExpectedWorkouts = new List <Workout>() { new Workout { WorkoutID = "1", Name = "Run", Description = "Short description here", Category = "Sport" }, new Workout { WorkoutID = "2", Name = "Walk", Description = "Short description here", Category = "Sport" }, new Workout { WorkoutID = "3", Name = "Sleep", Description = "Short description here", Category = "Sport" }, new Workout { WorkoutID = "4", Name = "Eat", Description = "Short description here", Category = "Sport" }, }; var fitnessService = new FitnessService(newsMock.Object); var NavService = new Mock <INavService>(); var BlobCache = new Mock <IBlobCache>(); var LocalDB = new Mock <ILocalDatabase>(); var SyncService = new Mock <ISyncService>(); newsMock.Setup(m => m.GetUserWorkoutsAsync("1")).ReturnsAsync(ExpectedWorkouts); var vm = new MainViewModel(NavService.Object, fitnessService, BlobCache.Object, LocalDB.Object, SyncService.Object); await vm.LoadEntriesAsync(); vm.UserWorkouts.Should().BeEquivalentTo(ExpectedWorkouts); }
public async Task TestingWorkoutExercises() { var newsMock = new Mock <IFitApi>(); var fitnessService = new FitnessService(newsMock.Object); var NavService = new Mock <INavService>(); var BlobCache = new Mock <IBlobCache>(); var LocalDB = new Mock <ILocalDatabase>(); var SyncService = new Mock <ISyncService>(); var ExpectedExercises = new List <Exercise>() { new Exercise { ExerciseID = "1", Name = "Run ex1" }, new Exercise { ExerciseID = "2", Name = "Run ex2" }, new Exercise { ExerciseID = "3", Name = "Run ex3" }, new Exercise { ExerciseID = "4", Name = "Run ex4" }, new Exercise { ExerciseID = "5", Name = "Run ex5" }, new Exercise { ExerciseID = "6", Name = "Run ex6" } }; newsMock.Setup(m => m.GetWorkoutExercisesAsync("1")).ReturnsAsync(ExpectedExercises); var vm = new WorkoutDetailViewModel(NavService.Object, fitnessService, LocalDB.Object); await vm.LoadExercises("1"); vm.WorkoutExercises.Should().BeEquivalentTo(ExpectedExercises); }
/// <summary> /// Authenticating to Google using a Service account /// Documentation: https://developers.google.com/accounts/docs/OAuth2#serviceaccount /// </summary> /// <param name="serviceAccountEmail">From Google Developer console https://console.developers.google.com</param> /// <param name="keyFilePath">Location of the Service account key file downloaded from Google Developer console https://console.developers.google.com</param> /// <returns></returns> public static FitnessService AuthenticateServiceAccount(string serviceAccountEmail, string keyFilePath) { // check the file exists if (!File.Exists(keyFilePath)) { Console.WriteLine("An Error occurred - Key file does not exist"); return(null); } string[] scopes = new string[] { FitnessService.Scope.FitnessActivityRead, // view and manage your analytics data FitnessService.Scope.FitnessActivityWrite, // edit management actives FitnessService.Scope.FitnessBodyRead, // manage users FitnessService.Scope.FitnessBodyWrite, FitnessService.Scope.FitnessLocationRead, FitnessService.Scope.FitnessLocationWrite }; // View analytics data var certificate = new X509Certificate2(keyFilePath, "notasecret", X509KeyStorageFlags.Exportable); try { ServiceAccountCredential credential = new ServiceAccountCredential( new ServiceAccountCredential.Initializer(serviceAccountEmail) { Scopes = scopes }.FromCertificate(certificate)); // Create the service. FitnessService service = new FitnessService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "Fitness API Sample", }); return(service); } catch (Exception ex) { Console.WriteLine(ex.InnerException); return(null); } }
static async Task Main(string[] args) { UserCredential credential; using (var stream = new FileStream("client_id.json", FileMode.Open, FileAccess.Read)) { credential = await GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, new[] { FitnessService.Scope.FitnessBodyWrite }, "user", CancellationToken.None); } var service = new FitnessService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "Fit Importer" }); var points = JsonConvert.DeserializeObject <List <DataPoint> >(File.ReadAllText("import.json")); var dataSet = new Dataset() { DataSourceId = WeightUserInput, MaxEndTimeNs = points.Max(p => p.EndTimeNanos.Value), MinStartTimeNs = points.Min(p => p.StartTimeNanos.Value), Point = points }; Console.WriteLine($"Importing {dataSet.Point.Count} data points"); var response = service .Users .DataSources .Datasets .Patch(dataSet, "me", WeightUserInput, $"{points.Min(p => p.StartTimeNanos.Value)}-{points.Max(p => p.EndTimeNanos.Value)}") .Execute(); Console.WriteLine("Press enter to exit."); Console.ReadLine(); }
/// <summary> /// Authenticate to Google Using Oauth2 /// Documentation https://developers.google.com/accounts/docs/OAuth2 /// </summary> /// <param name="clientId">From Google Developer console https://console.developers.google.com</param> /// <param name="clientSecret">From Google Developer console https://console.developers.google.com</param> /// <param name="userName">A string used to identify a user.</param> /// <returns></returns> public static FitnessService AuthenticateOauth(string clientId, string clientSecret, string userName) { string[] scopes = new string[] { FitnessService.Scope.FitnessActivityRead , // view and manage your analytics data FitnessService.Scope.FitnessActivityWrite, // edit management actives FitnessService.Scope.FitnessBodyRead, // manage users FitnessService.Scope.FitnessBodyWrite, FitnessService.Scope.FitnessLocationRead, FitnessService.Scope.FitnessLocationWrite}; // View analytics data try { // here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData% UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = clientId, ClientSecret = clientSecret } , scopes , userName , CancellationToken.None , new FileDataStore("Daimto.GoogleFitness.Auth.Store")).Result; FitnessService service = new FitnessService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "Fitness API Sample", }); return service; } catch (Exception ex) { Console.WriteLine(ex.InnerException); return null; } }
/// <summary> /// GoogleFit投稿処理 /// </summary> /// <param name="config"></param> /// <returns></returns> public static async Task postGoogleFit(IConfiguration config) { UserCredential credential; credential = await GoogleWebAuthorizationBroker.AuthorizeAsync( new ClientSecrets { ClientId = config.GetSection("AppSettings")["ClientId"], ClientSecret = config.GetSection("AppSettings")["ClientSecret"] }, new string[] { FitnessService.Scope.FitnessBodyRead, FitnessService.Scope.FitnessBodyWrite }, "user", CancellationToken.None, new FileDataStore("GoogleFitnessAuth", true)//trueにするとカレントパスに保存 ); var fitnessService = new FitnessService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = Assembly.GetExecutingAssembly().GetName().Name }); var dataSource = new DataSource() { Type = "derived", DataStreamName = "GoogieFitTestDataSource", Application = new Application() { Name = "TanitaHealthPlanet", Version = "1" }, DataType = new DataType() { Name = dataTypeName, Field = new List <DataTypeField>() { new DataTypeField() { Name = "weight", Format = "floatPoint" } } }, Device = new Device() { Manufacturer = "Tanita", Model = "RD-906", Type = "scale", Uid = "1000001", Version = "1.0" } }; var dataSourceId = $"{dataSource.Type}:{dataSource.DataType.Name}:{config.GetSection("AppSettings")["ClientId"].Split('-')[0]}:{dataSource.Device.Manufacturer}:{dataSource.Device.Model}:{dataSource.Device.Uid}:{dataSource.DataStreamName}"; var dataSrcList = await fitnessService.Users.DataSources.List(userId).ExecuteAsync(); if (dataSrcList.DataSource.Select(s => s.DataStreamId).Any(s => s == dataSourceId)) { dataSource = fitnessService.Users.DataSources.Get(userId, dataSourceId).Execute(); } else { dataSource = fitnessService.Users.DataSources.Create(dataSource, userId).Execute(); } var postNanosec = GetUnixEpochNanoSeconds(DateTime.UtcNow); var widthDataSource = new Dataset() { DataSourceId = dataSourceId, MaxEndTimeNs = postNanosec, MinStartTimeNs = postNanosec, Point = new List <DataPoint>() { new DataPoint() { DataTypeName = dataTypeName, StartTimeNanos = postNanosec, EndTimeNanos = postNanosec, Value = new List <Value>() { new Value() { FpVal = 80.0 } } } } }; var dataSetId = $"{postNanosec}-{postNanosec}"; await fitnessService.Users.DataSources.Datasets.Patch(widthDataSource, userId, dataSourceId, dataSetId).ExecuteAsync(); }
/// <summary> /// Initializes a new instance of the <see cref="FitnessQuery"/> class. /// </summary> /// <param name="service">The service.</param> /// <param name="dataSourceId">The data source identifier.</param> /// <param name="dataType">Type of the data.</param> protected FitnessQuery(FitnessService service, string dataSourceId, string dataType) { _service = service; _dataSourceId = dataSourceId; _dataType = dataType; }
public void Init() { try { string[] scopes = new string[] { FitnessService.Scope.FitnessBodyWrite, FitnessService.Scope.FitnessBodyRead, }; // here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData% var credential = GoogleWebAuthorizationBroker.AuthorizeAsync ( new ClientSecrets { ClientId = clientId, ClientSecret = clientSecret }, scopes, UserName, CancellationToken.None, new FileDataStore("Google.Fitness.Auth", false) ).Result; service = new FitnessService(new BaseClientService.Initializer() { ApplicationName = Assembly.GetExecutingAssembly().GetName().Name, HttpClientInitializer = credential }); dataSource = new DataSource() { Type = "raw", DataStreamName = "GoogleFitEmotivDataSource", Application = new Application() { Name = service.ApplicationName, Version = "1" }, DataType = new DataType() { Name = "sk.scholtz.emotive.cognitivestate", Field = new List <DataTypeField>() { new DataTypeField() { Name = "interest", Format = "floatPoint" }, new DataTypeField() { Name = "stress", Format = "floatPoint" }, new DataTypeField() { Name = "relaxation", Format = "floatPoint" }, new DataTypeField() { Name = "excitement", Format = "floatPoint" }, new DataTypeField() { Name = "engagement", Format = "floatPoint" }, new DataTypeField() { Name = "longtermexcitement", Format = "floatPoint" }, new DataTypeField() { Name = "focus", Format = "floatPoint" }, } }, Device = new Device() { Manufacturer = device.Manufacturer, Model = device.Model, Type = device.Type, Uid = device.Uid, Version = device.Version } }; //dataSourceId = $"{dataSource.Type}:{dataSource.DataType.Name}:{userId}:{dataSource.Device.Manufacturer}:{dataSource.Device.Model}:{dataSource.Device.Uid}:{dataSource.DataStreamName}"; //raw:sk.scholtz.emotive.cognitivestate:413883787851:Emotiv:RD-906:1000001:GoogleFitEmotivDataSource var dataSrcList = service.Users.DataSources.List(userId).ExecuteAsync().Result; dataSourceId = dataSrcList.DataSource.Select(s => s.DataStreamId).Where( s => s != null && s.Contains(dataSource.DataStreamName) && s.Contains(dataSource.Device.Manufacturer) && s.Contains(dataSource.Device.Uid)).FirstOrDefault(); if (!string.IsNullOrEmpty(dataSourceId)) { dataSource = service.Users.DataSources.Get(userId, dataSourceId).Execute(); } else { dataSource = service.Users.DataSources.Create(dataSource, userId).Execute(); } } catch (Exception exc) { Console.Error.WriteLine(exc.Message); } }
/// <summary> /// Initializes a new instance of the <see cref="HeartRateQuery" /> class. /// </summary> /// <param name="service">The service.</param> public HeartRateQuery(FitnessService service) : base(service, DataSource, DataType) { }
/// <summary> /// Authenticating to Google using a Service account /// Documentation: https://developers.google.com/accounts/docs/OAuth2#serviceaccount /// </summary> /// <param name="serviceAccountEmail">From Google Developer console https://console.developers.google.com</param> /// <param name="keyFilePath">Location of the Service account key file downloaded from Google Developer console https://console.developers.google.com</param> /// <returns></returns> public static FitnessService AuthenticateServiceAccount(string serviceAccountEmail, string keyFilePath) { // check the file exists if (!File.Exists(keyFilePath)) { Console.WriteLine("An Error occurred - Key file does not exist"); return null; } string[] scopes = new string[] { FitnessService.Scope.FitnessActivityRead , // view and manage your analytics data FitnessService.Scope.FitnessActivityWrite, // edit management actives FitnessService.Scope.FitnessBodyRead, // manage users FitnessService.Scope.FitnessBodyWrite, FitnessService.Scope.FitnessLocationRead, FitnessService.Scope.FitnessLocationWrite}; // View analytics data var certificate = new X509Certificate2(keyFilePath, "notasecret", X509KeyStorageFlags.Exportable); try { ServiceAccountCredential credential = new ServiceAccountCredential( new ServiceAccountCredential.Initializer(serviceAccountEmail) { Scopes = scopes }.FromCertificate(certificate)); // Create the service. FitnessService service = new FitnessService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "Fitness API Sample", }); return service; } catch (Exception ex) { Console.WriteLine(ex.InnerException); return null; } }