Adding multi-API support

This will allow users to change the API url, added coinchose as an
example as pointed out by @vias79 .

* tools class detects the API type
* getPrice returns the price based on API URL parsed

Fixes #236
This commit is contained in:
Sebastian Grewe 2013-06-23 20:41:43 +02:00
parent 39dc7cdb28
commit 4113e05a10
3 changed files with 63 additions and 14 deletions

View File

@ -26,11 +26,13 @@ require_once('shared.inc.php');
require_once(CLASS_DIR . '/tools.class.php'); require_once(CLASS_DIR . '/tools.class.php');
verbose("Running updates\n"); verbose("Running updates\n");
if ($aData = $tools->getApi($config['price']['url'], $config['price']['target'])) { verbose(" Price API Call ... ");
if (!$setting->setValue('price', $aData['ticker']['last'])) if ($price = $tools->getPrice()) {
verbose("ERR Table update failed"); verbose("found $price as price\n");
if (!$setting->setValue('price', $price))
verbose("unable to update value in settings table\n");
} else { } else {
verbose("ERR Failed download JSON data from " . $config['price']['url'].$config['price']['target'] . "\n"); verbose("failed to fetch API data: " . $tools->getError() . "\n");
} }
?> ?>

View File

@ -9,11 +9,7 @@ if (!defined('SECURITY'))
* Implements some common cron tasks outside * Implements some common cron tasks outside
* the scope of our web application * the scope of our web application
**/ **/
class Tools { class Tools extends Base {
public function __construct($debug) {
$this->debug = $debug;
}
/** /**
* Fetch JSON data from an API * Fetch JSON data from an API
* @param url string API URL * @param url string API URL
@ -21,13 +17,13 @@ class Tools {
* @param auth array Optional authentication data to be sent with * @param auth array Optional authentication data to be sent with
* @return dec array JSON decoded PHP array * @return dec array JSON decoded PHP array
**/ **/
public function getApi($url, $target, $auth=NULL) { private function getApi($url, $target, $auth=NULL) {
static $ch = null; static $ch = null;
static $ch = null; static $ch = null;
if (is_null($ch)) { if (is_null($ch)) {
$ch = curl_init(); $ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; BTCE PHP client; '.php_uname('s').'; PHP/'.phpversion().')'); curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; PHP client; '.php_uname('s').'; PHP/'.phpversion().')');
} }
curl_setopt($ch, CURLOPT_URL, $url . $target); curl_setopt($ch, CURLOPT_URL, $url . $target);
// curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data); // curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
@ -41,6 +37,49 @@ class Tools {
if (!$dec) throw new Exception('Invalid data received, please make sure connection is working and requested API exists'); if (!$dec) throw new Exception('Invalid data received, please make sure connection is working and requested API exists');
return $dec; return $dec;
} }
/**
* Detect the API to properly extract information
* @param url string API URL
* @return data string API type
**/
private function getApiType($url) {
if (preg_match('/coinchoose.com/', $url)) {
return 'coinchose';
} else if (preg_match('/btc-e.com/', $url)) {
return 'btce';
}
$this->setErrorMessage("API URL unknown");
return false;
}
/**
* Extract price information from API data
**/
public function getPrice() {
$aData = $this->getApi($this->config['price']['url'], $this->config['price']['target']);
$strCurrency = $this->config['currency'];
// Check the API type for configured URL
if (!$strApiType = $this->getApiType($this->config['price']['url']))
return false;
// Extract price depending on API type
switch ($strApiType) {
case 'coinchose':
foreach ($aData as $aItem) {
if($strCurrency == $aItem[0])
return $aItem['price'];
}
break;
case 'btce':
return $aData['ticker']['last'];
break;
}
// Catchall, we have no data extractor for this API url
$this->setErrorMessage("Undefined API to getPrice() on URL " . $this->config['price']['url']);
return false;
}
} }
$tools = new Tools($debug); $tools = new Tools();
$tools->setDebug($debug);
$tools->setConfig($config);

View File

@ -1,7 +1,6 @@
<?php <?php
// Make sure we are called from index.php // Make sure we are called from index.php
if (!defined('SECURITY')) if (!defined('SECURITY')) die('Hacking attempt');
die('Hacking attempt');
// What is our overall theme // What is our overall theme
define('THEME', 'mmcFE'); define('THEME', 'mmcFE');
@ -18,6 +17,7 @@ define('PAGES_DIR', INCLUDE_DIR . '/pages');
// Set debugging level for our debug class // Set debugging level for our debug class
define('DEBUG', 0); define('DEBUG', 0);
// SALT used to hash passwords
define('SALT', 'PLEASEMAKEMESOMETHINGRANDOM'); define('SALT', 'PLEASEMAKEMESOMETHINGRANDOM');
$config = array( $config = array(
@ -26,6 +26,14 @@ $config = array(
'target' => '/ltc_usd/ticker', 'target' => '/ltc_usd/ticker',
'currency' => 'USD' // Used in ministats template 'currency' => 'USD' // Used in ministats template
), ),
/**
* Another Example for API
'price' => array(
'url' => 'http://www.coinchoose.com',
'target' => '/api.php',
'currency' => 'BTC'
),
**/
'ap_threshold' => array( 'ap_threshold' => array(
'min' => 1, 'min' => 1,
'max' => 250 'max' => 250