MediaStorageService.php 9.8 KB

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