BaseApiController.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. <?php
  2. namespace App\Http\Controllers\Api;
  3. use Illuminate\Http\Request;
  4. use App\Http\Controllers\{
  5. Controller,
  6. AvatarController
  7. };
  8. use Auth, Cache, Storage, URL;
  9. use Carbon\Carbon;
  10. use App\{
  11. Avatar,
  12. Notification,
  13. Media,
  14. Profile,
  15. Status
  16. };
  17. use App\Transformer\Api\{
  18. AccountTransformer,
  19. NotificationTransformer,
  20. MediaTransformer,
  21. StatusTransformer
  22. };
  23. use League\Fractal;
  24. use League\Fractal\Serializer\ArraySerializer;
  25. use League\Fractal\Pagination\IlluminatePaginatorAdapter;
  26. use App\Jobs\AvatarPipeline\AvatarOptimize;
  27. use App\Jobs\ImageOptimizePipeline\ImageOptimize;
  28. use App\Jobs\VideoPipeline\{
  29. VideoOptimize,
  30. VideoPostProcess,
  31. VideoThumbnail
  32. };
  33. class BaseApiController extends Controller
  34. {
  35. protected $fractal;
  36. public function __construct()
  37. {
  38. $this->middleware('auth');
  39. $this->fractal = new Fractal\Manager();
  40. $this->fractal->setSerializer(new ArraySerializer());
  41. }
  42. public function notifications(Request $request)
  43. {
  44. $pid = Auth::user()->profile->id;
  45. $timeago = Carbon::now()->subMonths(6);
  46. $notifications = Notification::whereProfileId($pid)
  47. ->whereDate('created_at', '>', $timeago)
  48. ->latest()
  49. ->simplePaginate(10);
  50. $resource = new Fractal\Resource\Collection($notifications, new NotificationTransformer());
  51. $res = $this->fractal->createData($resource)->toArray();
  52. return response()->json($res);
  53. }
  54. public function accounts(Request $request, $id)
  55. {
  56. $profile = Profile::findOrFail($id);
  57. $resource = new Fractal\Resource\Item($profile, new AccountTransformer());
  58. $res = $this->fractal->createData($resource)->toArray();
  59. return response()->json($res);
  60. }
  61. public function accountFollowers(Request $request, $id)
  62. {
  63. $profile = Profile::findOrFail($id);
  64. $followers = $profile->followers;
  65. $resource = new Fractal\Resource\Collection($followers, new AccountTransformer());
  66. $res = $this->fractal->createData($resource)->toArray();
  67. return response()->json($res);
  68. }
  69. public function accountFollowing(Request $request, $id)
  70. {
  71. $profile = Profile::findOrFail($id);
  72. $following = $profile->following;
  73. $resource = new Fractal\Resource\Collection($following, new AccountTransformer());
  74. $res = $this->fractal->createData($resource)->toArray();
  75. return response()->json($res);
  76. }
  77. public function accountStatuses(Request $request, $id)
  78. {
  79. $this->validate($request, [
  80. 'only_media' => 'nullable',
  81. 'pinned' => 'nullable',
  82. 'exclude_replies' => 'nullable',
  83. 'max_id' => 'nullable|integer|min:1',
  84. 'since_id' => 'nullable|integer|min:1',
  85. 'min_id' => 'nullable|integer|min:1',
  86. 'limit' => 'nullable|integer|min:1|max:24'
  87. ]);
  88. $limit = $request->limit ?? 20;
  89. $max_id = $request->max_id ?? false;
  90. $min_id = $request->min_id ?? false;
  91. $since_id = $request->since_id ?? false;
  92. $only_media = $request->only_media ?? false;
  93. $user = Auth::user();
  94. $account = Profile::findOrFail($id);
  95. $statuses = $account->statuses()->getQuery();
  96. if($only_media == true) {
  97. $statuses = $statuses
  98. ->whereHas('media')
  99. ->whereNull('in_reply_to_id')
  100. ->whereNull('reblog_of_id');
  101. }
  102. if($id == $account->id && !$max_id && !$min_id && !$since_id) {
  103. $statuses = $statuses->orderBy('id', 'desc')
  104. ->paginate($limit);
  105. } else if($since_id) {
  106. $statuses = $statuses->where('id', '>', $since_id)
  107. ->orderBy('id', 'DESC')
  108. ->paginate($limit);
  109. } else if($min_id) {
  110. $statuses = $statuses->where('id', '>', $min_id)
  111. ->orderBy('id', 'ASC')
  112. ->paginate($limit);
  113. } else if($max_id) {
  114. $statuses = $statuses->where('id', '<', $max_id)
  115. ->orderBy('id', 'DESC')
  116. ->paginate($limit);
  117. } else {
  118. $statuses = $statuses->whereVisibility('public')->orderBy('id', 'desc')->paginate($limit);
  119. }
  120. $resource = new Fractal\Resource\Collection($statuses, new StatusTransformer());
  121. $res = $this->fractal->createData($resource)->toArray();
  122. return response()->json($res);
  123. }
  124. public function followSuggestions(Request $request)
  125. {
  126. $followers = Auth::user()->profile->recommendFollowers();
  127. $resource = new Fractal\Resource\Collection($followers, new AccountTransformer());
  128. $res = $this->fractal->createData($resource)->toArray();
  129. return response()->json($res);
  130. }
  131. public function avatarUpdate(Request $request)
  132. {
  133. $this->validate($request, [
  134. 'upload' => 'required|mimes:jpeg,png,gif|max:'.config('pixelfed.max_avatar_size'),
  135. ]);
  136. try {
  137. $user = Auth::user();
  138. $profile = $user->profile;
  139. $file = $request->file('upload');
  140. $path = (new AvatarController())->getPath($user, $file);
  141. $dir = $path['root'];
  142. $name = $path['name'];
  143. $public = $path['storage'];
  144. $currentAvatar = storage_path('app/'.$profile->avatar->media_path);
  145. $loc = $request->file('upload')->storeAs($public, $name);
  146. $avatar = Avatar::whereProfileId($profile->id)->firstOrFail();
  147. $opath = $avatar->media_path;
  148. $avatar->media_path = "$public/$name";
  149. $avatar->thumb_path = null;
  150. $avatar->change_count = ++$avatar->change_count;
  151. $avatar->last_processed_at = null;
  152. $avatar->save();
  153. Cache::forget("avatar:{$profile->id}");
  154. AvatarOptimize::dispatch($user->profile, $currentAvatar);
  155. } catch (Exception $e) {
  156. }
  157. return response()->json([
  158. 'code' => 200,
  159. 'msg' => 'Avatar successfully updated',
  160. ]);
  161. }
  162. public function showTempMedia(Request $request, int $profileId, $mediaId)
  163. {
  164. if (!$request->hasValidSignature()) {
  165. abort(401);
  166. }
  167. $profile = Auth::user()->profile;
  168. if($profile->id !== $profileId) {
  169. abort(403);
  170. }
  171. $media = Media::whereProfileId($profile->id)->findOrFail($mediaId);
  172. $path = storage_path('app/'.$media->media_path);
  173. return response()->file($path);
  174. }
  175. public function uploadMedia(Request $request)
  176. {
  177. $this->validate($request, [
  178. 'file.*' => function() {
  179. return [
  180. 'required',
  181. 'mimes:' . config('pixelfed.media_types'),
  182. 'max:' . config('pixelfed.max_photo_size'),
  183. ];
  184. },
  185. 'filter_name' => 'nullable|string|max:24',
  186. 'filter_class' => 'nullable|alpha_dash|max:24'
  187. ]);
  188. $user = Auth::user();
  189. $profile = $user->profile;
  190. if(config('pixelfed.enforce_account_limit') == true) {
  191. $size = Media::whereUserId($user->id)->sum('size') / 1000;
  192. $limit = (int) config('pixelfed.max_account_size');
  193. if ($size >= $limit) {
  194. abort(403, 'Account size limit reached.');
  195. }
  196. }
  197. $recent = Media::whereProfileId($profile->id)->whereNull('status_id')->count();
  198. if($recent > 50) {
  199. abort(403);
  200. }
  201. $monthHash = hash('sha1', date('Y').date('m'));
  202. $userHash = hash('sha1', $user->id.(string) $user->created_at);
  203. $photo = $request->file('file');
  204. $mimes = explode(',', config('pixelfed.media_types'));
  205. if(in_array($photo->getMimeType(), $mimes) == false) {
  206. return;
  207. }
  208. $storagePath = "public/m/{$monthHash}/{$userHash}";
  209. $path = $photo->store($storagePath);
  210. $hash = \hash_file('sha256', $photo);
  211. $media = new Media();
  212. $media->status_id = null;
  213. $media->profile_id = $profile->id;
  214. $media->user_id = $user->id;
  215. $media->media_path = $path;
  216. $media->original_sha256 = $hash;
  217. $media->size = $photo->getSize();
  218. $media->mime = $photo->getMimeType();
  219. $media->filter_class = $request->input('filter_class');
  220. $media->filter_name = $request->input('filter_name');
  221. $media->save();
  222. $url = URL::temporarySignedRoute(
  223. 'temp-media', now()->addHours(1), ['profileId' => $profile->id, 'mediaId' => $media->id]
  224. );
  225. switch ($media->mime) {
  226. case 'image/jpeg':
  227. case 'image/png':
  228. ImageOptimize::dispatch($media);
  229. break;
  230. case 'video/mp4':
  231. VideoThumbnail::dispatch($media);
  232. break;
  233. default:
  234. break;
  235. }
  236. $resource = new Fractal\Resource\Item($media, new MediaTransformer());
  237. $res = $this->fractal->createData($resource)->toArray();
  238. $res['preview_url'] = $url;
  239. $res['url'] = $url;
  240. return response()->json($res);
  241. }
  242. public function deleteMedia(Request $request)
  243. {
  244. $this->validate($request, [
  245. 'id' => 'required|integer|min:1|exists:media,id'
  246. ]);
  247. $media = Media::whereNull('status_id')
  248. ->whereUserId(Auth::id())
  249. ->findOrFail($request->input('id'));
  250. Storage::delete($media->media_path);
  251. Storage::delete($media->thumbnail_path);
  252. $media->forceDelete();
  253. return response()->json([
  254. 'msg' => 'Successfully deleted',
  255. 'code' => 200
  256. ]);
  257. }
  258. public function verifyCredentials(Request $request)
  259. {
  260. $id = Auth::id();
  261. $res = Cache::remember('user:account:id:'.$id, now()->addHours(6), function() use($id) {
  262. $profile = Profile::whereNull('status')->whereUserId($id)->firstOrFail();
  263. $resource = new Fractal\Resource\Item($profile, new AccountTransformer());
  264. return $this->fractal->createData($resource)->toArray();
  265. });
  266. return response()->json($res);
  267. }
  268. }