BaseApiController.php 10 KB

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