You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

102 lines
3.0 KiB

  1. <?php
  2. namespace App;
  3. use Illuminate\Database\Eloquent\Model;
  4. use Respect\Validation\Validator;
  5. use Movim\EmbedLight;
  6. use Embed\Embed;
  7. use Embed\Http\Crawler;
  8. use Embed\Http\CurlClient;
  9. use Movim\EmbedImagesExtractor;
  10. class Url extends Model
  11. {
  12. public function resolve($url)
  13. {
  14. if (Validator::url()->validate($url)) {
  15. $hash = hash('sha256', $url);
  16. $cached = \App\Url::where('hash', $hash)->first();
  17. if ($cached) {
  18. $this->id = $cached->id;
  19. $this->maybeResolveMessageFile($cached->cache);
  20. return $cached->cache;
  21. } else {
  22. $cached = new \App\Url;
  23. $cached->hash = $hash;
  24. }
  25. $cached->cache = $url;
  26. $cached->save();
  27. $this->id = $cached->id;
  28. $this->maybeResolveMessageFile($cached->cache);
  29. return $cached->cache;
  30. }
  31. }
  32. public function maybeResolveMessageFile($cache)
  33. {
  34. if ($cache->title == $cache->url
  35. && ($cache->type == 'image' || $cache->type == 'video')
  36. ) {
  37. $name = '';
  38. $path = parse_url($cache->url, PHP_URL_PATH);
  39. if ($path) {
  40. $name = basename($path);
  41. }
  42. $file = new MessageFile;
  43. $file->name = !empty($name) ? $name : $cache->url;
  44. $file->type = $cache->contentType;
  45. $file->size = (!empty($cache->images[0]) && array_key_exists('size', $cache->images[0]))
  46. ? $cache->images[0]['size']
  47. : 20000;
  48. $file->uri = $cache->url;
  49. $this->file = $file;
  50. }
  51. }
  52. public function getCacheAttribute()
  53. {
  54. return unserialize(base64_decode($this->attributes['cache']));
  55. }
  56. public function setCacheAttribute($url)
  57. {
  58. $client = new CurlClient;
  59. $client->setSettings([
  60. 'max_redirs' => 3, // see CURLOPT_MAXREDIRS
  61. 'connect_timeout' => 5, // see CURLOPT_CONNECTTIMEOUT
  62. 'timeout' => 5, // see CURLOPT_TIMEOUT
  63. 'ssl_verify_host' => 2, // see CURLOPT_SSL_VERIFYHOST
  64. 'ssl_verify_peer' => 1, // see CURLOPT_SSL_VERIFYPEER
  65. 'follow_location' => true, // see CURLOPT_FOLLOWLOCATION
  66. 'user_agent' => DEFAULT_HTTP_USER_AGENT,
  67. ]);
  68. try {
  69. $embed = new Embed(new Crawler($client));
  70. $configuration = Configuration::get();
  71. if (!empty($configuration->twittertoken)) {
  72. $embed->setSettings([
  73. 'twitter:token' => $configuration->twittertoken
  74. ]);
  75. }
  76. $embed->getExtractorFactory()->addDetector('images', EmbedImagesExtractor::class);
  77. $info = $embed->get($url);
  78. $embed = new EmbedLight($info);
  79. $this->attributes['cache'] = base64_encode(serialize($embed));
  80. } catch (\Exception $e) {
  81. error_log($e->getMessage());
  82. }
  83. }
  84. }