Explorar el Código

Auto Preview and other changes including sending frienddata if heartbeat is intsalled

logicp hace 7 años
padre
commit
83a91a14a6

+ 83 - 0
js/statusmessage.js

@@ -0,0 +1,83 @@
+/**
+ * Created by logicp on 6/05/17.
+ */
+(function($, Drupal, drupalSettings) {
+  Drupal.behaviors.status= {
+    attach: function (context, settings) {
+
+      Drupal.AjaxCommands.prototype.generatePreview = function(ajax, response, status) {
+
+        if (validateUrl(response.url)) {
+          console.dir(response);
+        }
+        var cleanUrl = response.url.replace(/^http(s?):\/\//i, "");
+        // console.log(cleanUrl);
+        $.ajax({
+          type:'POST',
+          url:'/statusmessage/generate-preview/' + cleanUrl,
+          success: function(response) {
+
+            // console.log(response.data);
+            if (response.data != null) {
+              var parser = new DOMParser();
+              var doc = parser.parseFromString(response.data, "text/html");
+
+              var imgs = doc.querySelectorAll('img')
+              var metaTags = doc.querySelectorAll('meta');
+              var title = doc.querySelector('title');
+              var markup;
+              var description;
+              var previewImage;
+
+              imgs.forEach(function (img) {
+                var imgClasses = img.classList;
+                if (imgClasses.value !== null && imgClasses.value.length > 0) {
+                  if (imgClasses.value.includes('logo')) {
+                    previewImage = img;
+                  }
+                }
+                if (previewImage !== null) {
+                }
+              });
+
+
+              metaTags.forEach(function (metaTag) {
+                if (metaTag.name == 'description') {
+                  description = metaTag.content;
+
+                }
+              });
+
+              console.dir(description);
+              console.log(previewImage);
+
+              markup = '<div id="statusmessage-preview"><h2> ' + title != null ? title.innerHTML : "No Title</h2>"
+                + description != null ? description.innerHTML : "No Description"
+                  + '<img src="' + previewImage != null ? previewImage.src + '" />' : 'google images />'
+                    + '</div>';
+
+              console.dir(markup);
+              console.log(markup);
+
+
+              var statusBlock = document.getElementById('block-statusblock');
+              var previewIframe = document.createElement('iframe');
+              previewIframe.classList.add('statusmessage-preview-iframe');
+              statusBlock.appendChild(previewIframe);
+              previewIframe.contentWindow.document.open();
+              previewIframe.contentWindow.document.write(markup);
+              previewIframe.contentWindow.document.close();
+            }
+          }
+        });
+      };
+
+      function validateUrl(input) {
+        return input.match(new RegExp("([a-zA-Z0-9]+://)?([a-zA-Z0-9_]+:[a-zA-Z0-9_]+@)?([a-zA-Z0-9.-]+\\.[A-Za-z]{2,4})(:[0-9]+)?(/.*)?"));
+      }
+
+    }
+  };
+
+})(jQuery, Drupal, drupalSettings);
+

+ 20 - 0
src/Ajax/ClientCommand.php

@@ -0,0 +1,20 @@
+<?php
+namespace Drupal\statusmessage\Ajax;
+
+use Drupal\Core\Ajax\CommandInterface;
+
+class ClientCommand implements CommandInterface {
+  protected $message;
+
+  public function __construct($message) {
+    $this->message = $message;
+  }
+
+  public function render() {
+
+    return array(
+      'command' => 'generatePreview',
+      'url' => $this->message
+    );
+  }
+}

+ 35 - 0
src/ClientGeneratorService.php

@@ -0,0 +1,35 @@
+<?php
+
+namespace Drupal\statusmessage;
+use Drupal\Core\Entity\Query\QueryFactory;
+use Drupal\Core\Entity\EntityTypeManager;
+use GuzzleHttp\Client;
+
+/**
+ * Class StatusTypeService.
+ *
+ * @package Drupal\statusmessage
+ */
+class ClientGeneratorService {
+
+  protected $httpClient;
+
+  /**
+   * Constructor.
+   */
+  public function __construct(Client $http_client) {
+    $this->httpClient = $http_client;
+  }
+
+
+  public function generatePreview($url) {
+
+    $request = $this->httpClient->post('/statusmessage/generate/preview/', [
+      'payload' => $url
+    ]);
+
+    $response = $request->getBody();
+
+  }
+
+}

+ 40 - 5
src/Controller/StatusPreviewController.php

@@ -1,8 +1,14 @@
 <?php
 
 namespace Drupal\statusmessage\Controller;
+require_once(DRUPAL_ROOT .'/vendor/autoload.php');
 
 use Drupal\Core\Controller\ControllerBase;
+use Symfony\Component\HttpFoundation\Response;
+use Symfony\Component\DependencyInjection\ContainerInterface;
+use GuzzleHttp\Client;
+
+
 
 /**
  * Class StatusPreviewController.
@@ -11,17 +17,46 @@ use Drupal\Core\Controller\ControllerBase;
  */
 class StatusPreviewController extends ControllerBase {
 
+  protected $httpClient;
+
+  /**
+   * {@inheritdoc}
+   */
+  public static function create(ContainerInterface $container) {
+    return new static(
+      $container->get('http_client'));
+  }
+
+  /**
+   * Constructor.
+   */
+  public function __construct(Client $http_client) {
+    $this->httpClient = $http_client;
+  }
   /**
    * Generate.
    *
    * @return string
    *   Return Hello string.
    */
-  public function generate() {
-    return [
-      '#type' => 'markup',
-      '#markup' => $this->t('Implement method: generate')
-    ];
+  public function generate($url) {
+
+    \Drupal::logger('StatusPreviewController')->debug('This is getting called');
+
+    $ogParsed = '';
+    $contents = file_get_contents('http://' . $url);
+
+
+    $response = new Response();
+    $response->setContent(\GuzzleHttp\json_encode(array('data' => $contents)));
+    $response->headers->set('Content-Type', 'application/json');
+    return $response;
+
+//    $seeethis = 'none';
+//    return [
+//      '#type' => 'form',
+//      '#plain_text' => $url,
+//    ];
   }
 
 }

+ 40 - 3
src/Form/StatusForm.php

@@ -5,8 +5,10 @@ namespace Drupal\statusmessage\Form;
 use Drupal\Core\Form\FormBase;
 use Drupal\Core\Form\FormStateInterface;
 use Drupal\statusmessage\Entity\Status;
+use Drupal\statusmessage\ClientGeneratorService;
 use Drupal\statusmessage\StatusService;
 use Drupal\statusmessage\StatusTypeService;
+use Drupal\statusmessage\Ajax\ClientCommand;
 use Drupal\heartbeat\HeartbeatStreamServices;
 use Drupal\Core\Ajax\AjaxResponse;
 use Drupal\heartbeat\Ajax\SelectFeedCommand;
@@ -24,13 +26,16 @@ class StatusForm extends FormBase {
 
   protected $statusService;
 
+  protected $previewGenerator;
+
   /**
    * {@inheritdoc}
    */
   public static function create(ContainerInterface $container) {
     return new static(
       $container->get('status_type_service'),
-      $container->get('statusservice'));
+      $container->get('statusservice'),
+      $container->get('preview_generator'));
   }
 
   /**
@@ -38,9 +43,10 @@ class StatusForm extends FormBase {
    * @param StatusTypeService $status_type_service
    * @param StatusService $status_service
    */
-  public function __construct(StatusTypeService $status_type_service, StatusService $status_service) {
+  public function __construct(StatusTypeService $status_type_service, StatusService $status_service, ClientGeneratorService $preview_generator) {
     $this->statusTypeService = $status_type_service;
     $this->statusService = $status_service;
+    $this->previewGenerator = $preview_generator;
   }
 
   /**
@@ -49,13 +55,25 @@ class StatusForm extends FormBase {
   public function buildForm(array $form, FormStateInterface $form_state) {
     /* @var $entity \Drupal\statusmessage\Entity\Status */
 
+    $form['#attached']['library'][] = 'statusmessage/status';
+
+    if (\Drupal::moduleHandler()->moduleExists('heartbeat')) {
+      $friendData = \Drupal::config('heartbeat_friendship.settings')->get('data');
+
+      $form['#attached']['library'][] = 'heartbeat/heartbeat';
+      $form['#attached']['drupalSettings']['friendData'] = $friendData;
+    }
+
     $form['message'] = array(
       '#type' => 'textarea',
       '#description' => 'Status Message',
       '#attributes' => array(
         'placeholder' => t('Post a status update'),
       ),
-
+      '#ajax' => [
+        'event' => 'change',
+        'callback' => '::statusAjaxSubmit',
+      ],
     );
 
 
@@ -122,6 +140,25 @@ $stophere = null;
 
   public function statusAjaxSubmit(array &$form, FormStateInterface $form_state) {
 
+    $message = $form_state->getValue('message');
+
+    preg_match_all('#\bhttps?://[^,\s()<>]+(?:\([\w\d]+\)|([^,[:punct:]\s]|/))#', $message, $match);
+
+
+    if ($this->previewGenerator !== null && !empty($match) && array_values($match)[0]) {
+
+      $url = array_values($match)[0];
+
+//      $this->previewGenerator->generatePreview($url);
+
+      $response = new AjaxResponse();
+      $response->addCommand(new ClientCommand($url[0]));
+
+      return $response;
+
+
+    }
+
     if (!empty($this->statusTypeService)) {
       foreach ($this->statusTypeService->loadAll() as $type) {
         if (!$type->getMedia()) {

+ 9 - 0
statusmessage.libraries.yml

@@ -0,0 +1,9 @@
+status:
+  version: 1.x
+  js:
+    js/statusmessage.js: {}
+  dependencies:
+    - core/jquery
+    - core/jquery.once
+    - core/drupal
+    - core/drupalSettings

+ 12 - 4
statusmessage.routing.yml

@@ -6,12 +6,20 @@ statusmessage.status_form:
     _title: 'DefaultForm'
   requirements:
     _access: 'TRUE'
-  
 
-statusmessage.status_preview_controller_generate:
-  path: '/statusmessage/generate/preview'
+
+#statusmessage.status_preview_controller_generate:
+#  path: '/statusmessage/generate/preview/{url}'
+#  defaults:
+#    _controller: '\Drupal\statusmessage\Controller\StatusPreviewController::generate'
+#    _title: 'Preview Generator'
+#  requirements:
+#    _permission: 'access content'
+
+statusmessage.status_preview_controller_generate_35:
+  path: '/statusmessage/generate-preview/{url}'
   defaults:
     _controller: '\Drupal\statusmessage\Controller\StatusPreviewController::generate'
-    _title: 'Preview Generator'
+    _title: 'Generate'
   requirements:
     _permission: 'access content'

+ 3 - 0
statusmessage.services.yml

@@ -7,3 +7,6 @@ services:
     class: Drupal\statusmessage\StatusTypeService
     arguments: ['@entity.query', '@entity_type.manager']
 
+  preview_generator:
+    class: Drupal\statusmessage\ClientGeneratorService
+    arguments: ['@http_client']