From e81d9b7ad77b179b58c5e605ef477c64460954a3 Mon Sep 17 00:00:00 2001 From: Dmitry Stadub Date: Mon, 9 Sep 2019 09:55:18 +0300 Subject: [PATCH] Added cacheing #11 Added save-prompt #12 --- Currency-Conv/Currency-Conv.psd1 | 4 +- Currency-Conv/Currency-Conv.psm1 | 5 +- Currency-Conv/Functions.ps1 | 100 +++++++++++++++++++++-------- Currency-Conv/README.md | 34 +++++++--- Currency-Conv/Shared-Functions.ps1 | 44 +++++++++---- 5 files changed, 135 insertions(+), 52 deletions(-) diff --git a/Currency-Conv/Currency-Conv.psd1 b/Currency-Conv/Currency-Conv.psd1 index 0dd3902..80861d2 100644 --- a/Currency-Conv/Currency-Conv.psd1 +++ b/Currency-Conv/Currency-Conv.psd1 @@ -12,7 +12,7 @@ # RootModule = '' # Version number of this module. -ModuleVersion = '1.0.0' +ModuleVersion = '1.5.0' # Supported PSEditions # CompatiblePSEditions = @() @@ -98,7 +98,7 @@ PrivateData = @{ PSData = @{ # Tags applied to this module. These help with module discovery in online galleries. - Tags = @('currency','currency convereter','exchange','currency-exchange', 'currencyconverterapi', 'convereter', 'exchang rates' ) + Tags = @('currency','currency-convereter','exchange','currency-exchange', 'currencyconverterapi', 'convereter', 'exchange-rates' ) # A URL to the license for this module. LicenseUri = 'http://opensource.org/licenses/MIT' diff --git a/Currency-Conv/Currency-Conv.psm1 b/Currency-Conv/Currency-Conv.psm1 index f625764..504c87b 100644 --- a/Currency-Conv/Currency-Conv.psm1 +++ b/Currency-Conv/Currency-Conv.psm1 @@ -2,11 +2,12 @@ . $PSScriptRoot\Functions.ps1 -CheckPsGalleryUpdate "Currency-Conv" "1.0.0" +CurrencyCheckPsGalleryUpdate "Currency-Conv" "1.5.0" _Initalize Export-ModuleMember -Function Get-Currencies -Export-ModuleMember -Function GetImpo-ExchangeRate +Export-ModuleMember -Function Get-ExchangeRate Export-ModuleMember -Function Get-Countries +Export-ModuleMember -Function Remove-CurrencyApiKey . $PSScriptRoot\Aliases.ps1 \ No newline at end of file diff --git a/Currency-Conv/Functions.ps1 b/Currency-Conv/Functions.ps1 index cdfdca9..b8b17df 100644 --- a/Currency-Conv/Functions.ps1 +++ b/Currency-Conv/Functions.ps1 @@ -4,38 +4,59 @@ function _Initalize() { + $script:currenciesCache = [System.Runtime.Caching.MemoryCache]::Default + $script:license=$null $script:apiKey = $null $script:baseUrl = $null - $script:apiKeyFile = Get-ProfileDataFile currency-conv ".cur_api_key" - - $script:baseUrlFile = Get-ProfileDataFile currency-conv ".path" + $script:apiKeyFile = CurrencyGet-ProfileDataFile currency-conv ".cur_api_key" + $script:baseUrlFile = CurrencyGet-ProfileDataFile currency-conv ".path" + $store = $false if( !(Test-Path $script:apiKeyFile)){ - Write-Console "Api key didn't found on the computer. " - Write-Console "To use the CurrencyConverter api you need to enter your apiKey or receive free api key." + CurrencyWrite-Console "Api key didn't found on the computer. " + CurrencyWrite-Console "To use the CurrencyConverter api you need to enter your apiKey or receive free api key." - while ( Test-Empty $script:baseUrl ){ + while ( CurrencyTest-Empty $script:baseUrl ){ LicenseTypePrompt } - $script:baseUrl | Out-File -FilePath $baseUrlFile + if( $script:license -ne 'fr' ){ - Read-Host -Prompt "Enter the received api key here: " | Out-File -FilePath $apiKeyFile + $script:apiKey = Read-Host -Prompt "Enter the received api key here: " }else{ - Read-Host -Prompt "Please open in the browser link 'https://free.currencyconverterapi.com/free-api-key' and follow the site instructions.` - Afterwards enter the received api key here: " | Out-File -FilePath $apiKeyFile - Write-Console "Important: Do not forget to verify your email address." + $script:apiKey = Read-Host -Prompt "Please open in the browser link 'https://free.currencyconverterapi.com/free-api-key' and follow the site instructions.` + Afterwards enter the received api key here: " + CurrencyWrite-Console "Important: Do not forget to verify your email address." } + + $store = currencyShow-ConfirmPrompt -Question "Do you want to store the ApiKey on disk for the future usage?" + + } + else{ + Get-Content -Path $apiKeyFile | ForEach-Object{ $script:apiKey= $_} + Get-Content -Path $baseUrlFile | ForEach-Object{ $script:baseUrl= $_} + } + + + if ($store) { + + $script:apiKey | Out-File -FilePath $apiKeyFile + $script:baseUrl | Out-File -FilePath $baseUrlFile + + #to doublecheck stored data + Get-Content -Path $apiKeyFile | ForEach-Object{ $script:apiKey= $_} + Get-Content -Path $baseUrlFile | ForEach-Object{ $script:baseUrl= $_} } - Get-Content -Path $apiKeyFile | ForEach-Object{ $script:apiKey= $_} - Get-Content -Path $baseUrlFile | ForEach-Object{ $script:baseUrl= $_} + $global:CurrencyConvExchangeRateCahcheLifetime = $([System.DateTimeOffset]::Now.AddSeconds(60.0)) + $global:CurrencyConvCountriesCahcheLifetime = $([System.DateTimeOffset]::Now.AddHours(15.0)) + $global:CurrencyConvCurrenciesCahcheLifetime = $([System.DateTimeOffset]::Now.AddHours(15.0)) } function LicenseTypePrompt { @@ -136,11 +157,11 @@ function Get-ExchangeRate { #"${from}_${to}%2C${to}_${from}" - $result = PerformWebRequest "convert" "${From}_${To}" + $result = PerformCahcedWebRequest "convert"-cacheExpirity $global:CurrencyConvExchangeRateCahcheLifetime -arg "${From}_${To}" - $from = $result.results | Select-Object -ExpandProperty "${from}_${to}" | ForEach-Object{$_.fr} - $to = $result.results | Select-Object -ExpandProperty "${from}_${to}" | ForEach-Object{$_.to} - $val = $result.results | Select-Object -ExpandProperty "${from}_${to}" | ForEach-Object{$_.val} + $from = $result.results | Select-Object -ExpandProperty "${from}_${to}" | CurrencyLast | ForEach-Object{$_.fr} + $to = $result.results | Select-Object -ExpandProperty "${from}_${to}" | CurrencyLast | ForEach-Object{$_.to} + $val = $result.results | Select-Object -ExpandProperty "${from}_${to}" | CurrencyLast | ForEach-Object{$_.val} #$from= $result.results."${from}_${to}" #$to= $result.results."${to}_${from}" @@ -179,8 +200,9 @@ Get-Countries #> function Get-Countries { - - $result = PerformWebRequest "countries" + + $result = PerformCahcedWebRequest "countries" $global:CurrencyConvCountriesCahcheLifetime + return $result.results } @@ -197,12 +219,32 @@ Supported currencies list #> function Get-Currencies { - - $result = PerformWebRequest "currencies" + + $result = PerformCahcedWebRequest "currencies" $global:CurrencyConvCurrenciesCahcheLifetime + $result.results.PSObject.Properties | ForEach-Object { $_.Value } - #return $result.results +} + + +function PerformCahcedWebRequest { + param ( + [string]$func, + [System.DateTimeOffset] $cacheExpirity, + [string]$arg='a' + ) + + if( -not $script:currenciesCache.Contains($func+$arg)){ + + $result = PerformWebRequest $func $arg + + $script:currenciesCache.Add($func+$arg, $result, $cacheExpirity) + } + + + return $script:currenciesCache.Get( $func+$arg) + } #Get-Currencies | Where-Object {$_.id -eq "BYN"} @@ -224,9 +266,15 @@ Remove currconv.com api key fromthe system Remove currconv.com api key fromthe system: #> -function Remove-CurrencyApi-Key { +function Remove-CurrencyApiKey { + + Remove-Item $script:apiKeyFile + + Remove-Item $script:baseUrlFile + + $script:apiKey = $null + $script:baseUrl = $null + $script:license=$null +} - rm $script:apiKeyFile - rm $script:baseUrlFile -} \ No newline at end of file diff --git a/Currency-Conv/README.md b/Currency-Conv/README.md index 19fbf9b..c8cdbf3 100644 --- a/Currency-Conv/README.md +++ b/Currency-Conv/README.md @@ -47,15 +47,27 @@ Get-Countries -Countries list with currencies Get-Currencies - Supported currencies list -Remove-CurrencyApi-Key- Clean key +Remove-CurrencyApiKey- Clean key ``` ## Aliases -| Cmdlet | Alias | -| -----------------|:--------:| -| Get-Currencies | gxc | -| Get-ExchangeRate | xe | +| Cmdlet | Alias | +| -----------------|:-----:| +| Get-Currencies | gxc | +| Get-ExchangeRate | xe | + +## Cache Timeouts + +Default cache timeouts are stored in global variables so it can be changed to meet your needs. + +Default values: + +```powershell + $global:CurrencyConvExchangeRateCahcheLifetime = $([System.DateTimeOffset]::Now.AddSeconds(60.0)) + $global:CurrencyConvCountriesCahcheLifetime = $([System.DateTimeOffset]::Now.AddHours(15.0)) + $global:CurrencyConvCurrenciesCahcheLifetime = $([System.DateTimeOffset]::Now.AddHours(15.0)) +``` ## Usage @@ -96,12 +108,19 @@ List supported currencies: Remove currconv.com api key fromthe system: ```powershell -/> Remove-CurrencyApi-Key +/> Remove-CurrencyApiKey ``` ## Changelog -### [v1.9.0](https://github.com/stadub/PowershellScripts/releases/tag/v0.9.0) Spet 1, 2019 +### [v1.5.0](https://github.com/stadub/PowershellScripts/releases/tag/v0.9.5) Spet 9, 2019 + +* Add Request cache +* Add ability to change cache timeount + +* Rename `Remove-CurrencyApi-Key` to `Remove-CurrencyApiKey` to be ps1 cmdlet name restrictions compliant + +### [v1.0.0](https://github.com/stadub/PowershellScripts/releases/tag/v0.9.0) Spet 1, 2019 * Add functions: @@ -120,7 +139,6 @@ Remove-CurrencyApi-Key- Clean key * Create tests - ## Motivation The modules are created and actively maintained during evenings and weekends for my own needs. diff --git a/Currency-Conv/Shared-Functions.ps1 b/Currency-Conv/Shared-Functions.ps1 index baa4071..9c38cce 100644 --- a/Currency-Conv/Shared-Functions.ps1 +++ b/Currency-Conv/Shared-Functions.ps1 @@ -1,6 +1,6 @@ -function CreateFolderIfNotExist { +function CurrencyCreateFolderIfNotExist { param ([string]$Folder) if( Test-Path $Folder -PathType Leaf){ Write-Error "The destanation path ${Folder} is file." @@ -12,7 +12,7 @@ function CreateFolderIfNotExist { } -function Test-Empty { +function CurrencyTest-Empty { param ( [Parameter(Position = 0)] [string]$string @@ -20,15 +20,15 @@ function Test-Empty { return [string]::IsNullOrWhitespace($string) } -function Get-ProfileDataFile { +function CurrencyGet-ProfileDataFile { param ( [string]$file, [string]$moduleName = $null ) - return Join-Path (Get-ProfileDir $moduleName) $file + return Join-Path (CurrencyGet-ProfileDir $moduleName) $file } -function Get-ProfileDir { +function CurrencyGet-ProfileDir { param ( [string]$moduleName = $null, [string]$profileFolder = $null @@ -36,7 +36,7 @@ function Get-ProfileDir { $profileDir = $ENV:AppData - if( Test-Empty $moduleName ){ + if( CurrencyTest-Empty $moduleName ){ if ( $script:MyInvocation.MyCommand.Name.EndsWith('.psm1') ){ $moduleName = $script:MyInvocation.MyCommand.Name @@ -48,14 +48,14 @@ function Get-ProfileDir { } } - if( Test-Empty $moduleName ){ + if( CurrencyTest-Empty $moduleName ){ throw "Unable to read module name." } - $scriptProfile = Combine-Path $profileDir '.ps1' 'ScriptData' $moduleName + $scriptProfile = CurrencyCombine-Path $profileDir '.ps1' 'ScriptData' $moduleName - if( Test-Empty $profileFolder){ - $scriptProfile = Combine-Path $profileDir '.ps1' 'ScriptData' $moduleName $profileFolder + if( CurrencyTest-Empty $profileFolder){ + $scriptProfile = CurrencyCombine-Path $profileDir '.ps1' 'ScriptData' $moduleName $profileFolder } if ( ! (Test-Path $scriptProfile -PathType Container )) { @@ -66,7 +66,7 @@ function Get-ProfileDir { } -function Combine-Path { +function CurrencyCombine-Path { param ( [string]$baseDir, [string]$path @@ -76,7 +76,7 @@ function Combine-Path { [IO.Path]::Combine([string[]]$allArgs) } -filter Last { +filter CurrencyLast { BEGIN { $current=$null @@ -93,7 +93,7 @@ filter Last { -function CheckPsGalleryUpdate { +function CurrencyCheckPsGalleryUpdate { param ( [string] $moduleName, [string] $currentVersion @@ -119,7 +119,7 @@ function CheckPsGalleryUpdate { } } -function Write-Console { +function CurrencyWrite-Console { param ( [string]$text, [String[]]$arg=$null @@ -131,4 +131,20 @@ function Write-Console { [Console]::WriteLine($text, $arg) } +} + +function currencyShow-ConfirmPrompt { + param ( + [Parameter(Position = 0, ParameterSetName = 'Positional', ValueFromPipeline = $True)] + [Alias("Question", "Description")] + $text ="Would you like to continue?" + ) + $reply = Read-Host -Prompt "$text` + [Y] Yes [N] No [S] Suspend(default is ""Yes""):" + + if ( $reply -match "[yY]" -and $null -ne $reply ) { + return $true + } + if ( $reply -match "[Ss]" ) { throw "Execution aborted" } + return $false } \ No newline at end of file