BaseApiController.php 11 KB

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