Skip to content

Commit

Permalink
Merge pull request #13 from stadub/Currency-Conv-Release-1.5
Browse files Browse the repository at this point in the history
added requests  caching #11  and save ApiKey prompt #12
  • Loading branch information
stadub committed Sep 9, 2019
2 parents 2a96919 + 372e316 commit e3ff052
Show file tree
Hide file tree
Showing 5 changed files with 134 additions and 51 deletions.
4 changes: 2 additions & 2 deletions Currency-Conv/Currency-Conv.psd1
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
# RootModule = ''

# Version number of this module.
ModuleVersion = '1.0.0'
ModuleVersion = '1.5.0'

# Supported PSEditions
# CompatiblePSEditions = @()
Expand Down Expand Up @@ -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'
Expand Down
5 changes: 3 additions & 2 deletions Currency-Conv/Currency-Conv.psm1
Original file line number Diff line number Diff line change
Expand Up @@ -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
100 changes: 74 additions & 26 deletions Currency-Conv/Functions.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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}"

Expand Down Expand Up @@ -179,8 +200,9 @@ Get-Countries
#>

function Get-Countries {

$result = PerformWebRequest "countries"

$result = PerformCahcedWebRequest "countries" $global:CurrencyConvCountriesCahcheLifetime

return $result.results
}

Expand All @@ -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"}
Expand All @@ -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
}
32 changes: 25 additions & 7 deletions Currency-Conv/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -96,11 +108,18 @@ List supported currencies:
Remove currconv.com api key fromthe system:

```powershell
/> Remove-CurrencyApi-Key
/> Remove-CurrencyApiKey
```

## Changelog

### [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.2](https://github.com/stadub/PowershellScripts/releases/tag/v0.9.0) Spet 1, 2019

* Add functions:
Expand All @@ -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.
Expand Down
44 changes: 30 additions & 14 deletions Currency-Conv/Shared-Functions.ps1
Original file line number Diff line number Diff line change
@@ -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."
Expand All @@ -12,31 +12,31 @@ function CreateFolderIfNotExist {
}


function Test-Empty {
function CurrencyTest-Empty {
param (
[Parameter(Position = 0)]
[string]$string
)
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
)

$profileDir = $ENV:AppData

if( Test-Empty $moduleName ){
if( CurrencyTest-Empty $moduleName ){

if ( $script:MyInvocation.MyCommand.Name.EndsWith('.psm1') ){
$moduleName = $script:MyInvocation.MyCommand.Name
Expand All @@ -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 )) {
Expand All @@ -66,7 +66,7 @@ function Get-ProfileDir {
}


function Combine-Path {
function CurrencyCombine-Path {
param (
[string]$baseDir,
[string]$path
Expand All @@ -76,7 +76,7 @@ function Combine-Path {
[IO.Path]::Combine([string[]]$allArgs)
}

filter Last {
filter CurrencyLast {
BEGIN
{
$current=$null
Expand All @@ -93,7 +93,7 @@ filter Last {



function CheckPsGalleryUpdate {
function CurrencyCheckPsGalleryUpdate {
param (
[string] $moduleName,
[string] $currentVersion
Expand All @@ -119,7 +119,7 @@ function CheckPsGalleryUpdate {
}
}

function Write-Console {
function CurrencyWrite-Console {
param (
[string]$text,
[String[]]$arg=$null
Expand All @@ -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
}

0 comments on commit e3ff052

Please sign in to comment.