Explorar el Código

upgrade to StatusHeartPost and work on StatusInstaGram, which will probably never be used

logicp hace 7 años
padre
commit
7cd889d9f8
Se han modificado 4 ficheros con 400 adiciones y 19 borrados
  1. 4 4
      config/schema/statusmessage.schema.yml
  2. 48 14
      src/StatusHeartPost.php
  3. 348 0
      src/StatusInstagram.php
  4. 0 1
      src/StatusTwitter.php

+ 4 - 4
config/schema/statusmessage.schema.yml

@@ -19,12 +19,12 @@ instagram_api.config:
   type: config_object
   label: 'Credentials to authenticate with Instagram API'
   mapping:
-    oauth_access_token:
+    client_id:
           type: text
-          label: 'Access Token'
-    oauth_access_token_secret:
+          label: 'Client ID'
+    client_secret:
           type: text
-          label: 'Access Token Secret'
+          label: 'Client Secret'
     consumer_key:
           type: text
           label: 'Consumer key'

+ 48 - 14
src/StatusHeartPost.php

@@ -46,8 +46,8 @@ class StatusHeartPost implements SharedContentInterface {
 
       $tags = $this->processTerms();
 
-      if ($fid = $this->getMedia()) {
-        $node->set('field_image', $fid);
+      if ($fids = $this->getMedia()) {
+        $node->set('field_image', $fids);
       }
 
       if (!empty($this->tags)) {
@@ -85,10 +85,10 @@ class StatusHeartPost implements SharedContentInterface {
   private function setNodeData() {
 
     $append = FALSE;
-
+    $title = $this->generator->getTitle();
     $node = Node::create([
       'type' => 'heartpost',
-      'title' => $this->generator->getTitle(),
+      'title' => strlen($title) < 50 ? $title : substr($title, 0, 47) . '...',
       'status' => 1,
     ]);
 
@@ -117,21 +117,41 @@ class StatusHeartPost implements SharedContentInterface {
   }
 
 
-  private function getMedia() {
+  private function getMedia()
+  {
+
+    $fids = array();
 
-    if ($this->generator->getImage()) {
+    if ($images = $this->generator->getImages()) {
+      for ($i = 0; $i < 10; $i++) {
+        if (count($fids) < 6 && $images[$i]['width'] > 400) {
+          $ext = strtolower(pathinfo($images[$i]['url'], PATHINFO_EXTENSION));
+          if (!$this->verifyExtension($ext)) {
+            $ext = explode($ext, $images[$i]['url']);
+            $ext = count($ext) > 1 ? $ext[1] : $ext[0];
+          }
+          $ext = strpos($ext, '?') ? substr($ext, 0, strpos($ext, '?')) : $ext;
+          $fileUrl = strlen($ext) > 0 ? substr($images[$i]['url'], 0, strpos($images[$i]['url'], $ext)) . $ext : $images[$i]['url'];
+          $data = file_get_contents($fileUrl);
+          $file = file_save_data($data, 'public://' . substr($fileUrl, strrpos($images[$i]['url'], '/') + 1), FILE_EXISTS_REPLACE);
+          $fids[] = $file->id();
+        }
+      }
+    } else {
 
-      $ext = strtolower(pathinfo($this->generator->getImage(), PATHINFO_EXTENSION));
-      $ext = strpos($ext, '?') ? substr($ext, 0, strpos($ext, '?')) : $ext;
-      $fileUrl = strlen($ext) > 0 ? substr($this->generator->getImage(), 0, strpos($this->generator->getImage(), $ext)) . $ext : $this->generator->getImage();
+      if ($this->generator->getImage()) {
 
-      $mainImage = file_get_contents($fileUrl);
-      $file = file_save_data($mainImage, 'public://' . substr($fileUrl, strrpos($this->generator->getImage(), '/') + 1), FILE_EXISTS_REPLACE);
+        $ext = strtolower(pathinfo($this->generator->getImage(), PATHINFO_EXTENSION));
+        $ext = strpos($ext, '?') ? substr($ext, 0, strpos($ext, '?')) : $ext;
+        $fileUrl = strlen($ext) > 0 ? substr($this->generator->getImage(), 0, strpos($this->generator->getImage(), $ext)) . $ext : $this->generator->getImage();
 
-      return $file->id();
-    }
-//    return $this->generator->getImages();
+        $mainImage = file_get_contents($fileUrl);
+        $file = file_save_data($mainImage, 'public://' . substr($fileUrl, strrpos($this->generator->getImage(), '/') + 1), FILE_EXISTS_REPLACE);
 
+        $fids[] = $file->id();
+      }
+    }
+    return $fids;
   }
 
 
@@ -184,4 +204,18 @@ class StatusHeartPost implements SharedContentInterface {
       }
     return $tids;
   }
+
+  public function verifyExtension($string) {
+    return $this->strposMultiple($string, ['jpg', 'jpeg', 'png', 'gif', 'bmp', ]);
+  }
+
+  public function strposMultiple($string, $patterns) {
+    $patterns = is_array($patterns) ? $patterns : is_object($patterns) ? (array) $patterns : array($patterns);
+
+    foreach($patterns as $pattern) {
+      if (stripos($string, $pattern)) {
+        return true;
+      }
+    }
+  }
 }

+ 348 - 0
src/StatusInstagram.php

@@ -0,0 +1,348 @@
+<?php
+/**
+ * Created by IntelliJ IDEA.
+ * User: logicp
+ * Date: 6/9/17
+ * Time: 4:12 PM
+ */
+
+namespace Drupal\statusmessage;
+
+//require_once DRUPAL_ROOT .'/vendor/autoload.php';
+//require_once __DIR__ . './../includes/InstagramAPIExchange.php';
+
+use InstagramAPIExchange;
+use Drupal\statusmessage\Entity;
+use Drupal\taxonomy\Entity\Term;
+use Drupal\node\Entity\Node;
+use Drupal\file\Entity\File;
+//use Drupal\Core\File;
+
+
+class StatusInstagram {
+
+  protected $oauthAccessToken;
+  protected $oauthAccessTokenSecret;
+  protected $consumerKey;
+  protected $consumerSecret;
+  protected $parameter;
+
+  private $instagramConfig;
+
+  public function __construct($parameter) {
+    $this->instagramConfig = \Drupal::config('instagram_api.settings');
+    $this->parameter = $parameter;
+  }
+
+
+  /**
+   * @return mixed
+   */
+  public function getConsumerSecret()
+  {
+    return $this->consumerSecret;
+  }
+
+  /**
+   * @param mixed $consumerSecret
+   */
+  public function setConsumerSecret($consumerSecret)
+  {
+    $this->consumerSecret = $consumerSecret;
+  }
+
+  /**
+   * @return mixed
+   */
+  public function getConsumerKey()
+  {
+    return $this->consumerKey;
+  }
+
+  /**
+   * @param mixed $consumerKey
+   */
+  public function setConsumerKey($consumerKey) {
+    $this->consumerKey = $consumerKey;
+  }
+
+  /**
+   * @return mixed
+   */
+  public function getOauthAccessTokenSecret()
+  {
+    return $this->oauthAccessTokenSecret;
+  }
+
+  /**
+   * @param mixed $oauthAccessTokenSecret
+   */
+  public function setOauthAccessTokenSecret($oauthAccessTokenSecret) {
+    $this->oauthAccessTokenSecret = $oauthAccessTokenSecret;
+  }
+
+  /**
+   * @return mixed
+   */
+  public function getOauthAccessToken() {
+    return $this->oauthAccessToken;
+  }
+
+  /**
+   * @param mixed $oauthAccessToken
+   */
+  public function setOauthAccessToken($oauthAccessToken) {
+    $this->oauthAccessToken = $oauthAccessToken;
+  }
+
+  private function getApiStatusParameter() {
+    return 'https://api.Instagram.com/1.1/statuses/show.json';
+  }
+
+
+  private function generateRequest($url) {
+
+    $twid = $this->parseUrl($url);
+
+    $settings = [
+      'oauth_access_token' => $this->instagramConfig->get('oauth_access_token'),
+      'oauth_access_token_secret' => $this->instagramConfig->get('oauth_access_token_secret'),
+      'consumer_key' => $this->instagramConfig->get('consumer_key'),
+      'consumer_secret' => $this->instagramConfig->get('consumer_secret'),
+    ];
+
+    $instagramApi = new InstagramAPIExchange($settings);
+    $getField = '?id=' . $twid . '&tweet_mode=extended';
+    return $instagramApi
+      ->setGetfield($getField)
+      ->buildOauth($this->getApiStatusParameter(), 'GET');
+  }
+
+  public function sendRequest() {
+
+    if ($response = $this->generateRequest($this->parameter)->performRequest()) {
+
+      $data = json_decode($response);
+      $tweetNode = $this->setNodeData($data);
+
+      $media = $this->getTweetMedia($data);
+
+      if ($media->images) {
+        $tweetNode->set('field_tweet_images', $media->images);
+      }
+
+      if ($media->video) {
+        $tweetNode->set('field_video', $media->video);
+      }
+
+      if ($media->userImage) {
+        $tweetNode->set('field_user_image', $media->userImage);
+      }
+
+
+      if ($tweetNode->save()) {
+        return $tweetNode->id();
+      }
+      return null;
+    }
+  }
+
+  private function parseUrl ($text) {
+    return explode('status/', $text)[1];
+  }
+
+
+  private function setNodeData($data) {
+
+    //Create datetime object for title, media file path and content date field
+    $nowTime = new \DateTime();
+    $posted = date('Y-m-d\TH:i:s', strtotime($data->created_at));
+    $user = \Drupal::currentUser();
+    $ip =  \Drupal::request()->getClientIp();//get user's IP
+
+    $links = [];
+
+    $terms = $this->processTerms($data);
+
+    if (!empty($data->entities->urls)) {
+      foreach ($data->entities->urls as $url) {
+        $links[] = !strpos($url->display_url, 'http') ? 'http://' . $url->display_url : $url->display_url;
+      }
+    }
+    //Check for attached media and create a directory for saving
+    if (isset($data->extended_entities->media)) {
+      $media = $this->getTweetMedia($data);
+    }
+
+    if ($data->user->profile_image_url_https) {
+      //TODO get profile image
+    }
+
+    $node = Node::create([
+      'type' => 'tweet',
+      'title' => $data->user->screen_name . '_' . $nowTime->format('Y.m.d.Hi'),
+      'uid' => $user->id(),
+      'field_tags' => $terms->tags,
+      'field_tweet_url' => $this->parameter,
+      'field_twit_id' => $data->id,
+      'field_post_date' => [$posted],
+      'field_username' => $terms->username,
+      'field_users' => $terms->users,
+      'field_links' => $links,
+      'status' => 1,
+    ]);
+
+    $node->set('body', ['value' => '<div class="created-date"> ' . $data->created_at . '</div>' . $data->full_text, 'format' =>'full_html']);
+    return $node;
+
+  }
+
+
+  private function getTweetMedia($data) {
+
+    $media = new \stdClass();
+    $images = [];
+    $video = null;
+    $userImage = null;
+
+    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_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_EXISTS_REPLACE);
+      $images[] = $file->id();
+    }
+    if (!empty($data->extended_entities->media[0]->video_info->variants)) {
+      $z = null;
+      $vidUrl = null;
+      $bitrate = new \stdClass();
+      $bitrate->value = null;
+      $bitrate->index = null;
+
+      $variantCount = count($data->extended_entities->media[0]->video_info->variants);
+      if ($variantCount > 1) {
+        for ($z = 0; $z < $variantCount; $z++) {
+          if ($data->extended_entities->media[0]->video_info->variants[$z]->bitrate &&
+            $data->extended_entities->media[0]->video_info->variants[$z]->content_type === 'video/mp4'
+          ) {
+            if ($data->extended_entities->media[0]->video_info->variants[$z]->bitrate > $bitrate->value) {
+              $bitrate->value = $data->extended_entities->media[0]->video_info->variants[$z]->bitrate;
+              $bitrate->index = $z;
+            }
+          }
+        }
+      } else {
+        $bitrate->index = 0;
+      }
+
+      if ($bitrate->index !== null) {
+        $data->extended_entities->media[0]->video_info->variants[$bitrate->index]->url;
+//        $video = system_retrieve_file($vidUrl, null, TRUE);
+//        $file = File::create([
+//          '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_EXISTS_REPLACE);
+        $video = $file->id();
+      }
+    }
+
+    $media->images = $images;
+    $media->video = $video;
+    $media->userImage = $userImage;
+
+    return $media;
+  }
+
+  private function processTerms($data) {
+
+    $terms = new \stdClass();
+    $terms->tags = [];
+    $terms->users = [];
+    $terms->username = -1;
+
+    if ($data->user->screen_name) {
+      $term = \Drupal::entityQuery('taxonomy_term')
+        ->condition('name', $data->user->screen_name)
+        ->condition('vid', 'instagram_user')
+        ->execute();
+
+      if (count($term) < 1) {
+        $term = Term::create([
+          'name' => $data->user->screen_name,
+          'vid' => 'instagram_user',
+          'field_count' => 1
+        ]);
+        if ($term->save()) {
+          $terms->username = $term->id();
+          if (\Drupal::moduleHandler()->moduleExists('heartbeat')) {
+            \Drupal\heartbeat\Entity\Heartbeat::newTermUsage($term->id());
+          }
+        } else {
+          \Drupal::logger('StatusInstagram')
+            ->warning('Could not save term with name %name', array('%name' => $data->user->screen_name));
+        }
+      } else {
+        $terms->username = array_values($term)[0];
+        if (\Drupal::moduleHandler()->moduleExists('heartbeat')) {
+          \Drupal\heartbeat\Entity\Heartbeat::updateTermUsage(array_values($term)[0], 'instagram_user');
+        }
+      }
+      $term = NULL;
+      foreach ($data->entities->hashtags as $key => $h) {
+        $term = \Drupal::entityQuery('taxonomy_term')
+          ->condition('name', $h->text)
+          ->condition('vid', 'Instagram')
+          ->execute();
+
+        if (count($term) < 1) {
+          $term = Term::create(['name' => $h->text, 'vid' => 'Instagram', 'field_count' => 1]);
+          if ($term->save()) {
+            $terms->tags[] = $term->id();
+            if (\Drupal::moduleHandler()->moduleExists('heartbeat')) {
+              \Drupal\heartbeat\Entity\Heartbeat::newTermUsage($term->id());
+            }
+          } else {
+            \Drupal::logger('StatusInstagram')
+              ->warning('Could not save term with name %name', array('%name' => $h->text));
+          }
+        } else {
+          $terms->tags[] = array_values($term)[0];
+          if (\Drupal::moduleHandler()->moduleExists('heartbeat')) {
+            \Drupal\heartbeat\Entity\Heartbeat::updateTermUsage(array_values($term)[0], 'Instagram');
+          }
+        }
+      }
+      $term = NULL;
+      foreach ($data->entities->user_mentions as $u) {
+        $term = \Drupal::entityQuery('taxonomy_term')
+          ->condition('name', $u->screen_name)
+          ->condition('vid', 'instagram_user')
+          ->execute();
+
+        if (count($term) < 1) {
+          $term = Term::create([
+            'name' => $u->screen_name,
+            'vid' => 'instagram_user'
+          ]);
+          if ($term->save()) {
+            $terms->users[] = $term->id();
+          } else {
+            \Drupal::logger('StatusInstagram')
+              ->warning('Could not save term with name %name', array('%name' => $u->screen_name));
+          }
+        } else {
+          $terms->users[] = array_values($term)[0];
+        }
+
+      }
+    }
+    return ($terms);
+  }
+}
+
+

+ 0 - 1
src/StatusTwitter.php

@@ -209,7 +209,6 @@ class StatusTwitter {
       $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_EXISTS_REPLACE);
 
-
       $userImage = $file->id();
     }
     foreach($data->extended_entities->media as $media)  {