Explorar el Código

Major update
adding parsing on server side
improved form behaviour

logicp hace 7 años
padre
commit
ff4243ff32

+ 79 - 0
src/Controller/StatusPreviewController.php

@@ -44,6 +44,21 @@ class StatusPreviewController extends ControllerBase {
     if ($url == 'build') {
       $url = \Drupal::request()->get('data');
 
+
+
+      $this->dom = new \DOMDocument;
+      $contents = file_get_contents('http://' . $url);
+      $this->dom->loadHTML($contents);
+
+      $xpath = new \DomXpath($this->dom);
+
+      $anchorAttributes = $this->getAnchorNodeNames();
+      $imgAttributes = $this->getImgNodeNames();
+      $imgLogos = $this->searchDom('img', 'logo');
+      $anchorLogos = $this->searchDom('a', 'logo');
+
+
+
       $contents = file_get_contents('http://' . $url);
       $response = new Response();
       $response->setContent(\GuzzleHttp\json_encode(array('data' => $contents)));
@@ -54,4 +69,68 @@ class StatusPreviewController extends ControllerBase {
 
   }
 
+
+
+  private function getAnchorNodeNames() {
+    if ($this->dom) {
+      $names = array();
+      $attrXpath = new \DomXpath($this->dom);
+
+      $nodes = $attrXpath->query('//a/@*');
+      $i = 0;
+      foreach ($nodes as $node) {
+        $names[$i] = new \stdClass();
+        $names[$i]->name = $node->nodeName;
+        $names[$i]->value = $node->nodeValue;
+        $i++;
+      }
+
+      return $names;
+    }
+  }
+
+  private function getImgNodeNames() {
+    if ($this->dom) {
+      $names = array();
+      $attrXpath = new \DomXpath($this->dom);
+
+      $nodes = $attrXpath->query('//img/@*');
+      $i = 0;
+      foreach ($nodes as $node) {
+        $names[$i] = new \stdClass();
+        $names[$i]->name = $node->nodeName;
+        $names[$i]->value = $node->nodeValue;
+        $i++;
+      }
+
+      return $names;
+    }
+  }
+
+  private function searchDom($tag, $string) {
+
+    if ($this->dom) {
+
+      $results = array();
+      $tags = $this->dom->getElementsByTagName($tag);
+
+
+      for ($i = 0; $i < $tags->length; $i++) {
+        $results[$i] = new \stdClass();
+
+        $src = $tags->item($i)->getAttribute('src');
+        if (strpos($src, 'logo')) {
+          $results[$i]->src = $src;
+        }
+
+        $href = $tags->item($i)->getAttribute('href');
+        if (strpos($href, 'logo')) {
+          $results[$i]->href = $href;
+        }
+      }
+
+      return $results;
+    }
+  }
+
 }

+ 60 - 45
src/Form/StatusForm.php

@@ -84,18 +84,18 @@ class StatusForm extends FormBase {
       ],
     );
 
-    $form['mediatabs'] = [
-      '#type' => 'radios',
-//      '#description' => $this->t('User selectable feeds'),
-      '#options' => $this->mediaTabs,
-//      '#ajax' => [
-//        'callback' => '::updateFeed',
-////        'event' => 'onclick',
-//        'progress' => array(
-//          'type' => 'none',
-////        'message' => t('Fetching feed'),
-//        ),
-      ];
+//    $form['mediatabs'] = [
+//      '#type' => 'radios',
+////      '#description' => $this->t('User selectable feeds'),
+//      '#options' => $this->mediaTabs,
+////      '#ajax' => [
+////        'callback' => '::updateFeed',
+//////        'event' => 'onclick',
+////        'progress' => array(
+////          'type' => 'none',
+//////        'message' => t('Fetching feed'),
+////        ),
+//      ];
 
 
     $form['post'] = array(
@@ -215,53 +215,68 @@ $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 (strpos($message, 'twitter')) {
-      if ($this->previewGenerator !== null && !empty($match) && array_values($match)[0] !== null) {
-        $url = is_array(array_values($match)[0]) ? array_values(array_values($match)[0])[0]: array_values($match)[0];
-        $statusTwitter = new StatusTwitter($url);
-        $nid = $statusTwitter->sendRequest();
+    if (strlen(trim($message)) > 1) {
+      preg_match_all('#\bhttps?://[^,\s()<>]+(?:\([\w\d]+\)|([^,[:punct:]\s]|/))#', $message, $match);
+      if (strpos($message, 'twitter')) {
+        if ($this->previewGenerator !== NULL && !empty($match) && array_values($match)[0] !== NULL) {
+          $url = is_array(array_values($match)[0]) ? array_values(array_values($match)[0])[0] : array_values($match)[0];
+          $statusTwitter = new StatusTwitter($url);
+          $nid = $statusTwitter->sendRequest();
+//        return $nid;
+        }
       }
-    } else if (strpos($message, 'youtube') || strpos($message, 'youtu.be')) {
-      if ($this->previewGenerator !== null && !empty($match) && array_values($match)[0] !== null) {
-        $url = is_array(array_values($match)[0]) ? array_values(array_values($match)[0])[0]: array_values($match)[0];
-        $statusYoutube = new StatusYoutube($url);
-        $nid = $statusYoutube->generateNode();
+      else {
+        if (strpos($message, 'youtube') || strpos($message, 'youtu.be')) {
+          if ($this->previewGenerator !== NULL && !empty($match) && array_values($match)[0] !== NULL) {
+            $url = is_array(array_values($match)[0]) ? array_values(array_values($match)[0])[0] : array_values($match)[0];
+            $statusYoutube = new StatusYoutube($url);
+            $nid = $statusYoutube->generateNode();
+//        return $nid;
+          }
+        }
       }
-    }
 
-    if (!empty($this->statusTypeService)) {
-      foreach ($this->statusTypeService->loadAll() as $type) {
-        if (!$type->getMedia()) {
+      if ($nid === NULL && !empty($this->statusTypeService)) {
+        foreach ($this->statusTypeService->loadAll() as $type) {
+          if (!$type->getMedia()) {
 
-          $userViewed = \Drupal::routeMatch()->getParameters()->get('user') === null ? \Drupal::currentUser()->id() : \Drupal::routeMatch()->getParameters()->get('user')->id();
+            $userViewed = \Drupal::routeMatch()
+              ->getParameters()
+              ->get('user') === NULL ? \Drupal::currentUser()
+              ->id() : \Drupal::routeMatch()
+              ->getParameters()
+              ->get('user')
+              ->id();
 
-          if ($userViewed !== null) {
+            if ($userViewed !== NULL) {
 
-            $statusEntity = Status::create([
-              'type' => $type->id(),
-              'uid' => \Drupal::currentUser()->id(),
-              'recipient' => $userViewed
-            ]);
+              $statusEntity = Status::create([
+                'type' => $type->id(),
+                'uid' => \Drupal::currentUser()->id(),
+                'recipient' => $userViewed
+              ]);
 
-            $statusEntity->setMessage($message);
-            $statusEntity->save();
+              $statusEntity->setMessage($message);
+              $statusEntity->save();
+            }
+          }
+        }
+      }
 
-            if (\Drupal::service('module_handler')->moduleExists('heartbeat')) {
+      if (\Drupal::service('module_handler')
+          ->moduleExists('heartbeat') && ($nid !== NULL || $statusEntity !== NULL)
+      ) {
 
 //              $configManager = \Drupal::service('config.manager');
-              $feedConfig = \Drupal::config('heartbeat_feed.settings');
+        $feedConfig = \Drupal::config('heartbeat_feed.settings');
 //              $feedConfig = $feedConfig = $configManager->get('heartbeat_feed.settings');
-              $response = new AjaxResponse();
-              $response->addCommand(new SelectFeedCommand($feedConfig->get('message')));
+        $response = new AjaxResponse();
+        $response->addCommand(new SelectFeedCommand($feedConfig->get('message')));
 
-              return $response;
-            }
-            break;
-          }
-        }
+        return $response;
       }
     }
+    return null;
   }
 
   /**

+ 80 - 0
src/Plugin/Field/FieldFormatter/StatusMessageFormatter.php

@@ -0,0 +1,80 @@
+<?php
+
+namespace Drupal\statusmessage\Plugin\Field\FieldFormatter;
+
+use Drupal\Component\Utility\Html;
+use Drupal\Core\Field\FieldItemInterface;
+use Drupal\Core\Field\FieldItemListInterface;
+use Drupal\Core\Field\FormatterBase;
+use Drupal\Core\Form\FormStateInterface;
+
+/**
+ * Plugin implementation of the 'status_message_formatter' formatter.
+ *
+ * @FieldFormatter(
+ *   id = "status_message_formatter",
+ *   label = @Translation("Status message formatter"),
+ *   field_types = {
+ *     "string_long"
+ *   }
+ * )
+ */
+class StatusMessageFormatter extends FormatterBase {
+
+  /**
+   * {@inheritdoc}
+   */
+  public static function defaultSettings() {
+    return [
+      // Implement default settings.
+    ] + parent::defaultSettings();
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function settingsForm(array $form, FormStateInterface $form_state) {
+    return [
+      // Implement settings form.
+    ] + parent::settingsForm($form, $form_state);
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function settingsSummary() {
+    $summary = [];
+    // Implement settings summary.
+
+    return $summary;
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public function viewElements(FieldItemListInterface $items, $langcode) {
+    $elements = [];
+
+    foreach ($items as $delta => $item) {
+      $elements[$delta] = ['#markup' => $this->viewValue($item)];
+    }
+
+    return $elements;
+  }
+
+  /**
+   * Generate the output appropriate for one field item.
+   *
+   * @param \Drupal\Core\Field\FieldItemInterface $item
+   *   One field item.
+   *
+   * @return string
+   *   The textual output generated.
+   */
+  protected function viewValue(FieldItemInterface $item) {
+    // The text value has no text format assigned to it, so the user input
+    // should equal the output, including newlines.
+    return nl2br(Html::escape($item->value));
+  }
+
+}

+ 3 - 3
src/StatusTwitter.php

@@ -207,14 +207,14 @@ class StatusTwitter {
 
     if ($data->user->profile_image_url_https) {
       $userImage = file_get_contents($data->user->profile_image_url_https);
-      $file = file_save_data($userImage, 'public://' . substr($data->user->profile_image_url_https, strrpos($data->user->profile_image_url_https, '/') + 1));
+      $file = file_save_data($userImage, 'public://' . substr($data->user->profile_image_url_https, strrpos($data->user->profile_image_url_https, '/') + 1), FILE_EXISTS_REPLACE);
 
 
       $userImage = $file->id();
     }
     foreach($data->extended_entities->media as $media)  {
       $image = file_get_contents($media->media_url);
-      $file = file_save_data($image, 'public://' . substr($media->media_url, strrpos($media->media_url, '/') + 1));
+      $file = file_save_data($image, 'public://' . substr($media->media_url, strrpos($media->media_url, '/') + 1), FILE_EXISTS_REPLACE);
       $images[] = $file->id();
     }
     if(!empty($data->extended_entities->media[0]->video_info->variants)) {
@@ -247,7 +247,7 @@ class StatusTwitter {
 //          'id' => 'id',
 //        ])->save();
         $video = file_get_contents($data->extended_entities->media[0]->video_info->variants[$bitrate->index]->url);
-        $file = file_save_data($video, 'public://' . substr($data->extended_entities->media[0]->video_info->variants[$bitrate->index]->url, strrpos($data->extended_entities->media[0]->video_info->variants[$bitrate->index]->url, '/') + 1));
+        $file = file_save_data($video, 'public://' . substr($data->extended_entities->media[0]->video_info->variants[$bitrate->index]->url, strrpos($data->extended_entities->media[0]->video_info->variants[$bitrate->index]->url, '/') + 1), FILE_EXISTS_REPLACE);
         $video = $file->id();
       }
     }