jeudi 27 février 2020

Websockets in codeigniter?

Okay,so long story short, I have a super long process running on my codeigniter app, and I want to update the user on the progress WHILE it is running. I tried polling (writing the messages to a txt file and letting the webpage query for it every second or so), which works, but isn't a smart idea for a production server. I tried Eventsource, which only works after the process is finished because of the nature of http requests.

Now I'm looking into websockets. I know you need Ratchet for codeigniter, but how do I implement this in my code below? I need the messages to be sent from the model.

Also, if anybody has any ideas on alternatives, please let me know! I've included my code with my eventsource implementation, which I can easily remove.

My index.php

<form id="form1">
  <div class="form-group">
    <label>Date From -></label>
    <input type="text" class="form-control" name="date" id="magento-date" placeholder="2019-10-15 06:46:30">
  </div>
  <div class="form-group">
    <label>Date To <-</label>
    <input type="text" class="form-control" name="dateTo" id="magento-date-to" placeholder="2019-10-16 06:46:30">
  </div>

  <button id="submit" type="submit" class="btn btn-default">Submit</button> 
</form>
<div class="progress progress-striped active">
  <div class="progress-bar" id="progress" style="width:0%"></div>
</div>
<div id="message"></div>

<script>

document.querySelector("#submit").addEventListener("click", function(event) {
  event.preventDefault();
  const url = <?= "'".base_url('classic/classicFirearmByDate', 'http')."'"; ?>;

  var myHeaders = new Headers();

  const form = new FormData(document.querySelector('#form1'));

  // The parameters we are gonna pass to the fetch function
  let fetchData = {
      method: 'POST',
      headers: myHeaders,
      body: new URLSearchParams(form)
  }

  //{method: "POST",header:myHeaders,body:{date:'2020baby'}}
  fetch(url, fetchData, message())
  .then((res) => res.text())
  .then(text => console.log(text))
  .catch((error) => console.log(error));

}, false);
function message() {
  var evtSource = new EventSource(<?= "'".base_url('classic/classicFirearmByDate', 'http')."'"; ?> );
  var eventList = document.querySelector('#message');

  evtSource.onopen = function () {
      console.log("Connection to server opened.");
  };

  evtSource.onmessage = function (e) {
      console.log(e);
      var newElement = document.getElementById("message");

      newElement.textContent = "message: " + e.data;
      // eventList.appendChild(newElement);
  };

  evtSource.onerror = function () {
      console.log("EventSource failed.");
  };
}
</script>

My controller.php

<?php
class Classic extends CI_Controller{
    . . .
public function classicFirearmByDate() {
    $data['title'] = 'Classic Firearms';
    $sandbox = $this->input->post('sandbox');
    . . .
    $date = trim(htmlspecialchars($this->input->post('date')));
    $dateTo = trim(htmlspecialchars($this->input->post('dateTo')));
    $data['body'] = $this->classic_firearms->get_firearm_by_date($date, $dateTo, $sandbox, $this->input->post());

My model.php

<?php
class Classic_firearms extends CI_Model{
. . .
public function get_firearm_by_date($date, $dateTo, $sandbox, $test) {
        $this->sessionId = $this->login($sandbox);
        $filter = array('complex_filter' => array(
                array(
                        'key' => 'updated_at',
                        'value' => array(
                                'key' => 'from',
                                'value' => $date//'2019-10-03 09:44:30'//
                        ),
                ),
                array(
                        'key' => 'updated_at',
                        'value' => array(
                                'key' => 'to',
                                'value' => $dateTo//'2019-10-03 09:46:30'//
                        ),
                ),
        ));

        $productId = $this->proxy->catalogProductList($this->sessionId, $filter);


        header("Content-Type: text/event-stream");
        header("Cache-Control: no-cache");
        header("Connection: keep-alive");

        if ($productId != null || $productId != [] ) {
                . . . //Many cURL requests and data conversion
                        echo 'data:  Working on {$product_name} Product!', "\n\n";

                        // flush the output buffer and send echoed messages to the browser
                        flush();



Aucun commentaire:

Enregistrer un commentaire