-
Notifications
You must be signed in to change notification settings - Fork 4
/
psFitb1t.psm1
1547 lines (1385 loc) · 53 KB
/
psFitb1t.psm1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#=======================================================================#
#
# Author: Collin Chaffin
# Last Modified: 03-13-2016 12:00PM
# Filename: psFitb1t.psm1
#
#
# Changelog:
#
# v 1.0.0.1 : 03-13-2016 : Initial release
# v 1.0.0.2 : 03-30-2016 : Added Get-HRmonth function
#
# Notes:
#
# This module utilizes personal Fitbit's user-specific API
# information to perform OAuth connection to Fitbit and submit the
# request for your heart rate data for any 24 hour period.
#
#
# Installation Instructions:
#
# Run the MSI installer or, if installing manually, copy the
# psFitb1t.psm1 and psFitb1t.psd files to:
# "%PSModulePath%psFitb1t"
#
# HINT: To manually create the module folder prior to copying:
# mkdir "%PSModulePath%psFitb1t"
#
# Once installed/copied, open Windows Powershell and execute:
# Import-Module psFitb1t
#
# Store your Fitbit API information by executing:
# Set-FitbitOAuthTokens
#
# If you have gotten this far, you should be able to query your
# first date by executing:
# Get-HRData -QueryDate "2016-01-01"
#
# Verification:
#
# Check "%PSModulePath%psFitb1t\Logs" folder for a daily rotating log.
# Example log for successful query:
#
# 03/13/2016 12:00:00 :: [INFO] :: START - Get-HRdata function execution
# 03/13/2016 12:00:00 :: [INFO] :: START - Connect-OAuthFitbit function execution
# 03/13/2016 12:00:00 :: [INFO] :: START - Loading DOTNET assemblies
# 03/13/2016 12:00:00 :: [INFO] :: FINISH - Loading DOTNET assemblies
# 03/13/2016 12:00:00 :: [INFO] :: START - Retrieving Fitbit API settings from registry
# 03/13/2016 12:00:00 :: [INFO] :: FINISH - Retrieving Fitbit API settings from registry
# 03/13/2016 12:00:01 :: [INFO] :: FINISH - Connect-OAuthFitbit function execution
# 03/13/2016 12:00:01 :: [INFO] :: START - Sending HTTP POST via REST to Fitbit
# 03/04/2016 12:00:44 :: [INFO] :: FINISH - Sending HTTP POST via REST to Fitbit
# 03/04/2016 12:00:44 :: [INFO] :: FINISH - Get-HRdata function execution
#
#=======================================================================#
#region Globals
#########################################################################
# Global Variables #
#########################################################################
# General Variables
# Disable psFitb1tDebugging for zero output and logging
$psFitb1tDebugging = $true
$psFitb1tLogging = $true
$Script:psFitb1tScope = "activity%20heartrate%20location%20nutrition%20profile%20settings%20sleep%20social%20weight"
$Script:psFitb1tTokenAge = "2592000"
#You should only have to change this redirect URL if you did not follow the directions and set it to this predetermined value:
$Script:psFitb1tRedirectURL = "https://localhost/psfitb1t"
$Script:psFitb1tHRQueryDate = ""
$Script:psFitb1tTokenReturnedAge = ""
$Script:psFitb1tAuthCode = ""
#Auth URL First
#$Script:psFitb1tAuthorizeUrl = "https://www.fitbit.com/oauth2/authorize?response_type=token&client_id=$psFitb1tClientID&redirect_uri=$psFitb1tRedirectURL&scope=$psFitb1tScope&expires_in=$psFitb1tTokenAge"
# Paths
$Script:psFitb1tInvocationPath = $([System.IO.Path]::GetDirectoryName($MyInvocation.MyCommand.Definition) + "\")
$Script:psFitb1tLogPath = $($psFitb1tInvocationPath) + "Logs\"
# Override this with a static manual path, if so desired or it defaults to \Logs folder in Module location
#########################################################################
#endregion
#region Functions
#########################################################################
# Functions #
#########################################################################
function Connect-OAuthFitbit
{
<#
.SYNOPSIS
This function utilizes personal Fitbit's user-specific API information to perform
OAuth connection to Fitbit and set up the final OAuth string needed to then retrieve
24hrs of HR data using the REST API.
.DESCRIPTION
Author: Collin Chaffin
Description: This function utilizes personal Fitbit's user-specific API
information to perform OAuth connection to Fitbit.
#>
[CmdletBinding()]
[OutputType([System.String])]
param (
)
BEGIN
{
(Write-Status -Message "START - Connect-OAuthFitbit function execution" -Status "INFO" -Debugging:$psFitb1tDebugging -Logging:$psFitb1tLogging -Logpath $psFitb1tLogPath)
try
{
(Write-Status -Message "START - Loading DOTNET assemblies" -Status "INFO" -Debugging:$psFitb1tDebugging -Logging:$psFitb1tLogging -Logpath $psFitb1tLogPath)
[Reflection.Assembly]::LoadWithPartialName("System.Security") | Out-Null
[Reflection.Assembly]::LoadWithPartialName("System.Net") | Out-Null
[Reflection.Assembly]::LoadWithPartialName("System.Web") | Out-Null
(Write-Status -Message "FINISH - Loading DOTNET assemblies" -Status "INFO" -Debugging:$psFitb1tDebugging -Logging:$psFitb1tLogging -Logpath $psFitb1tLogPath)
}
catch
{
Throw $("ERROR OCCURRED WHILE LOADING REQUIRED DOTNET ASSEMBLIES " + $_.Exception.Message)
}
# Retrieve required user-specific Fitbit API info from registry
try
{
if ($((Test-Path -Path HKCU:\Software\psFitb1t) -eq $false) `
-or $((Get-Item HKCU:\Software\psFitb1t).getvalue("psFitb1tClientID") -eq $null) `
-or $((Get-Item HKCU:\Software\psFitb1t).getvalue("psFitb1tRedirectURL") -eq $null)
)
{
(Write-Status -Message "Fitbit API settings not found - prompting operator" -Status "WARNING" -Debugging:$psFitb1tDebugging -Logging:$psFitb1tLogging -Logpath $psFitb1tLogPath)
# Call Set-FitbitOAuthTokens function to prompt for credentials and store them
Set-FitbitOAuthTokens
}
else
{
(Write-Status -Message "START - Retrieving Fitbit API settings from registry" -Status "INFO" -Debugging:$psFitb1tDebugging -Logging:$psFitb1tLogging -Logpath $psFitb1tLogPath)
$Script:psFitb1tClientID = (Get-Item HKCU:\Software\psFitb1t).getvalue("psFitb1tClientID")
$Script:psFitb1tRedirectURL = (Get-Item HKCU:\Software\psFitb1t).getvalue("psFitb1tRedirectURL")
$Script:psFitb1tTokenReturnedAge = (Get-Item HKCU:\Software\psFitb1t).getvalue("psFitb1tTokenAge")
$Script:psFitb1tAuthToken = (Get-Item HKCU:\Software\psFitb1t).getvalue("psFitb1tAuthToken")
(Write-Status -Message "FINISH - Retrieving Fitbit API settings from registry" -Status "INFO" -Debugging:$psFitb1tDebugging -Logging:$psFitb1tLogging -Logpath $psFitb1tLogPath)
}
}
catch
{
Throw $("ERROR OCCURRED WHILE LOADING REQUIRED FITBIT API INFORMATION " + $_.Exception.Message)
}
}
PROCESS
{
try
{
# Create a custom PSObject to store all require oAuth info and simply pass a single object to helper functions
$objOAuth = @()
$objOAuth = New-Object -TypeName PSObject
$objOAuth | Add-Member -Name 'client_id' -Value $($psFitb1tClientID) -MemberType NoteProperty -Force
$objOAuth | Add-Member -Name 'redirect_uri' -Value $($psFitb1tRedirectURL) -MemberType NoteProperty -Force
$objOAuth | Add-Member -Name 'scope' -Value $($psFitb1tScope) -MemberType NoteProperty -Force
$objOAuth | Add-Member -Name 'expires_in' -Value $($psFitb1tTokenAge) -MemberType NoteProperty -Force
$objOAuth | Add-Member -Name 'token_remaining' -Value $($psFitb1tTokenReturnedAge) -MemberType NoteProperty -Force
$objOAuth | Add-Member -Name 'date' -Value $($psFitb1tHRQueryDate) -MemberType NoteProperty -Force
$objOAuth | Add-Member -Name 'access_token' -Value $($psFitb1tAuthToken) -MemberType NoteProperty -Force
#Do we have a good token already? Check registry
if ($($Script:psFitb1tTokenReturnedAge) -and $(Test-Date -inputDate $Script:psFitb1tTokenReturnedAge) -and $( [DateTime]$(get-date ([System.DateTime]::Now) -Format s) -lt [DateTime]$(Get-Date($psFitb1tTokenReturnedAge)) ) )
{
write-verbose "Token Okay"
[string]$oAuthRequestString = $psFitb1tAuthToken
}
else
{
write-verbose "Token Expired $($Script:psFitb1tTokenReturnedAge)"
# Finally, generate the final OAuth request string with all the above generated information passing one single custom PSObject
[string]$oAuthRequestString = (Get-FitbitOAuthToken -objOAuth $objOAuth)
}
# Return the one single oAuth request POST string to hand back to calling function (tweet or direct message) to POST it
Return $oAuthRequestString;
}
catch
{
Throw $("ERROR OCCURRED WHILE BUILDING OAUTH REQUEST " + $_.Exception.Message)
}
}
END
{
(Write-Status -Message "FINISH - Connect-OAuthFitbit function execution" -Status "INFO" -Debugging:$psFitb1tDebugging -Logging:$psFitb1tLogging -Logpath $psFitb1tLogPath)
}
}
function Get-FitbitOAuthToken
{
<#
.SYNOPSIS
Generate a new Fitbit oAuth2 token or used stored
.DESCRIPTION
Author: Collin Chaffin
Description: This function generates a new Fitbit oAuth2 token or used stored
.PARAMETER objOAuth
[PSObject] Custom PSObject containing all required OAuth information
.EXAMPLE
$oAuthSignature = (Get-FitbitOAuthToken -objOAuth $objOAuth)
$oAuthSignature
ptUHUftvP0l635876583ygrgg346JQoJ+7yBa//uZcE=
#>
[CmdletBinding()]
[OutputType([String])]
param (
[Parameter(Position = 0, Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[PSObject]
$objOAuth
)
BEGIN
{
(Write-Status -Message "START - Get-FitbitOAuthToken function execution" -Status "INFO" -Debugging:$psFitb1tDebugging -Logging:$psFitb1tLogging -Logpath $psFitb1tLogPath)
}
PROCESS
{
try
{
(Write-Status -Message "START - Building OAuth signature" -Status "INFO" -Debugging:$psFitb1tDebugging -Logging:$psFitb1tLogging -Logpath $psFitb1tLogPath)
# Make GET request to have user authorize and parse for token returned - run with -VERBOSE switch to view the string actually being sent!
$Script:psFitb1tAuthorizeUrl = "https://www.fitbit.com/oauth2/authorize?response_type=token&client_id=$psFitb1tClientID&redirect_uri=$psFitb1tRedirectURL&scope=$psFitb1tScope&expires_in=$psFitb1tTokenAge"
Write-Verbose "Sending $($psFitb1tAuthorizeUrl)"
Add-Type -AssemblyName System.Windows.Forms
$form = New-Object -TypeName System.Windows.Forms.Form -Property @{ Width = 440; Height = 640 }
$browser = New-Object -TypeName System.Windows.Forms.WebBrowser -Property @{ Width = 420; Height = 600; Url = $psFitb1tAuthorizeUrl }
$onDocumentCompleted = {
$myurl = $browser.Url.AbsoluteUri
if ($browser.Url.AbsoluteUri -match "access_token=([^&]*)")
{
#Get the magic token
$Script:psFitb1tAuthCode = $Matches[1]
if ($browser.Url.AbsoluteUri -match "expires_in=([^&]*)")
{
$Script:psFitb1tTokenReturnedAge = $(get-date ([System.DateTime]::Now).AddSeconds([int]$Matches[1]) -Format s)
Write-Verbose "Token expires: $($Script:psFitb1tTokenReturnedAge)"
#write $Script:psFitb1tTokenReturnedAge to registry
New-ItemProperty HKCU:\Software\psFitb1t -name "psFitb1tTokenAge" -value "$Script:psFitb1tTokenReturnedAge" -Force | out-null
#write $Script:psFitb1tAuthToken to registry
New-ItemProperty HKCU:\Software\psFitb1t -name "psFitb1tAuthToken" -value "$Script:psFitb1tAuthCode" -Force | out-null
$form.Close()
}
#Close it
$form.Close()
}
elseif ($browser.Url.AbsoluteUri -match "error=")
{
$form.Close()
}
}
$browser.add_DocumentCompleted($onDocumentCompleted)
$form.Controls.Add($browser)
$null = $form.ShowDialog()
Write-Verbose "Auth Code is: $($psFitb1tAuthCode)"
(Write-Status -Message "FINISH - Building OAuth signature" -Status "INFO" -Debugging:$psFitb1tDebugging -Logging:$psFitb1tLogging -Logpath $psFitb1tLogPath)
return $psFitb1tAuthCode;
}
catch
{
Throw $("ERROR OCCURRED GENERATING NEW OAUTH SIGNATURE " + $_.Exception.Message)
}
}
END
{
(Write-Status -Message "FINISH - Get-FitbitOAuthToken function execution" -Status "INFO" -Debugging:$psFitb1tDebugging -Logging:$psFitb1tLogging -Logpath $psFitb1tLogPath)
}
}
function Test-Date
{
<#
.SYNOPSIS
Test if date is valid
.DESCRIPTION
Author: Collin Chaffin
Description: This function tests if date is valid
.PARAMETER inputDate
[String] Date STRING to test with different possible formats
.EXAMPLE
Test-Date -inputDate "2016-03-29T03:23:28"
#>
param
(
[Parameter(Mandatory = $true)]
$inputDate
)
(($inputDate -as [DateTime]) -ne $null)
}
function Write-Status
{
<#
.SYNOPSIS
Write a status message to console and log if debugging
.DESCRIPTION
Author: Collin Chaffin
Description: This function writes a status message out to console
appending exact time/date of command execution and will
optionally write to daily log
.PARAMETER Message
[String] Message to write
.PARAMETER Status
[String] Status code string
.PARAMETER Debugging
[Bool] If this switch is true then output debugging to console
.EXAMPLE
Write-Status -Message "Action completed successfully" -Status "SUCCESS" -Debugging $debugging
03/13/2016 12:00:00 :: [SUCCESS] :: Action completed successfully
#>
[CmdletBinding()]
[OutputType([System.String])]
param (
[Parameter(Position = 0, Mandatory = $true, ValueFromPipeline = $true)]
[System.String]
$Message,
[Parameter(Mandatory = $false)]
[System.String]
$Status = "INFO",
[Parameter(Mandatory = $false)]
[Switch]
$Debugging,
[Parameter(Mandatory = $false)]
[Switch]
$Logging,
[Parameter(Mandatory = $false)]
[System.String]
$LogPath = $(($psFitb1tInvocationPath) + "Logs\")
)
BEGIN
{
try
{
# Do not do anything unless global script debugging is true
If ($Debugging -eq $true)
{
# Set up variables and log file/path
[String]$statusTime = (Get-Date -Format "MM/dd/yyyy HH:mm:ss")
# If -Logging passed, set up logging a a DAILY log file (change path in globals at top of script)
if ($Logging -eq $true)
{
If (!(Test-Path $psFitb1tLogPath)) { New-Item -ItemType Directory -Force -Path ($psFitb1tLogPath) | Out-Null }
[String]$logFileDate = (Get-Date -Format "MM-dd-yyyy")
[String]$logFile = $($psFitb1tLogPath) + "psFitb1t-" + $logFileDate + ".log"
}
}
}
catch
{
Throw $("ERROR OCCURRED WHILE WRITING OUTPUT " + $_.Exception.Message)
}
}
PROCESS
{
try
{
# Do not do anything unless global script debugging is true
If ($Debugging -eq $true)
{
# Ensure custom status is always uppercase
$Status = $Status.ToUpper()
# Format output message
$Message = "$statusTime :: [$Status] :: $Message"
# Write out to console
Write-Host $Message -ForegroundColor Cyan
# If -Logging passed, set up logging a a DAILY log file (change path in globals at top of script)
if ($Logging -eq $true)
{
Add-Content -Path $logFile -Value ($Message)
}
}
}
catch
{
Throw $("ERROR OCCURRED WRITING STATUS" + $_.Exception.Message)
}
}
END
{
}
}
Function Set-FitbitOAuthTokens
{
<#
.SYNOPSIS
Stores required Fitbit API OAuth settings providing both GUI wizard and
command-line options
.DESCRIPTION
Author: Collin Chaffin
Description: This function stores the required Fitbit API settings
provided by the operator interactively into the HKCU
registry hive for subsequent sessions providing both
GUI wizard and command-line options
.PARAMETER Force
[Switch] Clear existing stored Fitbit API information and repopulate
.PARAMETER psFitb1tClientID
[String] Fitbit Client ID
.PARAMETER psFitb1tRedirectURL
[String] Fitbit Redirection URL
.PARAMETER psFitb1tHRQueryDate
[String] Fitbit Last Query Date
.PARAMETER psFitb1tTokenAge
[String] Fitbit Access Token Expiration Datetime
.EXAMPLE
Set-FitbitOAuthTokens
If Fitbit API settings are not found in the registry, prompt the operator
interactively via a GUI wizard to provide and open the Fitbit API webpage
to assist operator in locating their user-specific Fitbit application information
NOTE: Only missing information will be requested via wizard interface
.EXAMPLE
Set-FitbitOAuthTokens -Force
Remove existing Fitbit API information from registry and repopulate via
GUI wizard
.EXAMPLE
Set-FitbitOAuthTokens -Force -psFitb1tClientID "01234567890"
Remove existing Fitbit API information from registry and repopulate via
automatically detected "command-line" mode. In this case because all
four required pieces of information were not provided, the missing three
will be interactively prompted but via standard commandline text prompting
#>
[CmdletBinding(DefaultParameterSetName = 'Wizard')]
[OutputType([System.String])]
param
(
[Parameter(ParameterSetName = 'CmdLine', Mandatory = $false)]
[Parameter(ParameterSetName = 'Wizard', Mandatory = $false)]
[Switch]
$Force,
[Parameter(ParameterSetName = 'CmdLine', Mandatory = $true, HelpMessage = 'Please enter your Fitbit application CLIENT ID:')]
[ValidateNotNullOrEmpty()]
[System.String]
$psFitb1tClientID,
[Parameter(ParameterSetName = 'CmdLine', Mandatory = $false, HelpMessage = 'Please enter your Fitbit application REDIRECT URL:')]
[ValidateNotNullOrEmpty()]
[System.String]
$psFitb1tRedirectURL = $Script:psFitb1tRedirectURL
)
BEGIN
{
(Write-Status -Message "START - Set-FitbitOAuthTokens function execution" -Status "INFO" -Debugging:$psFitb1tDebugging -Logging:$psFitb1tLogging -Logpath $psFitb1tLogPath)
}
PROCESS
{
# If we were passed -Force switch
if ($Force.IsPresent)
{
try
{
# Force switch used, remove/clear all stored API info and drop to either wizard or cmdline to repopulate
if ($((Get-Item HKCU:\Software\psFitb1t).getvalue("psFitb1tClientID") -ne $null)) { Remove-ItemProperty HKCU:\Software\psFitb1t -name "psFitb1tClientID" }
if ($((Get-Item HKCU:\Software\psFitb1t).getvalue("psFitb1tRedirectURL") -ne $null)) { Remove-ItemProperty HKCU:\Software\psFitb1t -name "psFitb1tRedirectURL" }
if ($((Get-Item HKCU:\Software\psFitb1t).getvalue("psFitb1tHRQueryDate") -ne $null)) { Remove-ItemProperty HKCU:\Software\psFitb1t -name "psFitb1tHRQueryDate" }
if ($((Get-Item HKCU:\Software\psFitb1t).getvalue("psFitb1tTokenAge") -ne $null)) { Remove-ItemProperty HKCU:\Software\psFitb1t -name "psFitb1tTokenAge" }
if ($((Get-Item HKCU:\Software\psFitb1t).getvalue("psFitb1tAuthToken") -ne $null)) { Remove-ItemProperty HKCU:\Software\psFitb1t -name "psFitb1tAuthToken" }
}
catch
{
Throw $("ERROR OCCURRED CLEARING FITBIT API INFORMATION FROM REGISTRY " + $_.Exception.Message)
}
}
# (Re)Populate the registry with 4 pieces of required Fitbit OAuth info
try
{
# If any single piece of info is missing, start the process
if ($((Test-Path -Path HKCU:\Software\psFitb1t) -eq $false) `
-or $((Get-Item HKCU:\Software\psFitb1t).getvalue("psFitb1tClientID") -eq $null) `
-or $((Get-Item HKCU:\Software\psFitb1t).getvalue("psFitb1tRedirectURL") -eq $null)
)
{
Write-Host "`nPlease configure your personal Fitbit application from which you must store the following pieces of information:`n`n""Client ID""`n""Redirect URL""`n`nOpening default browser to: https://dev.fitbit.com" -ForegroundColor Yellow
Start-Process "https://dev.fitbit.com/"
# Entire reg key is missing so create it
if (!(Test-Path -Path HKCU:\Software\psFitb1t))
{
(Write-Status -Message "START - psFitb1t registry key creation" -Status "INFO" -Debugging:$psFitb1tDebugging -Logging:$psFitb1tLogging -Logpath $psFitb1tLogPath)
New-Item -Path HKCU:\Software -Name psFitb1t | out-null
(Write-Status -Message "FINISH - psFitb1t registry key creation" -Status "INFO" -Debugging:$psFitb1tDebugging -Logging:$psFitb1tLogging -Logpath $psFitb1tLogPath)
}
Switch ($PSCmdlet.ParameterSetName)
{
'Wizard'
{
# Now that we are sure reg key exists, call the wizard form and prompt only for missing value(s)
# NOTE: If reg key exists and only 2 pieces of info are missing, operator only receives a wizard with 2 pages with 4 being all info missing
Call-psFitb1t-API_psf | Out-Null
}
'CmdLine'
{
if (!$psFitb1tClientID)
{
Write-Host "`n`nEnter Fitbit Client ID:" -ForegroundColor Yellow -NoNewline
$psFitb1tClientID = Read-Host
if ($psFitb1tClientID) { New-ItemProperty HKCU:\Software\psFitb1t -name "psFitb1tClientID" -value "$psFitb1tClientID" | out-null }
}
else
{
New-ItemProperty HKCU:\Software\psFitb1t -name "psFitb1tClientID" -value "$psFitb1tClientID" | out-null
}
if (! $psFitb1tRedirectURL)
{
Write-Host "Enter Fitbit Redirect URL:" -ForegroundColor Yellow -NoNewline
$psFitb1tRedirectURL = Read-Host
if ($psFitb1tRedirectURL) { New-ItemProperty HKCU:\Software\psFitb1t -name "psFitb1tRedirectURL" -value "$psFitb1tRedirectURL" | out-null }
}
else
{
New-ItemProperty HKCU:\Software\psFitb1t -name "psFitb1tRedirectURL" -value "$psFitb1tRedirectURL" | out-null
}
}
}
}
}
catch
{
Throw $("ERROR OCCURRED WRITING FITBIT API INFORMATION TO REGISTRY " + $_.Exception.Message)
}
finally
{
# Now that the reg values are present regardless of method, read back in the values and set our globals
$Script:psFitb1tClientID = (Get-Item HKCU:\Software\psFitb1t).getvalue("psFitb1tClientID")
$Script:psFitb1tRedirectURL = (Get-Item HKCU:\Software\psFitb1t).getvalue("psFitb1tRedirectURL")
}
}
END
{
(Write-Status -Message "FINISH - Set-FitbitOAuthTokens function execution" -Status "INFO" -Debugging:$psFitb1tDebugging -Logging:$psFitb1tLogging -Logpath $psFitb1tLogPath)
}
}
function Get-HRdata
{
<#
.SYNOPSIS
Sends a Fitbit Tweet
.DESCRIPTION
Author: Collin Chaffin
Description: Sends a request for 24hrs of HR data using OAuth and REST
.PARAMETER QueryDate
The single 24hr Date to retrieve HR data (*FITBIT LIMITATION*) per query
.EXAMPLE
Get-HRdata -QueryDate "2016-03-13"
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $false)]
[ValidateLength(1, 140)]
[String]$QueryDate = $(Get-Date ([System.DateTime]::Now).AddDays(-1) -Format "yyyy-MM-dd")
)
BEGIN
{
(Write-Status -Message "START - Get-HRdata function execution" -Status "INFO" -Debugging:$psFitb1tDebugging -Logging:$psFitb1tLogging -Logpath $psFitb1tLogPath)
}
PROCESS
{
try
{
if (!$(Test-Date -inputDate $QueryDate))
{
[String]$QueryDate = $(Get-Date ([System.DateTime]::Now).AddDays(-1) -Format "yyyy-MM-dd")
}
else
{
[String]$QueryDate = $(Get-Date $QueryDate -Format "yyyy-MM-dd")
}
$Script:psFitb1tHRQueryDate = $QueryDate
# Call our main connect routine to setup the oAuth
$psFitb1tAuthCode = Connect-OAuthFitbit
(Write-Status -Message "START - Sending HTTP POST via REST to Fitbit" -Status "INFO" -Debugging:$psFitb1tDebugging -Logging:$psFitb1tLogging -Logpath $psFitb1tLogPath)
$Script:psFitb1tGetHRurl = "https://api.fitbit.com/1/user/-/activities/heart/date/$($psFitb1tHRQueryDate)/1d/1sec/time/00:00/23:59.json"
Write-Verbose "Sending to URL $($psFitb1tGetHRurl)"
Write-Verbose "This request: Headers=$psFitb1tAuthCode"
# Call the REST API to handle the final OAUTH POST
$retData = Invoke-RestMethod -Method Get -Uri $psFitb1tGetHRurl -Headers @{ 'Authorization' = "Bearer " + $psFitb1tAuthCode } -ContentType "application/x-www-form-urlencoded"
#Write the output
$output = @()
$output = New-Object -TypeName PSObject
#Assign the dataset to custom obj
$output = $retData.'activities-heart-intraday'.dataset
#Add the query date to output object
$output | Add-Member -Name 'Date' -Value $($psFitb1tHRQueryDate) -MemberType NoteProperty -Force
#Write to csv
$output | Export-Csv -NoTypeInformation "$($Script:psFitb1tInvocationPath)FitbitHR_$($psFitb1tHRQueryDate).csv"
#Write to xls
Export-FitbitXLS -objInput $output "$($Script:psFitb1tInvocationPath)FitbitHR_$($psFitb1tHRQueryDate).xlsx" -appendSheet:$false -worksheetName "$psFitb1tHRQueryDate" -chartType "xlLine"
(Write-Status -Message "FINISH - Sending HTTP POST via REST to Fitbit" -Status "INFO" -Debugging:$psFitb1tDebugging -Logging:$psFitb1tLogging -Logpath $psFitb1tLogPath)
}
catch
{
Throw $("ERROR OCCURRED RETRIEVING HR DATA " + $_.Exception.Message)
}
}
END
{
#write last query date to registry
New-ItemProperty HKCU:\Software\psFitb1t -name "psFitb1tHRQueryDate" -value "$Script:psFitb1tHRQueryDate" -Force | out-null
(Write-Status -Message "FINISH - Get-HRdata function execution" -Status "INFO" -Debugging:$psFitb1tDebugging -Logging:$psFitb1tLogging -Logpath $psFitb1tLogPath)
}
}
function Get-HRmonth
{
<#
.SYNOPSIS
Get entire month of heartrate reports via psFitb1t's Get-HRdata
.DESCRIPTION
Determines how many possible days in the requested month and calls psFitb1t's Get-HRdata to retrieve the daily reports. It first verifies if
you have already retrieved any reports for days in the queried month and if so, only processes missing days.
Returns bool for overall success or failure.
.PARAMETER QueryMonth
A description of the QueryMonth parameter.
.EXAMPLE
PS C:\> Get-HRmonth -QueryMonth '2016-01'
This queries all days for January, 2016 that do not already have reports on disk
.NOTES
Requires the primary Get-HRdata retrieval function.
#>
[CmdletBinding()]
[OutputType([bool])]
param
(
[Parameter(Mandatory = $true)]
[System.String]
$QueryMonth = "2016-01" #This will accept mult formats such as "01/2016","2016-01"
)
BEGIN
{
(Write-Status -Message "START - Get-HRmonth function execution" -Status "INFO" -Debugging:$psFitb1tDebugging -Logging:$psFitb1tLogging -Logpath $psFitb1tLogPath)
Import-Module -Name psFitb1t -ea 'Stop' | Out-Null
$nbrDaysInMonth = [DateTime]::DaysInMonth($([DateTime](Get-Date($QueryMonth))).Year, $([Datetime](Get-Date($QueryMonth))).Month)
$daysToProcess = 0
$cntProc = 0
}
PROCESS
{
try
{
(Write-Status -Message "START - Requesting monthly HR data from Fitbit" -Status "INFO" -Debugging:$psFitb1tDebugging -Logging:$psFitb1tLogging -Logpath $psFitb1tLogPath)
#Get total real days to process = days in month minus any existing days already processed
for ($i = 1; $i -le $nbrDaysInMonth; $i++)
{
$day = ("{0:D2}" -f $i)
if (!(Test-Path -Path "$((Get-Module psFitb1t).ModuleBase)\FitbitHR_$(([Datetime](Get-Date($QueryMonth))).ToString('yyyy'))-$(([Datetime](Get-Date($QueryMonth))).ToString('MM'))-$($day).xlsx"))
{
$daysToProcess++
}
}
(Write-Status -Message "START - Requesting $($daysToProcess) days of HR data from Fitbit" -Status "INFO" -Debugging:$psFitb1tDebugging -Logging:$psFitb1tLogging -Logpath $psFitb1tLogPath)
#Process the missing days and provide accurate progress counter based on number computed above
for ($i = 1; $i -le $nbrDaysInMonth; $i++)
{
$day = ("{0:D2}" -f $i)
if (!(Test-Path -Path "$((Get-Module psFitb1t).ModuleBase)\FitbitHR_$(([Datetime](Get-Date($QueryMonth))).ToString('yyyy'))-$(([Datetime](Get-Date($QueryMonth))).ToString('MM'))-$($day).xlsx"))
{
$cntProc++
Write-Verbose "$((Get-Module psFitb1t).ModuleBase)\FitbitHR_$(([Datetime](Get-Date($QueryMonth))).ToString('yyyy'))-$(([Datetime](Get-Date($QueryMonth))).ToString('MM'))-$($day).xlsx missing!"
Write-Verbose "Running: Get-HRData -QueryDate ""$($([Datetime](Get-Date($QueryMonth))).ToString('yyyy'))-$($([Datetime](Get-Date($QueryMonth))).ToString('MM'))-$($day)"" `n"
Write-Progress -Activity "Retrieving heartrate data for $($([Datetime](Get-Date($QueryMonth))).Year)-$($([Datetime](Get-Date($QueryMonth))).Month)-$($day)" -PercentComplete (($cntProc / $daysToProcess) * 100)
(Write-Status -Message "START - Requesting HR data for $($([Datetime](Get-Date($QueryMonth))).Year)-$($([Datetime](Get-Date($QueryMonth))).Month)-$($day) from Fitbit" -Status "INFO" -Debugging:$psFitb1tDebugging -Logging:$psFitb1tLogging -Logpath $psFitb1tLogPath)
Get-HRData -QueryDate "$($([Datetime](Get-Date($QueryMonth))).Year)-$($([Datetime](Get-Date($QueryMonth))).Month)-$($day)"
}
}
(Write-Status -Message "FINISH - Requesting monthly HR data from Fitbit" -Status "INFO" -Debugging:$psFitb1tDebugging -Logging:$psFitb1tLogging -Logpath $psFitb1tLogPath)
}
catch
{
Throw $("ERROR OCCURRED RETRIEVING MONTHLY HR DATA " + $_.Exception.Message)
}
}
END
{
(Write-Status -Message "FINISH - Get-HRmonth function execution" -Status "INFO" -Debugging:$psFitb1tDebugging -Logging:$psFitb1tLogging -Logpath $psFitb1tLogPath)
}
}
Function Export-FitbitXLS
{
<#
.SYNOPSIS
Saves data to Excel using com object
.DESCRIPTION
The Export-FitbitXLS function allows you to save data to an Excel file
.PARAMETER objInput
Specifies the input object
.PARAMETER outputPath
Specifies the path to the output XLS file
.PARAMETER worksheetName
The name for the worksheet
.PARAMETER sheetIndex
Specify if END
.PARAMETER chartType
Type of chart based on [microsoft.Office.Interop.Excel.XlChartType]
.PARAMETER appendSheet
Append or overwrite
.EXAMPLE
Export-FitbitXLS -objInput $obj "$($Script:psFitb1tInvocationPath)FitbitHR_$($psFitb1tHRQueryDate).xlsx" -appendSheet:$false -worksheetName "$psFitb1tHRQueryDate" -chartType "xlLine"
#>
param (
[parameter(ValueFromPipeline = $true, Position = 1)]
[ValidateNotNullOrEmpty()]
$objInput,
[parameter(Position = 2)]
[ValidateNotNullOrEmpty()]
[string]$outputPath,
[string]$worksheetName = ("Sheet $((Get-Date).Ticks)"),
[switch]$newSheetLast = $true,
[PSObject]$chartType,
[switch]$appendSheet = $true
)
BEGIN
{
#Nested internal helper clipboard function specific to this XLS function
#Adds txt strings to txtbox then to clipboard
function Add-ClipBoardTxt
{
param (
[String]$txtInput
)
process
{
try
{
Add-Type -AssemblyName System.Windows.Forms | Out-Null
$tmpTextbox = New-Object System.Windows.Forms.TextBox
$tmpTextbox.Multiline = $true
$tmpTextbox.Text = $txtInput
$tmpTextbox.SelectAll()
$tmpTextbox.Copy()
}
catch
{
Throw $("ERROR OCCURRED COPYING EXCEL DATA TO CLIPBOARD " + $_.Exception.Message)
}
}
}
#Nested internal helper clipboard function specific to this XLS function
#Builds internal array with header row and sends all to clipboard at once
#To send each of thousands cells one at time to Excel takes far too long this is much faster
function Send-ToClipboard
{
param (
[PSObject[]]$objConvert,
[Switch]$headerRow
)
process
{
try
{
$tmpArray = @()
if ($headerRow)
{
$line = ""
$objConvert | Get-Member -MemberType Property, NoteProperty, CodeProperty | Select -Property Name | %{ $line += ($_.Name.tostring() + "`t") }
$tmpArray += ($line.TrimEnd("`t") + "`r")
}
else
{
foreach ($obj in $objConvert)
{
$line = ""
$obj | Get-Member -MemberType Property, NoteProperty | %{
$Name = $_.Name
if (!$obj.$Name) { $obj.$Name = "" }
$line += ([string]$obj.$Name + "`t")
}
$tmpArray += ($line.TrimEnd("`t") + "`r")
}
}
Add-ClipBoardTxt $tmpArray
}
catch
{
Throw $("ERROR OCCURRED ADDING EXCEL DATA TO CLIPBOARD " + $_.Exception.Message)
}
}
}
try
{
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Office.Interop.Excel") | Out-Null
if ($chartType)
{
[Microsoft.Office.Interop.Excel.XlChartType]$chartType = $chartType
}
$excelObj = New-Object -ComObject "Excel.Application"
$originalAlerts = $excelObj.DisplayAlerts
$excelObj.DisplayAlerts = $false
if (Test-Path -Path $outputPath -PathType "Leaf")
{
$excelWorkbook = $excelObj.Workbooks.Open($outputPath)
}
else
{
$excelWorkbook = $excelObj.Workbooks.Add()
}
$excelSheet = $excelObj.Worksheets.Add($excelWorkbook.Worksheets.Item(1))
if (!$appendSheet)
{
$excelWorkbook.Sheets | where { $_ -ne $excelSheet } | %{ $_.Delete() }
}
$excelSheet.Name = $worksheetName
if ($newSheetLast -eq $true -and $excelWorkbook.Sheets.Count -ge 2)
{
$sheetCount = $excelWorkbook.Sheets.Count
2..($sheetCount) | %{
$excelWorkbook.Sheets.Item($_).Move($excelWorkbook.Sheets.Item($_ - 1))
}
}
$excelSheet.Activate()
$tmpArray = @()
}
catch
{
Throw $("ERROR OCCURRED RELEASING COM OBJECTS " + $_.Exception.Message)
}
}
PROCESS
{
try
{
$tmpArray += $objInput
}
catch
{
Throw $("ERROR OCCURRED CREATING EXCEL ARRAY " + $_.Exception.Message)
}
}
END
{
try
{
Send-ToClipboard $tmpArray -headerRow:$True
$selection = $excelSheet.Range("A1")
$selection.Select() | Out-Null
$excelSheet.Paste()
$excelSheet.UsedRange.HorizontalAlignment = [microsoft.Office.Interop.Excel.XlHAlign]::xlHAlignCenter
Send-ToClipboard $tmpArray
$selection = $excelSheet.Range("A2")
$selection.Select() | Out-Null
$excelSheet.Paste() | Out-Null
$selection = $excelSheet.Range("A1")
$selection.Select() | Out-Null
$excelSheet.UsedRange.EntireColumn.AutoFit() | Out-Null
$excelWorkbook.Sheets.Item(1).Select()
if ($chartType)
{
$chart = $excelSheet.Shapes.AddChart().Chart
$chart.ChartType = $chartType
$chart.ChartTitle.Text = "Fitbit Heartrates for: $($Script:psFitb1tHRQueryDate)"
$excelSheet.Shapes.Item("Chart 1").top = 120
$excelSheet.Shapes.Item("Chart 1").width = 1200
$excelSheet.Shapes.Item("Chart 1").Height = 400
$excelSheet.Shapes.Item("Chart 1").Left = 180
}
$range = $excelSheet.Range("o2", "s3")
$range.Merge() | Out-Null
$range.VerticalAlignment = -4160
$range.Style = 'Title'
$selection = $excelSheet.Range("P5", "R5")
$selection.Select() | Out-Null
$excelSheet.UsedRange.HorizontalAlignment = [microsoft.Office.Interop.Excel.XlHAlign]::xlHAlignCenter
$excelSheet.UsedRange.EntireColumn.AutoFit() | Out-Null
$excelSheet.columns.item('p').NumberFormat = "[Blue]#0"
$excelSheet.columns.item('q').NumberFormat = "[Blue]#0"
$excelSheet.columns.item('r').NumberFormat = "[Blue]#0"
$excelObj.Cells.Item(2, 15).Value() = "Fitbit Heartrates for: $($Script:psFitb1tHRQueryDate)"
$excelObj.Cells.Item(1, 2).Value() = "Time"
$excelObj.Cells.Item(1, 3).Value() = "HeartRate"
$excelObj.Cells.Item(5, 16).Value() = "Minimum"
$excelObj.Cells.Item(5, 17).Value() = "Maximum"
$excelObj.Cells.Item(5, 18).Value() = "Average"
$strFormula1 = "=MIN(C2:C99999)"
$strFormula2 = "=MAX(C2:C99999)"
$strFormula3 = "=AVERAGE(C2:C99999)"
$excelObj.Cells.Item(6, 16).Formula = $strFormula1
$excelObj.Cells.Item(6, 17).Formula = $strFormula2
$excelObj.Cells.Item(6, 18).Formula = $strFormula3
$excelObj.Cells.Item(5, 16).Font.Bold = $True
$excelObj.Cells.Item(5, 17).Font.Bold = $True
$excelObj.Cells.Item(5, 18).Font.Bold = $True
#Auto fit everything so it looks better
$usedRange = $excelSheet.UsedRange
$usedRange.EntireColumn.AutoFit() | Out-Null
$excelWorkbook.Sheets.Item(1).Select()
$excelWorkbook.SaveAs($outputPath)
$excelWorkbook.Saved = $True
$excelWorkbook.Close()
$excelObj.DisplayAlerts = $originalAlerts
$excelObj.Quit()
#Cleanup all this com object crap what a PITA Excel com objects are!!
Release-Ref $chart
Release-Ref $selection
Release-Ref $range
Release-Ref $usedRange
Release-Ref $excelSheet
Release-Ref $excelWorkbook
Release-Ref $excelObj
Remove-Variable chart | Out-Null
Remove-Variable selection | Out-Null