StatusTwitter.php 8.4 KB

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