1
0

BaseApiController.php 12 KB

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