MediaStorageService.php 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. <?php
  2. namespace App\Services;
  3. use App\Util\ActivityPub\Helpers;
  4. use Illuminate\Http\File;
  5. use Illuminate\Support\Facades\Cache;
  6. use Illuminate\Support\Facades\Redis;
  7. use Illuminate\Support\Facades\Storage;
  8. use Illuminate\Support\Str;
  9. use App\Media;
  10. use App\Profile;
  11. use App\User;
  12. use GuzzleHttp\Client;
  13. use App\Services\AccountService;
  14. use App\Http\Controllers\AvatarController;
  15. use GuzzleHttp\Exception\RequestException;
  16. use App\Jobs\MediaPipeline\MediaDeletePipeline;
  17. use Illuminate\Support\Arr;
  18. use App\Jobs\AvatarPipeline\AvatarStorageCleanup;
  19. class MediaStorageService {
  20. public static function store(Media $media)
  21. {
  22. if(config_cache('pixelfed.cloud_storage') == true) {
  23. (new self())->cloudStore($media);
  24. }
  25. return;
  26. }
  27. public static function avatar($avatar, $local = false, $skipRecentCheck = false)
  28. {
  29. return (new self())->fetchAvatar($avatar, $local, $skipRecentCheck);
  30. }
  31. public static function head($url)
  32. {
  33. $c = new Client();
  34. try {
  35. $r = $c->request('HEAD', $url);
  36. } catch (RequestException $e) {
  37. return false;
  38. }
  39. $h = Arr::mapWithKeys($r->getHeaders(), function($item, $key) {
  40. return [strtolower($key) => last($item)];
  41. });
  42. if(!isset($h['content-length'], $h['content-type'])) {
  43. return false;
  44. }
  45. $len = (int) $h['content-length'];
  46. $mime = $h['content-type'];
  47. if($len < 10 || $len > ((config_cache('pixelfed.max_photo_size') * 1000))) {
  48. return false;
  49. }
  50. return [
  51. 'length' => $len,
  52. 'mime' => $mime
  53. ];
  54. }
  55. protected function cloudStore($media)
  56. {
  57. if($media->remote_media == true) {
  58. if(config('media.storage.remote.cloud')) {
  59. (new self())->remoteToCloud($media);
  60. }
  61. } else {
  62. (new self())->localToCloud($media);
  63. }
  64. }
  65. protected function localToCloud($media)
  66. {
  67. $path = storage_path('app/'.$media->media_path);
  68. $thumb = storage_path('app/'.$media->thumbnail_path);
  69. $p = explode('/', $media->media_path);
  70. $name = array_pop($p);
  71. $pt = explode('/', $media->thumbnail_path);
  72. $thumbname = array_pop($pt);
  73. $storagePath = implode('/', $p);
  74. $url = ResilientMediaStorageService::store($storagePath, $path, $name);
  75. if($thumb) {
  76. $thumbUrl = ResilientMediaStorageService::store($storagePath, $thumb, $thumbname);
  77. $media->thumbnail_url = $thumbUrl;
  78. }
  79. $media->cdn_url = $url;
  80. $media->optimized_url = $url;
  81. $media->replicated_at = now();
  82. $media->save();
  83. if($media->status_id) {
  84. Cache::forget('status:transformer:media:attachments:' . $media->status_id);
  85. MediaService::del($media->status_id);
  86. StatusService::del($media->status_id, false);
  87. }
  88. }
  89. protected function remoteToCloud($media)
  90. {
  91. $url = $media->remote_url;
  92. if(!Helpers::validateUrl($url)) {
  93. return;
  94. }
  95. $head = $this->head($media->remote_url);
  96. if(!$head) {
  97. return;
  98. }
  99. $mimes = [
  100. 'image/jpeg',
  101. 'image/png',
  102. 'video/mp4'
  103. ];
  104. $mime = $head['mime'];
  105. $max_size = (int) config_cache('pixelfed.max_photo_size') * 1000;
  106. $media->size = $head['length'];
  107. $media->remote_media = true;
  108. $media->save();
  109. if(!in_array($mime, $mimes)) {
  110. return;
  111. }
  112. if($head['length'] >= $max_size) {
  113. return;
  114. }
  115. switch ($mime) {
  116. case 'image/png':
  117. $ext = '.png';
  118. break;
  119. case 'image/gif':
  120. $ext = '.gif';
  121. break;
  122. case 'image/jpeg':
  123. $ext = '.jpg';
  124. break;
  125. case 'video/mp4':
  126. $ext = '.mp4';
  127. break;
  128. }
  129. $base = MediaPathService::get($media->profile);
  130. $path = Str::random(40) . $ext;
  131. $tmpBase = storage_path('app/remcache/');
  132. $tmpPath = $media->profile_id . '-' . $path;
  133. $tmpName = $tmpBase . $tmpPath;
  134. $data = file_get_contents($url, false, null, 0, $head['length']);
  135. file_put_contents($tmpName, $data);
  136. $hash = hash_file('sha256', $tmpName);
  137. $disk = Storage::disk(config('filesystems.cloud'));
  138. $file = $disk->putFileAs($base, new File($tmpName), $path, 'public');
  139. $permalink = $disk->url($file);
  140. $media->media_path = $file;
  141. $media->cdn_url = $permalink;
  142. $media->original_sha256 = $hash;
  143. $media->replicated_at = now();
  144. $media->save();
  145. if($media->status_id) {
  146. Cache::forget('status:transformer:media:attachments:' . $media->status_id);
  147. }
  148. unlink($tmpName);
  149. }
  150. protected function fetchAvatar($avatar, $local = false, $skipRecentCheck = false)
  151. {
  152. $queue = random_int(1, 15) > 5 ? 'mmo' : 'low';
  153. $url = $avatar->remote_url;
  154. $driver = $local ? 'local' : config('filesystems.cloud');
  155. if(empty($url) || Helpers::validateUrl($url) == false) {
  156. return;
  157. }
  158. $head = $this->head($url);
  159. if($head == false) {
  160. return;
  161. }
  162. $mimes = [
  163. 'application/octet-stream',
  164. 'image/jpeg',
  165. 'image/png',
  166. ];
  167. $mime = $head['mime'];
  168. $max_size = (int) config('pixelfed.max_avatar_size') * 1000;
  169. if(!$skipRecentCheck) {
  170. if($avatar->last_fetched_at && $avatar->last_fetched_at->gt(now()->subMonths(3))) {
  171. return;
  172. }
  173. }
  174. Cache::forget('avatar:' . $avatar->profile_id);
  175. AccountService::del($avatar->profile_id);
  176. // handle pleroma edge case
  177. if(Str::endsWith($mime, '; charset=utf-8')) {
  178. $mime = str_replace('; charset=utf-8', '', $mime);
  179. }
  180. if(!in_array($mime, $mimes)) {
  181. return;
  182. }
  183. if($head['length'] >= $max_size) {
  184. return;
  185. }
  186. $base = ($local ? 'public/cache/' : 'cache/') . 'avatars/' . $avatar->profile_id;
  187. $ext = $head['mime'] == 'image/jpeg' ? 'jpg' : 'png';
  188. $path = 'avatar_' . strtolower(Str::random(random_int(3,6))) . '.' . $ext;
  189. $tmpBase = storage_path('app/remcache/');
  190. $tmpPath = 'avatar_' . $avatar->profile_id . '-' . $path;
  191. $tmpName = $tmpBase . $tmpPath;
  192. $data = @file_get_contents($url, false, null, 0, $head['length']);
  193. if(!$data) {
  194. return;
  195. }
  196. file_put_contents($tmpName, $data);
  197. $mimeCheck = Storage::mimeType('remcache/' . $tmpPath);
  198. if(!$mimeCheck || !in_array($mimeCheck, ['image/png', 'image/jpeg'])) {
  199. $avatar->last_fetched_at = now();
  200. $avatar->save();
  201. unlink($tmpName);
  202. return;
  203. }
  204. $disk = Storage::disk($driver);
  205. $file = $disk->putFileAs($base, new File($tmpName), $path, 'public');
  206. $permalink = $disk->url($file);
  207. $avatar->media_path = $base . '/' . $path;
  208. $avatar->is_remote = true;
  209. $avatar->cdn_url = $local ? config('app.url') . $permalink : $permalink;
  210. $avatar->size = $head['length'];
  211. $avatar->change_count = $avatar->change_count + 1;
  212. $avatar->last_fetched_at = now();
  213. $avatar->save();
  214. Cache::forget('avatar:' . $avatar->profile_id);
  215. AccountService::del($avatar->profile_id);
  216. AvatarStorageCleanup::dispatch($avatar)->onQueue($queue)->delay(now()->addMinutes(random_int(3, 15)));
  217. unlink($tmpName);
  218. }
  219. public static function delete(Media $media, $confirm = false)
  220. {
  221. if(!$confirm) {
  222. return;
  223. }
  224. MediaDeletePipeline::dispatch($media)->onQueue('mmo');
  225. }
  226. }