From b61a1545a77c9a3e42e12005cf435933d8033fe5 Mon Sep 17 00:00:00 2001 From: marcdeb1 Date: Tue, 18 Dec 2018 01:20:54 +0100 Subject: [PATCH] Realtime action --- src/Controller/MainController.php | 327 +++++++++++++++--------------- src/Model/Entity/Claim.php | 8 +- src/Model/Entity/Transaction.php | 1 - src/Template/Main/claims.ctp | 123 +++++------ src/Template/Main/index.ctp | 5 +- src/Template/Main/realtime.ctp | 14 +- 6 files changed, 250 insertions(+), 228 deletions(-) diff --git a/src/Controller/MainController.php b/src/Controller/MainController.php index f6fd254..afc1d49 100644 --- a/src/Controller/MainController.php +++ b/src/Controller/MainController.php @@ -106,7 +106,7 @@ class MainController extends AppController { $hashRate = $this->_formatHashRate($this->_gethashrate()); // recent claims - $claims = $this->Claims->find()->select(['transaction_hash_id', 'name', 'vout', 'claim_id', 'claim_type', 'author', 'title', 'description', 'content_type', 'is_nsfw', 'language', 'thumbnail_url', 'created_at'])-> + $claims = $this->Claims->find()->select(['transaction_hash_id', 'name', 'vout', 'claim_id', 'claim_type', 'author', 'title', 'description', 'content_type', 'is_nsfw', 'language', 'thumbnail_url', 'created_at', 'publisher_id'])-> distinct(['Claims.claim_id'])->order(['Claims.created_at' => 'DESC'])->limit(5)->toArray(); foreach($claims as $claim) { @@ -124,7 +124,9 @@ class MainController extends AppController { $this->loadModel('Transactions'); $canConvert = false; - $priceInfo = json_decode($this->redis->get(self::lbcPriceKey)); + if(isset($this->redis)) { + $priceInfo = json_decode($this->redis->get(self::lbcPriceKey)); + } if (isset($priceInfo->price)) { $canConvert = true; } @@ -136,7 +138,7 @@ class MainController extends AppController { $page = intval($this->request->query('page')); $conn = ConnectionManager::get('default'); - $stmt = $conn->execute('SELECT COUNT(Id) AS Total FROM Claims'); + $stmt = $conn->execute('SELECT COUNT(Id) AS Total FROM claim'); $count = $stmt->fetch(\PDO::FETCH_OBJ); $numClaims = $count->Total; @@ -149,12 +151,19 @@ class MainController extends AppController { } $offset = ($page - 1) * $pageLimit; - $claims = $this->Claims->find()->distinct(['Claims.ClaimId'])->contain(['Stream', 'Publisher' => ['fields' => ['Name']]])->order(['Claims.Created' => 'DESC'])->offset($offset)->limit($pageLimit)->toArray(); - for ($i = 0; $i < count($claims); $i++) { - if ($canConvert && $claims[$i]->Fee > 0 && $claims[$i]->FeeCurrency == 'USD') { - $claims[$i]->Price = $claims[$i]->Fee / $priceInfo->price; + $claims = $this->Claims->find()->distinct(['claim_id'])->order(['created_at' => 'DESC'])->offset($offset)->limit($pageLimit)->toArray(); + foreach($claims as $claim) { + if(isset($claim->publisher_id)) { + $publisher = $this->Claims->find()->select(['name'])->where(['claim_id' => $claim->publisher_id])->first(); + $claim->publisher = $publisher; } - + } + + for ($i = 0; $i < count($claims); $i++) { + if ($canConvert && $claims[$i]->Fee > 0 && $claims[$i]->fee_currency == 'USD') { + $claims[$i]->price = $claims[$i]->fee / $priceInfo->price; + } + if (isset($claims[$i]->Stream)) { $json = json_decode($claims[$i]->Stream->Stream); if (isset($json->metadata->license)) { @@ -172,13 +181,16 @@ class MainController extends AppController { $this->set('currentPage', $page); $this->set('claims', $claims); } else { - $claim = $this->Claims->find()->contain(['Stream', 'Publisher' => ['fields' => ['ClaimId', 'Name']]])->where(['Claims.ClaimId' => $id])->order(['Claims.Created' => 'DESC'])->first(); + $claim = $this->Claims->find()->where(['claim_id' => $id])->order(['created_at' => 'DESC'])->first(); + $publisher = $this->Claims->find()->select(['name'])->where(['claim_id' => $claim->publisher_id])->first(); + $claim->publisher = $publisher; + if (!$claim) { return $this->redirect('/'); } - if ($canConvert && $claim->Fee > 0 && $claim->FeeCurrency == 'USD') { - $claim->Price = $claim->Fee / $priceInfo->price; + if ($canConvert && $claim->fee > 0 && $claim->fee_currency == 'USD') { + $claim->price = $claim->fee / $priceInfo->price; } if (isset($claim->Stream)) { @@ -192,14 +204,13 @@ class MainController extends AppController { } $moreClaims = []; - if (isset($claim->Publisher) || $claim->ClaimType == 1) { + if (isset($claim->publisher) || $claim->claim_type == 1) { // find more claims for the publisher - $moreClaims = $this->Claims->find()->contain(['Stream', 'Publisher' => ['fields' => ['Name']]])-> - where(['Claims.ClaimType' => 2, 'Claims.Id <>' => $claim->Id, 'Claims.PublisherId' => isset($claim->Publisher) ? $claim->Publisher->ClaimId : $claim->ClaimId])-> - limit(9)->order(['Claims.Fee' => 'DESC', 'RAND()' => 'DESC'])->toArray(); + $moreClaims = $this->Claims->find()->where(['claim_type' => 2, 'id <>' => $claim->id, 'publisher_id' => isset($claim->publisher) ? $claim->publisher_id : $claim->claim_id])-> + limit(9)->order(['fee' => 'DESC', 'RAND()' => 'DESC'])->toArray(); for ($i = 0; $i < count($moreClaims); $i++) { - if ($canConvert && $moreClaims[$i]->Fee > 0 && $moreClaims[$i]->FeeCurrency == 'USD') { - $moreClaims[$i]->Price = $moreClaims[$i]->Fee / $priceInfo->price; + if ($canConvert && $moreClaims[$i]->fee > 0 && $moreClaims[$i]->fee_currency == 'USD') { + $moreClaims[$i]->price = $moreClaims[$i]->fee / $priceInfo->price; } if (isset($moreClaims[$i]->Stream)) { @@ -225,114 +236,20 @@ class MainController extends AppController { // load 10 blocks and transactions $conn = ConnectionManager::get('default'); - $blocks = $this->Blocks->find()->select(['Height', 'BlockTime', 'TransactionHashes'])->order(['Height' => 'desc'])->limit(10)->toArray(); + $blocks = $this->Blocks->find()->select(['height', 'block_time', 'transaction_hashes'])->order(['height' => 'desc'])->limit(10)->toArray(); for ($i = 0; $i < count($blocks); $i++) { - $tx_hashes = json_decode($blocks[$i]->TransactionHashes); - $blocks[$i]->TransactionCount = count($tx_hashes); + $tx_hashes = json_decode($blocks[$i]->transaction_hashes); + $blocks[$i]->transaction_count = count($tx_hashes); } - $stmt = $conn->execute('SELECT T.Hash, T.InputCount, T.OutputCount, T.Value, IFNULL(T.TransactionTime, T.CreatedTime) AS TxTime ' . - 'FROM Transactions T ORDER BY CreatedTime DESC LIMIT 10'); + $stmt = $conn->execute('SELECT T.id, T.hash, T.input_count, T.output_count, IFNULL(T.transaction_time, T.created_at) AS TxTime ' . + 'FROM transaction T ORDER BY created_at DESC LIMIT 10'); $txs = $stmt->fetchAll(\PDO::FETCH_OBJ); $this->set('blocks', $blocks); $this->set('txs', $txs); } - public function apiblocksize($timePeriod = '24h') { - $this->autoRender = false; - - if (!$this->request->is('get')) { - return $this->_jsonError('Invalid HTTP request method.', 400); - } - - $validPeriods = ['24h', '72h', '168h', '30d', '90d', '1y']; - if (!in_array($timePeriod, $validPeriods)) { - return $this->_jsonError('Invalid time period specified.', 400); - } - - $isHourly = (strpos($timePeriod, 'h') !== false); - $now = new \DateTime('now', new \DateTimeZone('UTC')); - $dateFormat = $isHourly ? 'Y-m-d H:00:00' : 'Y-m-d'; - $sqlDateFormat = $isHourly ? '%Y-%m-%d %H:00:00' : '%Y-%m-%d'; - $intervalPrefix = $isHourly ? 'PT' : 'P'; - $start = $now->sub(new \DateInterval($intervalPrefix . strtoupper($timePeriod))); - - $resultSet = []; - - $conn = ConnectionManager::get('default'); - - // get avg block sizes for the time period - $stmt = $conn->execute("SELECT AVG(BlockSize) AS AvgBlockSize, DATE_FORMAT(FROM_UNIXTIME(BlockTime), '$sqlDateFormat') AS TimePeriod " . - "FROM Blocks WHERE DATE_FORMAT(FROM_UNIXTIME(BlockTime), '$sqlDateFormat') >= ? GROUP BY TimePeriod ORDER BY TimePeriod ASC", [$start->format($dateFormat)]); - $avgBlockSizes = $stmt->fetchAll(\PDO::FETCH_OBJ); - foreach ($avgBlockSizes as $size) { - if (!isset($resultSet[$size->TimePeriod])) { - $resultSet[$size->TimePeriod] = []; - } - $resultSet[$size->TimePeriod]['AvgBlockSize'] = (float) $size->AvgBlockSize; - } - - // get avg prices - $stmt = $conn->execute("SELECT AVG(USD) AS AvgUSD, DATE_FORMAT(Created, '$sqlDateFormat') AS TimePeriod " . - "FROM PriceHistory WHERE DATE_FORMAT(Created, '$sqlDateFormat') >= ? GROUP BY TimePeriod ORDER BY TimePeriod ASC", [$start->format($dateFormat)]); - $avgPrices = $stmt->fetchAll(\PDO::FETCH_OBJ); - foreach ($avgPrices as $price) { - if (!isset($resultSet[$price->TimePeriod])) { - $resultSet[$price->TimePeriod] = []; - } - $resultSet[$price->TimePeriod]['AvgUSD'] = (float) $price->AvgUSD; - } - - return $this->_jsonResponse(['success' => true, 'data' => $resultSet]); - } - - public function apirealtimeblocks() { - // load 10 blocks - $this->autoRender = false; - $this->loadModel('Blocks'); - $blocks = $this->Blocks->find()->select(['Height', 'BlockTime', 'TransactionHashes'])->order(['Height' => 'desc'])->limit(10)->toArray(); - for ($i = 0; $i < count($blocks); $i++) { - $tx_hashes = json_decode($blocks[$i]->TransactionHashes); - $blocks[$i]->TransactionCount = count($tx_hashes); - unset($blocks[$i]->TransactionHashes); - } - - $this->_jsonResponse(['success' => true, 'blocks' => $blocks]); - } - - public function apirealtimetx() { - // load 10 transactions - $this->autoRender = false; - $conn = ConnectionManager::get('default'); - $stmt = $conn->execute('SELECT T.Hash, T.InputCount, T.OutputCount, T.Value, IFNULL(T.TransactionTime, T.CreatedTime) AS TxTime ' . - 'FROM Transactions T ORDER BY CreatedTime DESC LIMIT 10'); - $txs = $stmt->fetchAll(\PDO::FETCH_OBJ); - - $this->_jsonResponse(['success' => true, 'txs' => $txs]); - } - - protected function _formatHashRate($value) { - if ($value === 'N/A') { - return $value; - } - - /*if ($value > 1000000000000) { - return number_format( $value / 1000000000000, 2, '.', '' ) . ' TH'; - }*/ - if ($value > 1000000000) { - return number_format( $value / 1000000000, 2, '.', '' ) . ' GH/s'; - } - if ($value > 1000000) { - return number_format( $value / 1000000, 2, '.', '' ) . ' MH/s'; - } - if ($value > 1000) { - return number_format( $value / 1000, 2, '.', '' ) . ' KH/s'; - } - - return number_format($value) . ' H/s'; - } - public function find() { $criteria = $this->request->query('q'); @@ -650,53 +567,78 @@ class MainController extends AppController { echo $qrCode->writeString(); exit(0); } + + public function apiblocksize($timePeriod = '24h') { + $this->autoRender = false; - public static function curl_get($url) { - $ch = curl_init(); - curl_setopt($ch, CURLOPT_URL, $url); - curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); - - $response = curl_exec($ch); - Log::debug('Request execution completed.'); - - if ($response === false) { - $error = curl_error($ch); - $errno = curl_errno($ch); - curl_close($ch); - - throw new \Exception(sprintf('The request failed: %s', $error), $errno); - } else { - curl_close($ch); + if (!$this->request->is('get')) { + return $this->_jsonError('Invalid HTTP request method.', 400); } - return $response; + $validPeriods = ['24h', '72h', '168h', '30d', '90d', '1y']; + if (!in_array($timePeriod, $validPeriods)) { + return $this->_jsonError('Invalid time period specified.', 400); + } + + $isHourly = (strpos($timePeriod, 'h') !== false); + $now = new \DateTime('now', new \DateTimeZone('UTC')); + $dateFormat = $isHourly ? 'Y-m-d H:00:00' : 'Y-m-d'; + $sqlDateFormat = $isHourly ? '%Y-%m-%d %H:00:00' : '%Y-%m-%d'; + $intervalPrefix = $isHourly ? 'PT' : 'P'; + $start = $now->sub(new \DateInterval($intervalPrefix . strtoupper($timePeriod))); + + $resultSet = []; + + $conn = ConnectionManager::get('default'); + + // get avg block sizes for the time period + $stmt = $conn->execute("SELECT AVG(BlockSize) AS AvgBlockSize, DATE_FORMAT(FROM_UNIXTIME(BlockTime), '$sqlDateFormat') AS TimePeriod " . + "FROM Blocks WHERE DATE_FORMAT(FROM_UNIXTIME(BlockTime), '$sqlDateFormat') >= ? GROUP BY TimePeriod ORDER BY TimePeriod ASC", [$start->format($dateFormat)]); + $avgBlockSizes = $stmt->fetchAll(\PDO::FETCH_OBJ); + foreach ($avgBlockSizes as $size) { + if (!isset($resultSet[$size->TimePeriod])) { + $resultSet[$size->TimePeriod] = []; + } + $resultSet[$size->TimePeriod]['AvgBlockSize'] = (float) $size->AvgBlockSize; + } + + // get avg prices + $stmt = $conn->execute("SELECT AVG(USD) AS AvgUSD, DATE_FORMAT(Created, '$sqlDateFormat') AS TimePeriod " . + "FROM PriceHistory WHERE DATE_FORMAT(Created, '$sqlDateFormat') >= ? GROUP BY TimePeriod ORDER BY TimePeriod ASC", [$start->format($dateFormat)]); + $avgPrices = $stmt->fetchAll(\PDO::FETCH_OBJ); + foreach ($avgPrices as $price) { + if (!isset($resultSet[$price->TimePeriod])) { + $resultSet[$price->TimePeriod] = []; + } + $resultSet[$price->TimePeriod]['AvgUSD'] = (float) $price->AvgUSD; + } + + return $this->_jsonResponse(['success' => true, 'data' => $resultSet]); + } + + public function apirealtimeblocks() { + // load 10 blocks + $this->autoRender = false; + $this->loadModel('Blocks'); + $blocks = $this->Blocks->find()->select(['Height', 'BlockTime', 'TransactionHashes'])->order(['Height' => 'desc'])->limit(10)->toArray(); + for ($i = 0; $i < count($blocks); $i++) { + $tx_hashes = json_decode($blocks[$i]->TransactionHashes); + $blocks[$i]->TransactionCount = count($tx_hashes); + unset($blocks[$i]->TransactionHashes); + } + + $this->_jsonResponse(['success' => true, 'blocks' => $blocks]); } - private function _gethashrate() { - $req = ['method' => 'getnetworkhashps', 'params' => []]; - try { - $res = json_decode(self::curl_json_post(self::$rpcurl, json_encode($req))); - if (!isset($res->result)) { - return 0; - } - return $res->result; - } catch (\Exception $e) { - return 'N/A'; - } - } + public function apirealtimetx() { + // load 10 transactions + $this->autoRender = false; + $conn = ConnectionManager::get('default'); + $stmt = $conn->execute('SELECT T.Hash, T.InputCount, T.OutputCount, T.Value, IFNULL(T.TransactionTime, T.CreatedTime) AS TxTime ' . + 'FROM Transactions T ORDER BY CreatedTime DESC LIMIT 10'); + $txs = $stmt->fetchAll(\PDO::FETCH_OBJ); - private function _gettxoutsetinfo() { - $req = ['method' => 'gettxoutsetinfo', 'params' => []]; - try { - $res = json_decode(self::curl_json_post(self::$rpcurl, json_encode($req))); - if (!isset($res->result)) { - return 0; - } - return $res->result; - } catch (\Exception $e) { - return 'N/A'; - } + $this->_jsonResponse(['success' => true, 'txs' => $txs]); } public function apistatus() { @@ -868,7 +810,7 @@ class MainController extends AppController { return $this->_jsonResponse(['success' => true, 'utxo' => $utxo]); } - public function apiutxosupply() { + public function apiutxosupply() { $this->autoRender = false; $this->loadModel('Addresses'); @@ -902,6 +844,75 @@ class MainController extends AppController { return $this->_jsonResponse(['success' => true, 'utxosupply' => ['total' => $txoutsetinfo->total_amount, 'circulating' => $circulating]]); } + + protected function _formatHashRate($value) { + if ($value === 'N/A') { + return $value; + } + + /*if ($value > 1000000000000) { + return number_format( $value / 1000000000000, 2, '.', '' ) . ' TH'; + }*/ + if ($value > 1000000000) { + return number_format( $value / 1000000000, 2, '.', '' ) . ' GH/s'; + } + if ($value > 1000000) { + return number_format( $value / 1000000, 2, '.', '' ) . ' MH/s'; + } + if ($value > 1000) { + return number_format( $value / 1000, 2, '.', '' ) . ' KH/s'; + } + + return number_format($value) . ' H/s'; + } + + public static function curl_get($url) { + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, $url); + curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + + $response = curl_exec($ch); + Log::debug('Request execution completed.'); + + if ($response === false) { + $error = curl_error($ch); + $errno = curl_errno($ch); + curl_close($ch); + + throw new \Exception(sprintf('The request failed: %s', $error), $errno); + } else { + curl_close($ch); + } + + return $response; + } + + private function _gethashrate() { + $req = ['method' => 'getnetworkhashps', 'params' => []]; + try { + $res = json_decode(self::curl_json_post(self::$rpcurl, json_encode($req))); + if (!isset($res->result)) { + return 0; + } + return $res->result; + } catch (\Exception $e) { + return 'N/A'; + } + } + + private function _gettxoutsetinfo() { + $req = ['method' => 'gettxoutsetinfo', 'params' => []]; + try { + $res = json_decode(self::curl_json_post(self::$rpcurl, json_encode($req))); + if (!isset($res->result)) { + return 0; + } + return $res->result; + } catch (\Exception $e) { + return 'N/A'; + } + } private static function curl_json_post($url, $data, $headers = []) { $ch = curl_init(); diff --git a/src/Model/Entity/Claim.php b/src/Model/Entity/Claim.php index d12c480..eab2204 100644 --- a/src/Model/Entity/Claim.php +++ b/src/Model/Entity/Claim.php @@ -3,12 +3,16 @@ namespace App\Model\Entity; use Cake\ORM\Entity; +use Cake\ORM\TableRegistry; class Claim extends Entity { function getLbryLink() { $link = $this->name; - if (isset($this->Publisher->Name)) { - $link = $this->Publisher->Name . '/' . $link; + $ClaimModel = TableRegistry::get('Claims'); + $publisher = $ClaimModel->find()->select(['name'])->where(['claim_id' => $this->publisher_id])->first(); + + if (isset($publisher->name)) { + $link = $publisher->name . '/' . $link; } $link = 'lbry://' . $link; return $link; diff --git a/src/Model/Entity/Transaction.php b/src/Model/Entity/Transaction.php index b491ed7..aa0ed81 100644 --- a/src/Model/Entity/Transaction.php +++ b/src/Model/Entity/Transaction.php @@ -5,7 +5,6 @@ namespace App\Model\Entity; use Cake\ORM\Entity; use Cake\ORM\TableRegistry; - class Transaction extends Entity { public function value() { $OutputModel = TableRegistry::get('Outputs'); diff --git a/src/Template/Main/claims.ctp b/src/Template/Main/claims.ctp index 0d4bfad..963205f 100644 --- a/src/Template/Main/claims.ctp +++ b/src/Template/Main/claims.ctp @@ -41,13 +41,13 @@ $a = ['purple', 'orange', 'blue', 'teal', 'green', 'yellow']; $autoThumbText = $claim->getAutoThumbText(); $cost = 'Free'; -if (isset($claim->Price) && $claim->Price > 0) { - $cost = $this->Amount->formatCurrency($claim->Price) . ' LBC'; -} else if (isset($claim->Fee) && strtolower($claim->FeeCurrency) === 'lbc') { - $cost = $this->Amount->formatCurrency($claim->Fee) . ' LBC'; +if (isset($claim->price) && $claim->price > 0) { + $cost = $this->Amount->formatCurrency($claim->price) . ' LBC'; +} else if (isset($claim->fee) && strtolower($claim->fee_currency) === 'lbc') { + $cost = $this->Amount->formatCurrency($claim->fee) . ' LBC'; } -$desc = $claim->Description; +$desc = $claim->description; if (strlen(trim($desc)) == 0) { $desc = 'No description available.'; } else { @@ -57,29 +57,29 @@ if (strlen(trim($desc)) == 0) { ?> -assign('title', 'Claim • ' . $claim->Name) ?> +assign('title', 'Claim • ' . $claim->name) ?>
-

LBRY ClaimsName ?>

-

ClaimId ?>

+

LBRY Claimsname ?>

+

claim_id ?>

- IsNSFW && strlen(trim($claim->ThumbnailUrl)) > 0): ?> - + is_nsfw && strlen(trim($claim->thumbnail_url)) > 0): ?> +
- ClaimType == 2): ?> + claim_type == 2): ?>
Published By
- Publisher)): ?> - Publisher->Name ?> + publisher)): ?> + publisher->name ?> Anonymous @@ -87,17 +87,17 @@ if (strlen(trim($desc)) == 0) {
Created On
-
TransactionTime > 0 ? $claim->TransactionTime : $claim->Created->format('U'))->format('j M Y H:i:s') ?> UTC
+
transaction_time > 0 ? $claim->transaction_time : $claim->created_at->format('U'))->format('j M Y H:i:s') ?> UTC
Transaction ID
- + - ClaimType == 2): ?> + claim_type == 2): ?>
Cost
Safe for Work
-
IsNSFW ? 'No' : 'Yes' ?>
+
is_nsfw ? 'No' : 'Yes' ?>
@@ -105,11 +105,11 @@ if (strlen(trim($desc)) == 0) {