StatusTwitter.php 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. <?php
  2. /**
  3. * Created by IntelliJ IDEA.
  4. * User: logicp
  5. * Date: 6/9/17
  6. * Time: 4:12 PM
  7. */
  8. namespace Drupal\statusmessage;
  9. //require_once DRUPAL_ROOT .'/vendor/autoload.php';
  10. require_once __DIR__ . './../includes/TwitterAPIExchange.php';
  11. use TwitterAPIExchange;
  12. use Drupal\statusmessage\Entity;
  13. use Drupal\taxonomy\Entity\Term;
  14. use Drupal\node\Entity\Node;
  15. use Drupal\file\Entity\File;
  16. //use Drupal\Core\File;
  17. class StatusTwitter {
  18. protected $oauthAccessToken;
  19. protected $oauthAccessTokenSecret;
  20. protected $consumerKey;
  21. protected $consumerSecret;
  22. protected $parameter;
  23. private $twitterConfig;
  24. public function __construct($parameter) {
  25. $this->twitterConfig = \Drupal::config('twitter_api.settings');
  26. $this->parameter = $parameter;
  27. }
  28. /**
  29. * @return mixed
  30. */
  31. public function getConsumerSecret()
  32. {
  33. return $this->consumerSecret;
  34. }
  35. /**
  36. * @param mixed $consumerSecret
  37. */
  38. public function setConsumerSecret($consumerSecret)
  39. {
  40. $this->consumerSecret = $consumerSecret;
  41. }
  42. /**
  43. * @return mixed
  44. */
  45. public function getConsumerKey()
  46. {
  47. return $this->consumerKey;
  48. }
  49. /**
  50. * @param mixed $consumerKey
  51. */
  52. public function setConsumerKey($consumerKey) {
  53. $this->consumerKey = $consumerKey;
  54. }
  55. /**
  56. * @return mixed
  57. */
  58. public function getOauthAccessTokenSecret()
  59. {
  60. return $this->oauthAccessTokenSecret;
  61. }
  62. /**
  63. * @param mixed $oauthAccessTokenSecret
  64. */
  65. public function setOauthAccessTokenSecret($oauthAccessTokenSecret) {
  66. $this->oauthAccessTokenSecret = $oauthAccessTokenSecret;
  67. }
  68. /**
  69. * @return mixed
  70. */
  71. public function getOauthAccessToken() {
  72. return $this->oauthAccessToken;
  73. }
  74. /**
  75. * @param mixed $oauthAccessToken
  76. */
  77. public function setOauthAccessToken($oauthAccessToken) {
  78. $this->oauthAccessToken = $oauthAccessToken;
  79. }
  80. private function getApiStatusParameter() {
  81. return 'https://api.twitter.com/1.1/statuses/show.json';
  82. }
  83. private function generateRequest($url) {
  84. $twid = $this->parseUrl($url);
  85. $settings = [
  86. 'oauth_access_token' => $this->twitterConfig->get('oauth_access_token'),
  87. 'oauth_access_token_secret' => $this->twitterConfig->get('oauth_access_token_secret'),
  88. 'consumer_key' => $this->twitterConfig->get('consumer_key'),
  89. 'consumer_secret' => $this->twitterConfig->get('consumer_secret'),
  90. ];
  91. $twitterApi = new TwitterAPIExchange($settings);
  92. $getField = '?id=' . $twid . '&tweet_mode=extended';
  93. return $twitterApi
  94. ->setGetfield($getField)
  95. ->buildOauth($this->getApiStatusParameter(), 'GET');
  96. }
  97. public function sendRequest() {
  98. if ($response = $this->generateRequest($this->parameter)->performRequest()) {
  99. $data = json_decode($response);
  100. $tweetNode = $this->setNodeData($data);
  101. $media = $this->getTweetMedia($data);
  102. if ($media->images) {
  103. $tweetNode->set('field_tweet_images', $media->images);
  104. }
  105. if ($media->video) {
  106. $tweetNode->set('field_video', $media->video);
  107. }
  108. if ($media->userImage) {
  109. $tweetNode->set('field_user_image', $media->userImage);
  110. }
  111. if ($tweetNode->save()) {
  112. return $tweetNode->id();
  113. }
  114. return null;
  115. }
  116. }
  117. private function parseUrl ($text) {
  118. return explode('status/', $text)[1];
  119. }
  120. private function setNodeData($data) {
  121. //Create datetime object for title, media file path and content date field
  122. $nowTime = new \DateTime();
  123. $posted = date('Y-m-d\TH:i:s', strtotime($data->created_at));
  124. $user = \Drupal::currentUser();
  125. $ip = \Drupal::request()->getClientIp();//get user's IP
  126. $links = [];
  127. $terms = $this->processTerms($data);
  128. if (!empty($data->entities->urls)) {
  129. foreach ($data->entities->urls as $url) {
  130. $links[] = $url->display_url;
  131. }
  132. }
  133. //Check for attached media and create a directory for saving
  134. if (isset($data->extended_entities->media)) {
  135. $media = $this->getTweetMedia($data);
  136. }
  137. if ($data->user->profile_image_url_https) {
  138. //TODO get profile image
  139. }
  140. $node = Node::create([
  141. 'type' => 'tweet',
  142. 'title' => $data->user->screen_name . '_' . $nowTime->format('Y.m.d.Hi'),
  143. 'uid' => $user->id(),
  144. 'field_tags' => $terms->tags,
  145. 'field_tweet_url' => $this->parameter,
  146. 'field_twit_id' => $data->id,
  147. 'field_post_date' => [$posted],
  148. 'field_username' => $terms->username,
  149. 'field_users' => $terms->users,
  150. 'field_links' => $links,
  151. 'status' => 1,
  152. ]);
  153. $node->set('body', ['value' => '<div class="created-date"> ' . $data->created_at . '</div>' . $data->full_text, 'format' =>'full_html']);
  154. return $node;
  155. }
  156. private function getTweetMedia($data) {
  157. $media = new \stdClass();
  158. $images = [];
  159. $video = null;
  160. $userImage = null;
  161. if ($data->user->profile_image_url_https) {
  162. $userImage = file_get_contents($data->user->profile_image_url_https);
  163. $file = file_save_data($userImage, 'public://' . substr($data->user->profile_image_url_https, strrpos($data->user->profile_image_url_https, '/') + 1));
  164. $userImage = $file->id();
  165. }
  166. foreach($data->extended_entities->media as $media) {
  167. $image = file_get_contents($media->media_url);
  168. $file = file_save_data($image, 'public://' . substr($media->media_url, strrpos($media->media_url, '/') + 1));
  169. $images[] = $file->id();
  170. }
  171. if(!empty($data->extended_entities->media[0]->video_info->variants)) {
  172. $z = null;
  173. $vidUrl = null;
  174. $bitrate = new \stdClass();
  175. $bitrate->value = null;
  176. $bitrate->index = null;
  177. $variantCount = count($data->extended_entities->media[0]->video_info->variants);
  178. if ($variantCount > 1) {
  179. for ($z = 0; $z < $variantCount; $z++) {
  180. if ($data->extended_entities->media[0]->video_info->variants[$z]->bitrate &&
  181. $data->extended_entities->media[0]->video_info->variants[$z]->content_type === 'video/mp4'
  182. ) {
  183. if ($data->extended_entities->media[0]->video_info->variants[$z]->bitrate > $bitrate->value) {
  184. $bitrate->value = $data->extended_entities->media[0]->video_info->variants[$z]->bitrate;
  185. $bitrate->index = $z;
  186. }
  187. }
  188. }
  189. } else {
  190. $bitrate->index = 0;
  191. }
  192. if ($bitrate->index !== null) {
  193. $data->extended_entities->media[0]->video_info->variants[$bitrate->index]->url;
  194. // $video = system_retrieve_file($vidUrl, null, TRUE);
  195. // $file = File::create([
  196. // 'id' => 'id',
  197. // ])->save();
  198. $video = file_get_contents($data->extended_entities->media[0]->video_info->variants[$bitrate->index]->url);
  199. $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));
  200. $video = $file->id();
  201. }
  202. }
  203. $media->images = $images;
  204. $media->video = $video;
  205. $media->userImage = $userImage;
  206. return $media;
  207. }
  208. private function processTerms($data) {
  209. $terms = new \stdClass();
  210. $terms->tags = [];
  211. $terms->users = [];
  212. $terms->username = -1;
  213. if ($data->user->screen_name) {
  214. $term = \Drupal::entityQuery('taxonomy_term')
  215. ->condition('name', $data->user->screen_name)
  216. ->condition('vid', 'twitter_user')
  217. ->execute();
  218. if (count($term) < 1) {
  219. $term = Term::create(['name' => $data->user->screen_name, 'vid' => 'twitter_user']);
  220. if ($term->save()) {
  221. $terms->username = $term->id();
  222. } else {
  223. \Drupal::logger('StatusTwitter')->warning('Could not save term with name %name', array('%name' => $data->user->screen_name));
  224. }
  225. } else {
  226. $terms->username = array_values($term)[0];
  227. }
  228. }
  229. $term = null;
  230. foreach($data->entities->hashtags as $key => $h) {
  231. $term = \Drupal::entityQuery('taxonomy_term')
  232. ->condition('name', $h->text)
  233. ->condition('vid', 'twitter')
  234. ->execute();
  235. if (count($term) < 1) {
  236. $term = Term::create(['name' => $h->text, 'vid' => 'twitter']);
  237. if ($term->save()) {
  238. $terms->tags[] = $term->id();
  239. } else {
  240. \Drupal::logger('StatusTwitter')->warning('Could not save term with name %name', array('%name' => $h->text));
  241. }
  242. } else {
  243. $terms->tags[] = array_values($term)[0];
  244. }
  245. }
  246. $term = null;
  247. foreach($data->entities->user_mentions as $u) {
  248. $term = \Drupal::entityQuery('taxonomy_term')
  249. ->condition('name', $u->screen_name)
  250. ->condition('vid', 'twitter_user')
  251. ->execute();
  252. if (count($term) < 1) {
  253. $term = Term::create(['name' => $u->screen_name, 'vid' => 'twitter_user']);
  254. if ($term->save()) {
  255. $terms->users[] = $term->id();
  256. } else {
  257. \Drupal::logger('StatusTwitter')->warning('Could not save term with name %name', array('%name' => $u->screen_name));
  258. }
  259. } else {
  260. $terms->users[] = array_values($term)[0];
  261. }
  262. }
  263. return($terms);
  264. }
  265. }