From dfda28dadf63759611e284bbc275a12e25f2f2f2 Mon Sep 17 00:00:00 2001
From: Trần Văn Minh <tranvanminh30398@gmail.com>
Date: Fri, 12 Jun 2020 08:50:44 +0700
Subject: [PATCH] gọi ajax

---
 app/Console/Commands/CrawlerNctTrackListenCommand.php  |  4 ++++
 app/Http/Controllers/NctController.php                 | 38 ++++++++++++++++++++++++++++++++++++++
 app/Http/Middleware/VerifyCsrfToken.php                |  2 +-
 app/Repositories/TrackRepository.php                   | 37 ++++++++++++++++++++++++++++---------
 composer.json                                          |  6 ++++++
 packages/yangqi/htmldom/src/Yangqi/Htmldom/Htmldom.php |  2 +-
 resources/views/result.blade.php                       |  1 +
 resources/views/welcome.blade.php                      | 71 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
 routes/web.php                                         |  4 ++++
 9 files changed, 153 insertions(+), 12 deletions(-)
 create mode 100644 app/Http/Controllers/NctController.php
 create mode 100644 resources/views/result.blade.php

diff --git a/app/Console/Commands/CrawlerNctTrackListenCommand.php b/app/Console/Commands/CrawlerNctTrackListenCommand.php
index 0059999..505cf22 100644
--- a/app/Console/Commands/CrawlerNctTrackListenCommand.php
+++ b/app/Console/Commands/CrawlerNctTrackListenCommand.php
@@ -60,6 +60,10 @@ class CrawlerNctTrackListenCommand extends Command
         $data = $this->trackRepository->getNctTrackListen($inserted);
 
         print_r($data);die();
+        // file_get_contents('http://localhost:8000/get-counter');
+        // sendRequest('http://localhost:8000/get-counter', [], 'GET');
+        // cURL('http://localhost:8000/get-counter');
+        // return false;
 
 
     }
diff --git a/app/Http/Controllers/NctController.php b/app/Http/Controllers/NctController.php
new file mode 100644
index 0000000..fb4e828
--- /dev/null
+++ b/app/Http/Controllers/NctController.php
@@ -0,0 +1,38 @@
+<?php
+
+namespace App\Http\Controllers;
+
+use Illuminate\Contracts\View\View;
+use App\Models\Crontjob;
+use GuzzleHttp\Client;
+use Illuminate\Http\Request;
+
+class NctController extends Controller
+{
+    public function getCounter()
+    {
+        // $client = new Client();
+        // $url = 'https://www.nhaccuatui.com/interaction/api/counter?listSongIds=5494094';
+        // $res = $client->get($url,['headers' => [
+        //     'access-control-allow-origin' => '*',
+        // ]ư);
+        
+        // // echo $res->getStatusCode(); // 200
+        // print_r('<pre>' . print_r((string)$res->getBody(), true) . '</pre>');
+        return View('welcome');
+    }
+    public function updateCounter()
+    {
+        // error_log('counter: '.request('counter'));
+        $counter = request('counter');
+        return $counter;
+        // return View("result")->with($counter);
+        // Crontjob::create(['message' => request('counter')]);
+    }
+    
+    public function returnCounter($counter)
+    {
+        return View("result")->with($counter);
+        // return redirect()->action('NctController@getCounter');
+    }
+}
diff --git a/app/Http/Middleware/VerifyCsrfToken.php b/app/Http/Middleware/VerifyCsrfToken.php
index a2c3541..d249f78 100644
--- a/app/Http/Middleware/VerifyCsrfToken.php
+++ b/app/Http/Middleware/VerifyCsrfToken.php
@@ -12,6 +12,6 @@ class VerifyCsrfToken extends BaseVerifier
      * @var array
      */
     protected $except = [
-        //
+        'http://localhost:8000/update-counter'
     ];
 }
diff --git a/app/Repositories/TrackRepository.php b/app/Repositories/TrackRepository.php
index ac9fb85..8d5d410 100644
--- a/app/Repositories/TrackRepository.php
+++ b/app/Repositories/TrackRepository.php
@@ -5,6 +5,7 @@ namespace App\Repositories;
 use App\Helpers\Constants;
 use App\Models\CrawlerListen;
 use App\Models\Track;
+use Goutte\Client;
 use Sunra\PhpSimple\HtmlDomParser;
 use Yangqi\Htmldom\Htmldom;
 
@@ -437,23 +438,41 @@ class TrackRepository extends BaseRepository
 
     public function getNctTrackListen($inserted)
     {
-        return file_get_contents('https://www.nhaccuatui.com/interaction/api/counter?listSongIds=6217224');
+        // return file_get_contents('https://www.nhaccuatui.com/interaction/api/counter?listSongIds=6217224');
 
         $tracks = [];
         //
+        // file_get_contents('http://localhost:8000/get-counter');
+        // return false;
         if (count($inserted) > 0) {
             foreach ($inserted as $key => $track) {
                 $url = $track['link_nct'];
+                // $doc = new DomDocument();
                 //$dom = new Htmldom($url);
-                $dom = file_get_contents($url);
-                //print_r($dom);
-
-                //sleep(5);
+                // $html = new Htmldom($url);
+                // $dom = file_get_contents($url);
+                $dom = file_get_contents('http://localhost:8000/get-counter');
+                $client = new Client();
+                $crawler = $client->request('GET', 'http://localhost:8000/get-counter');
+                // $button = $crawler->selectButton('Nhấn');
+                $crawler =$client->click($crawler->selectLink('more')->link());
+                $html = $client->getResponse()->getContent();
+                $newCrawler = new Crawler($html);
+                $crawler->filter('div')->each(function ($node) {
+                    print $node->text()."\n";
+                });
+                // print_r($crawler);
+                // print_r($track);
+                sleep(5);
                 /* Lấy tên bài hát ------------------------------------------------------------------------------------------ */
-                /*$element_track_title = 'div.show_listen span';
-                foreach ($dom->find($element_track_title) as $data) {
-                    $tracks[$track['id']] = str_replace([], [], $data->innertext);
-                }*/
+                // $element_track_title = 'div.show_listen span';
+                // if (preg_match('/<div id="total">([^<]*)<\/div>/', $dom, $matches) > 0) {
+                //     print_r($matches); //This is text one
+                // }
+                // foreach ($html->find($element_track_title) as $data) {
+                //     $tracks[$track['id']] = str_replace([], [], $data->innertext);
+                //     print_r($data);
+                // }
 
 
 
diff --git a/composer.json b/composer.json
index 4b63bee..29ec6c7 100644
--- a/composer.json
+++ b/composer.json
@@ -6,12 +6,18 @@
     "type": "project",
     "require": {
         "php": ">=5.6.4",
+        "fabpot/goutte": "3.2.3",
+        "guzzlehttp/guzzle": "6.3",
         "ixudra/curl": "^6.19",
         "laravel/framework": "5.4.*",
         "laravel/tinker": "~1.0",
         "maatwebsite/excel": "~2.1.0",
         "phpmailer/phpmailer": "^6.1",
         "sunra/php-simple-html-dom-parser": "^1.5",
+        "symfony/browser-kit": "3.4.3",
+        "symfony/css-selector": "3.4.3",
+        "symfony/dom-crawler": "3.4.40",
+        "symfony/phpunit-bridge": "4",
         "yangqi/htmldom": "@dev"
     },
     "require-dev": {
diff --git a/packages/yangqi/htmldom/src/Yangqi/Htmldom/Htmldom.php b/packages/yangqi/htmldom/src/Yangqi/Htmldom/Htmldom.php
index 4cceb9b..b598662 100644
--- a/packages/yangqi/htmldom/src/Yangqi/Htmldom/Htmldom.php
+++ b/packages/yangqi/htmldom/src/Yangqi/Htmldom/Htmldom.php
@@ -525,7 +525,7 @@ class Htmldom {
 			return true;
 		}
 
-		if (!preg_match("/^[\w-:]+$/", $tag)) {
+		if (!preg_match("/^[\w\-:]+$/", $tag)) {
 			$node->_[YANGQI_HDOM_INFO_TEXT] = '<' . $tag . $this->copy_until('<>');
 			if ($this->char==='<') {
 				$this->link_nodes($node, false);
diff --git a/resources/views/result.blade.php b/resources/views/result.blade.php
new file mode 100644
index 0000000..5bfe12a
--- /dev/null
+++ b/resources/views/result.blade.php
@@ -0,0 +1 @@
+<div>{{$counter}}</div>
\ No newline at end of file
diff --git a/resources/views/welcome.blade.php b/resources/views/welcome.blade.php
index 44b7e72..ae77b33 100644
--- a/resources/views/welcome.blade.php
+++ b/resources/views/welcome.blade.php
@@ -4,7 +4,7 @@
         <meta charset="utf-8">
         <meta http-equiv="X-UA-Compatible" content="IE=edge">
         <meta name="viewport" content="width=device-width, initial-scale=1">
-
+        <meta name="csrf-token" content="{{ csrf_token() }}">
         <title>Laravel</title>
 
         <!-- Fonts -->
@@ -63,8 +63,12 @@
                 margin-bottom: 30px;
             }
         </style>
+        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
     </head>
     <body>
+        <div id="total"></div>
+        <div><h2 id="get">2</h2></div>
+        <!-- <a onclick="Ajax();">more</a> -->
         <div class="flex-center position-ref full-height">
             @if (Route::has('login'))
                 <div class="top-right links">
@@ -93,3 +97,68 @@
         </div>
     </body>
 </html>
+<script>
+$(document).ready(function(){
+    Ajax();
+    setTimeout(function() {
+  location.reload();
+}, 60000);
+});
+
+function Ajax(){
+    var url = 'https://www.nhaccuatui.com/interaction/api/counter?listSongIds=5494094';
+
+    // $.get( url, function( data ) {
+    //     var obj = data.data.songs;
+    //     console.log(obj);
+    //     for (const property in obj) {
+    //         console.log(obj[property]);
+    //         $('#get').html(obj[property]);
+    //         counter = obj[property];
+    //     }
+    // // $( "#get" ).html( data );
+    // // alert( "Load was performed." );
+    // });
+
+
+    $.ajax({
+        type: "GET",
+        url: url,
+        data: {},
+        cache: false,
+        success: function(data) {
+            var obj = data.data.songs;
+            // data_json = JSON.parse(data);
+            var counter = 0;
+            for (const property in obj) {
+                console.log(obj[property]);
+                $('#total').html(obj[property]);
+                counter = obj[property];
+            }
+            $.ajax({
+                headers: {
+                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
+                },
+                type: "POST",
+                url: 'http://localhost:8000/update-counter',
+                data: {
+                    counter: counter
+                },
+                cache: false,
+                success: function(data) {
+                    console.log('Cập nhật thành công: '+data);
+                }
+            })
+            console.log(data.data.songs);
+            var obj = data.data.songs;
+            // data_json = JSON.parse(data);
+            for (const property in obj) {
+                console.log(obj[property]);
+                $('#total').html(obj[property]);
+            }
+            // console.log(data_json);
+            $('#data-loading').hide();
+        }
+    });
+}
+</script>
diff --git a/routes/web.php b/routes/web.php
index 810aa34..b140c1b 100644
--- a/routes/web.php
+++ b/routes/web.php
@@ -14,3 +14,7 @@
 Route::get('/', function () {
     return view('welcome');
 });
+
+Route::get('/get-counter', 'NctController@getCounter');
+Route::post('/update-counter', 'NctController@updateCounter');
+Route::get('/return-counter/{counter}', 'NctController@returnCounter');
--
libgit2 0.27.0