ApiV1Controller.php 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479
  1. <?php
  2. namespace App\Http\Controllers\Api;
  3. use Illuminate\Http\Request;
  4. use App\Http\Controllers\Controller;
  5. use Illuminate\Support\Str;
  6. use App\Util\ActivityPub\Helpers;
  7. use App\Util\Media\Filter;
  8. use Laravel\Passport\Passport;
  9. use Auth, Cache, DB, URL;
  10. use App\{
  11. Avatar,
  12. Bookmark,
  13. DirectMessage,
  14. Follower,
  15. FollowRequest,
  16. Hashtag,
  17. Like,
  18. Media,
  19. Notification,
  20. Profile,
  21. Status,
  22. StatusHashtag,
  23. User,
  24. UserSetting,
  25. UserFilter,
  26. };
  27. use League\Fractal;
  28. use App\Transformer\Api\Mastodon\v1\{
  29. AccountTransformer,
  30. MediaTransformer,
  31. NotificationTransformer,
  32. StatusTransformer,
  33. };
  34. use App\Transformer\Api\{
  35. RelationshipTransformer,
  36. };
  37. use App\Http\Controllers\FollowerController;
  38. use League\Fractal\Serializer\ArraySerializer;
  39. use League\Fractal\Pagination\IlluminatePaginatorAdapter;
  40. use App\Http\Controllers\StatusController;
  41. use App\Jobs\AvatarPipeline\AvatarOptimize;
  42. use App\Jobs\LikePipeline\LikePipeline;
  43. use App\Jobs\SharePipeline\SharePipeline;
  44. use App\Jobs\StatusPipeline\NewStatusPipeline;
  45. use App\Jobs\StatusPipeline\StatusDelete;
  46. use App\Jobs\FollowPipeline\FollowPipeline;
  47. use App\Jobs\ImageOptimizePipeline\ImageOptimize;
  48. use App\Jobs\VideoPipeline\{
  49. VideoOptimize,
  50. VideoPostProcess,
  51. VideoThumbnail
  52. };
  53. use App\Services\{
  54. AccountService,
  55. LikeService,
  56. InstanceService,
  57. NotificationService,
  58. MediaPathService,
  59. PublicTimelineService,
  60. ProfileService,
  61. RelationshipService,
  62. SearchApiV2Service,
  63. StatusService,
  64. MediaBlocklistService,
  65. SnowflakeService,
  66. UserFilterService
  67. };
  68. use App\Util\Lexer\Autolink;
  69. use App\Util\Localization\Localization;
  70. use App\Util\Media\License;
  71. use App\Jobs\MediaPipeline\MediaSyncLicensePipeline;
  72. class ApiV1Controller extends Controller
  73. {
  74. protected $fractal;
  75. public function __construct()
  76. {
  77. $this->fractal = new Fractal\Manager();
  78. $this->fractal->setSerializer(new ArraySerializer());
  79. }
  80. public function apps(Request $request)
  81. {
  82. abort_if(!config_cache('pixelfed.oauth_enabled'), 404);
  83. $this->validate($request, [
  84. 'client_name' => 'required',
  85. 'redirect_uris' => 'required',
  86. 'scopes' => 'nullable',
  87. 'website' => 'nullable'
  88. ]);
  89. $uris = implode(',', explode('\n', $request->redirect_uris));
  90. $client = Passport::client()->forceFill([
  91. 'user_id' => null,
  92. 'name' => e($request->client_name),
  93. 'secret' => Str::random(40),
  94. 'redirect' => $uris,
  95. 'personal_access_client' => false,
  96. 'password_client' => false,
  97. 'revoked' => false,
  98. ]);
  99. $client->save();
  100. $res = [
  101. 'id' => $client->id,
  102. 'name' => $client->name,
  103. 'website' => null,
  104. 'redirect_uri' => $client->redirect,
  105. 'client_id' => $client->id,
  106. 'client_secret' => $client->secret,
  107. 'vapid_key' => null
  108. ];
  109. return response()->json($res, 200, [
  110. 'Access-Control-Allow-Origin' => '*'
  111. ]);
  112. }
  113. /**
  114. * GET /api/v1/accounts/verify_credentials
  115. *
  116. *
  117. * @return \App\Transformer\Api\AccountTransformer
  118. */
  119. public function verifyCredentials(Request $request)
  120. {
  121. abort_if(!$request->user(), 403);
  122. abort_if($request->user()->status != null, 403);
  123. $id = $request->user()->profile_id;
  124. $res = ProfileService::get($id);
  125. $res['source'] = [
  126. 'privacy' => $res['locked'] ? 'private' : 'public',
  127. 'sensitive' => false,
  128. 'language' => null,
  129. 'note' => '',
  130. 'fields' => []
  131. ];
  132. return response()->json($res);
  133. }
  134. /**
  135. * GET /api/v1/accounts/{id}
  136. *
  137. * @param integer $id
  138. *
  139. * @return \App\Transformer\Api\AccountTransformer
  140. */
  141. public function accountById(Request $request, $id)
  142. {
  143. $profile = Profile::whereNull('status')->findOrFail($id);
  144. $resource = new Fractal\Resource\Item($profile, new AccountTransformer());
  145. $res = $this->fractal->createData($resource)->toArray();
  146. return response()->json($res);
  147. }
  148. /**
  149. * PATCH /api/v1/accounts/update_credentials
  150. *
  151. * @return \App\Transformer\Api\AccountTransformer
  152. */
  153. public function accountUpdateCredentials(Request $request)
  154. {
  155. abort_if(!$request->user(), 403);
  156. $this->validate($request, [
  157. 'avatar' => 'sometimes|mimetypes:image/jpeg,image/png',
  158. 'display_name' => 'nullable|string',
  159. 'note' => 'nullable|string',
  160. 'locked' => 'nullable',
  161. 'website' => 'nullable',
  162. // 'source.privacy' => 'nullable|in:unlisted,public,private',
  163. // 'source.sensitive' => 'nullable|boolean'
  164. ]);
  165. $user = $request->user();
  166. $profile = $user->profile;
  167. $settings = $user->settings;
  168. $changes = false;
  169. $other = array_merge(AccountService::defaultSettings()['other'], $settings->other ?? []);
  170. $syncLicenses = false;
  171. $licenseChanged = false;
  172. $composeSettings = array_merge(AccountService::defaultSettings()['compose_settings'], $settings->compose_settings ?? []);
  173. // return $request->input('locked');
  174. if($request->has('avatar')) {
  175. $av = Avatar::whereProfileId($profile->id)->first();
  176. if($av) {
  177. $currentAvatar = storage_path('app/'.$av->media_path);
  178. $file = $request->file('avatar');
  179. $path = "public/avatars/{$profile->id}";
  180. $name = strtolower(str_random(6)). '.' . $file->guessExtension();
  181. $request->file('avatar')->storeAs($path, $name);
  182. $av->media_path = "{$path}/{$name}";
  183. $av->save();
  184. Cache::forget("avatar:{$profile->id}");
  185. Cache::forget('user:account:id:'.$user->id);
  186. AvatarOptimize::dispatch($user->profile, $currentAvatar);
  187. }
  188. $changes = true;
  189. }
  190. if($request->has('source[language]')) {
  191. $lang = $request->input('source[language]');
  192. if(in_array($lang, Localization::languages())) {
  193. $user->language = $lang;
  194. $changes = true;
  195. $other['language'] = $lang;
  196. }
  197. }
  198. if($request->has('website')) {
  199. $website = $request->input('website');
  200. if($website != $profile->website) {
  201. if($website) {
  202. if(!strpos($website, '.')) {
  203. $website = null;
  204. }
  205. if($website && !strpos($website, '://')) {
  206. $website = 'https://' . $website;
  207. }
  208. $host = parse_url($website, PHP_URL_HOST);
  209. $bannedInstances = InstanceService::getBannedDomains();
  210. if(in_array($host, $bannedInstances)) {
  211. $website = null;
  212. }
  213. }
  214. $profile->website = $website ? $website : null;
  215. $changes = true;
  216. }
  217. }
  218. if($request->has('display_name')) {
  219. $displayName = $request->input('display_name');
  220. if($displayName !== $user->name) {
  221. $user->name = $displayName;
  222. $profile->name = $displayName;
  223. $changes = true;
  224. }
  225. }
  226. if($request->has('note')) {
  227. $note = $request->input('note');
  228. if($note !== strip_tags($profile->bio)) {
  229. $profile->bio = Autolink::create()->autolink(strip_tags($note));
  230. $changes = true;
  231. }
  232. }
  233. if($request->has('locked')) {
  234. $locked = $request->input('locked') == 'true';
  235. if($profile->is_private != $locked) {
  236. $profile->is_private = $locked;
  237. $changes = true;
  238. }
  239. }
  240. if($request->has('reduce_motion')) {
  241. $reduced = $request->input('reduce_motion');
  242. if($settings->reduce_motion != $reduced) {
  243. $settings->reduce_motion = $reduced;
  244. $changes = true;
  245. }
  246. }
  247. if($request->has('high_contrast_mode')) {
  248. $contrast = $request->input('high_contrast_mode');
  249. if($settings->high_contrast_mode != $contrast) {
  250. $settings->high_contrast_mode = $contrast;
  251. $changes = true;
  252. }
  253. }
  254. if($request->has('video_autoplay')) {
  255. $autoplay = $request->input('video_autoplay');
  256. if($settings->video_autoplay != $autoplay) {
  257. $settings->video_autoplay = $autoplay;
  258. $changes = true;
  259. }
  260. }
  261. if($request->has('license')) {
  262. $license = $request->input('license');
  263. abort_if(!in_array($license, License::keys()), 422, 'Invalid media license id');
  264. $syncLicenses = $request->input('sync_licenses') == true;
  265. abort_if($syncLicenses && Cache::get('pf:settings:mls_recently:'.$user->id) == 2, 422, 'You can only sync licenses twice per 24 hours');
  266. if($composeSettings['default_license'] != $license) {
  267. $composeSettings['default_license'] = $license;
  268. $licenseChanged = true;
  269. $changes = true;
  270. }
  271. }
  272. if($request->has('media_descriptions')) {
  273. $md = $request->input('media_descriptions') == true;
  274. if($composeSettings['media_descriptions'] != $md) {
  275. $composeSettings['media_descriptions'] = $md;
  276. $changes = true;
  277. }
  278. }
  279. if($request->has('crawlable')) {
  280. $crawlable = $request->input('crawlable');
  281. if($settings->crawlable != $crawlable) {
  282. $settings->crawlable = $crawlable;
  283. $changes = true;
  284. }
  285. }
  286. if($request->has('show_profile_follower_count')) {
  287. $show_profile_follower_count = $request->input('show_profile_follower_count');
  288. if($settings->show_profile_follower_count != $show_profile_follower_count) {
  289. $settings->show_profile_follower_count = $show_profile_follower_count;
  290. $changes = true;
  291. }
  292. }
  293. if($request->has('show_profile_following_count')) {
  294. $show_profile_following_count = $request->input('show_profile_following_count');
  295. if($settings->show_profile_following_count != $show_profile_following_count) {
  296. $settings->show_profile_following_count = $show_profile_following_count;
  297. $changes = true;
  298. }
  299. }
  300. if($request->has('public_dm')) {
  301. $public_dm = $request->input('public_dm');
  302. if($settings->public_dm != $public_dm) {
  303. $settings->public_dm = $public_dm;
  304. $changes = true;
  305. }
  306. }
  307. if($request->has('source[privacy]')) {
  308. $scope = $request->input('source[privacy]');
  309. if(in_array($scope, ['public', 'private', 'unlisted'])) {
  310. if($composeSettings['default_scope'] != $scope) {
  311. $composeSettings['default_scope'] = $profile->is_private ? 'private' : $scope;
  312. $changes = true;
  313. }
  314. }
  315. }
  316. if($request->has('disable_embeds')) {
  317. $disabledEmbeds = $request->input('disable_embeds');
  318. if($other['disable_embeds'] != $disabledEmbeds) {
  319. $other['disable_embeds'] = $disabledEmbeds;
  320. $changes = true;
  321. }
  322. }
  323. if($changes) {
  324. $settings->other = $other;
  325. $settings->compose_settings = $composeSettings;
  326. $settings->save();
  327. $user->save();
  328. $profile->save();
  329. Cache::forget('profile:settings:' . $profile->id);
  330. Cache::forget('user:account:id:' . $profile->user_id);
  331. Cache::forget('profile:follower_count:' . $profile->id);
  332. Cache::forget('profile:following_count:' . $profile->id);
  333. Cache::forget('profile:embed:' . $profile->id);
  334. Cache::forget('profile:compose:settings:' . $user->id);
  335. Cache::forget('profile:view:'.$user->username);
  336. AccountService::del($user->profile_id);
  337. }
  338. if($syncLicenses && $licenseChanged) {
  339. $key = 'pf:settings:mls_recently:'.$user->id;
  340. $val = Cache::has($key) ? 2 : 1;
  341. Cache::put($key, $val, 86400);
  342. MediaSyncLicensePipeline::dispatch($user->id, $request->input('license'));
  343. }
  344. $res = AccountService::get($user->profile_id);
  345. $res['bio'] = strip_tags($res['note']);
  346. $res = array_merge($res, $other);
  347. return response()->json($res);
  348. }
  349. /**
  350. * GET /api/v1/accounts/{id}/followers
  351. *
  352. * @param integer $id
  353. *
  354. * @return \App\Transformer\Api\AccountTransformer
  355. */
  356. public function accountFollowersById(Request $request, $id)
  357. {
  358. abort_if(!$request->user(), 403);
  359. $user = $request->user();
  360. $profile = Profile::whereNull('status')->findOrFail($id);
  361. $limit = $request->input('limit') ?? 40;
  362. if($profile->domain) {
  363. $res = [];
  364. } else {
  365. if($profile->id == $user->profile_id) {
  366. $followers = $profile->followers()->paginate($limit);
  367. $resource = new Fractal\Resource\Collection($followers, new AccountTransformer());
  368. $res = $this->fractal->createData($resource)->toArray();
  369. } else {
  370. if($profile->is_private) {
  371. abort_if(!$profile->followedBy($user->profile), 403);
  372. }
  373. $settings = $profile->user->settings;
  374. if( in_array($user->profile_id, $profile->blockedIds()->toArray()) ||
  375. $settings->show_profile_followers == false
  376. ) {
  377. $res = [];
  378. } else {
  379. $followers = $profile->followers()->paginate($limit);
  380. $resource = new Fractal\Resource\Collection($followers, new AccountTransformer());
  381. $res = $this->fractal->createData($resource)->toArray();
  382. }
  383. }
  384. }
  385. return response()->json($res);
  386. }
  387. /**
  388. * GET /api/v1/accounts/{id}/following
  389. *
  390. * @param integer $id
  391. *
  392. * @return \App\Transformer\Api\AccountTransformer
  393. */
  394. public function accountFollowingById(Request $request, $id)
  395. {
  396. abort_if(!$request->user(), 403);
  397. $user = $request->user();
  398. $profile = Profile::whereNull('status')->findOrFail($id);
  399. $limit = $request->input('limit') ?? 40;
  400. if($profile->domain) {
  401. $res = [];
  402. } else {
  403. if($profile->id == $user->profile_id) {
  404. $following = $profile->following()->paginate($limit);
  405. $resource = new Fractal\Resource\Collection($following, new AccountTransformer());
  406. $res = $this->fractal->createData($resource)->toArray();
  407. } else {
  408. if($profile->is_private) {
  409. abort_if(!$profile->followedBy($user->profile), 403);
  410. }
  411. $settings = $profile->user->settings;
  412. if( in_array($user->profile_id, $profile->blockedIds()->toArray()) ||
  413. $settings->show_profile_following == false
  414. ) {
  415. $res = [];
  416. } else {
  417. $following = $profile->following()->paginate($limit);
  418. $resource = new Fractal\Resource\Collection($following, new AccountTransformer());
  419. $res = $this->fractal->createData($resource)->toArray();
  420. }
  421. }
  422. }
  423. return response()->json($res);
  424. }
  425. /**
  426. * GET /api/v1/accounts/{id}/statuses
  427. *
  428. * @param integer $id
  429. *
  430. * @return \App\Transformer\Api\StatusTransformer
  431. */
  432. public function accountStatusesById(Request $request, $id)
  433. {
  434. abort_if(!$request->user(), 403);
  435. $user = $request->user();
  436. $this->validate($request, [
  437. 'only_media' => 'nullable',
  438. 'media_type' => 'sometimes|string|in:photo,video',
  439. 'pinned' => 'nullable',
  440. 'exclude_replies' => 'nullable',
  441. 'max_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  442. 'since_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  443. 'min_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  444. 'limit' => 'nullable|integer|min:1|max:80'
  445. ]);
  446. $profile = AccountService::get($id);
  447. abort_if(!$profile, 404);
  448. $limit = $request->limit ?? 20;
  449. $max_id = $request->max_id;
  450. $min_id = $request->min_id;
  451. $pid = $request->user()->profile_id;
  452. $scope = $request->only_media == true ?
  453. ['photo', 'photo:album', 'video', 'video:album'] :
  454. ['photo', 'photo:album', 'video', 'video:album', 'share', 'reply'];
  455. if($request->only_media && $request->has('media_type')) {
  456. $mt = $request->input('media_type');
  457. if($mt == 'video') {
  458. $scope = ['video', 'video:album'];
  459. }
  460. }
  461. if($pid == $profile['id']) {
  462. $visibility = ['public', 'unlisted', 'private'];
  463. } else if($profile['locked']) {
  464. $following = Cache::remember('profile:following:'.$pid, now()->addMinutes(1440), function() use($pid) {
  465. $following = Follower::whereProfileId($pid)->pluck('following_id');
  466. return $following->push($pid)->toArray();
  467. });
  468. $visibility = true == in_array($profile['id'], $following) ? ['public', 'unlisted', 'private'] : [];
  469. } else {
  470. $following = Cache::remember('profile:following:'.$pid, now()->addMinutes(1440), function() use($pid) {
  471. $following = Follower::whereProfileId($pid)->pluck('following_id');
  472. return $following->push($pid)->toArray();
  473. });
  474. $visibility = true == in_array($profile['id'], $following) ? ['public', 'unlisted', 'private'] : ['public', 'unlisted'];
  475. }
  476. $dir = $min_id ? '>' : '<';
  477. $id = $min_id ?? $max_id;
  478. $res = Status::whereProfileId($profile['id'])
  479. ->whereNull('in_reply_to_id')
  480. ->whereNull('reblog_of_id')
  481. ->whereIn('type', $scope)
  482. ->where('id', $dir, $id)
  483. ->whereIn('scope', $visibility)
  484. ->limit($limit)
  485. ->orderByDesc('id')
  486. ->get()
  487. ->map(function($s) use($user) {
  488. try {
  489. $status = StatusService::get($s->id, false);
  490. } catch (\Exception $e) {
  491. $status = false;
  492. }
  493. if($user && $status) {
  494. $status['favourited'] = (bool) LikeService::liked($user->profile_id, $s->id);
  495. }
  496. return $status;
  497. })
  498. ->filter(function($s) {
  499. return $s;
  500. })
  501. ->values();
  502. return response()->json($res);
  503. }
  504. /**
  505. * POST /api/v1/accounts/{id}/follow
  506. *
  507. * @param integer $id
  508. *
  509. * @return \App\Transformer\Api\RelationshipTransformer
  510. */
  511. public function accountFollowById(Request $request, $id)
  512. {
  513. abort_if(!$request->user(), 403);
  514. $user = $request->user();
  515. $target = Profile::where('id', '!=', $user->profile_id)
  516. ->whereNull('status')
  517. ->findOrFail($id);
  518. $private = (bool) $target->is_private;
  519. $remote = (bool) $target->domain;
  520. $blocked = UserFilter::whereUserId($target->id)
  521. ->whereFilterType('block')
  522. ->whereFilterableId($user->profile_id)
  523. ->whereFilterableType('App\Profile')
  524. ->exists();
  525. if($blocked == true) {
  526. abort(400, 'You cannot follow this user.');
  527. }
  528. $isFollowing = Follower::whereProfileId($user->profile_id)
  529. ->whereFollowingId($target->id)
  530. ->exists();
  531. // Following already, return empty relationship
  532. if($isFollowing == true) {
  533. $res = RelationshipService::get($user->profile_id, $target->id) ?? [];
  534. return response()->json($res);
  535. }
  536. // Rate limits, max 7500 followers per account
  537. if($user->profile->following()->count() >= Follower::MAX_FOLLOWING) {
  538. abort(400, 'You cannot follow more than ' . Follower::MAX_FOLLOWING . ' accounts');
  539. }
  540. // Rate limits, follow 30 accounts per hour max
  541. if($user->profile->following()->where('followers.created_at', '>', now()->subHour())->count() >= Follower::FOLLOW_PER_HOUR) {
  542. abort(400, 'You can only follow ' . Follower::FOLLOW_PER_HOUR . ' users per hour');
  543. }
  544. if($private == true) {
  545. $follow = FollowRequest::firstOrCreate([
  546. 'follower_id' => $user->profile_id,
  547. 'following_id' => $target->id
  548. ]);
  549. if($remote == true && config('federation.activitypub.remoteFollow') == true) {
  550. (new FollowerController())->sendFollow($user->profile, $target);
  551. }
  552. } else {
  553. $follower = new Follower();
  554. $follower->profile_id = $user->profile_id;
  555. $follower->following_id = $target->id;
  556. $follower->save();
  557. if($remote == true && config('federation.activitypub.remoteFollow') == true) {
  558. (new FollowerController())->sendFollow($user->profile, $target);
  559. }
  560. FollowPipeline::dispatch($follower);
  561. }
  562. RelationshipService::refresh($user->profile_id, $target->id);
  563. Cache::forget('profile:following:'.$target->id);
  564. Cache::forget('profile:followers:'.$target->id);
  565. Cache::forget('profile:following:'.$user->profile_id);
  566. Cache::forget('profile:followers:'.$user->profile_id);
  567. Cache::forget('api:local:exp:rec:'.$user->profile_id);
  568. Cache::forget('user:account:id:'.$target->user_id);
  569. Cache::forget('user:account:id:'.$user->id);
  570. Cache::forget('profile:follower_count:'.$target->id);
  571. Cache::forget('profile:follower_count:'.$user->profile_id);
  572. Cache::forget('profile:following_count:'.$target->id);
  573. Cache::forget('profile:following_count:'.$user->profile_id);
  574. $res = RelationshipService::get($user->profile_id, $target->id);
  575. return response()->json($res);
  576. }
  577. /**
  578. * POST /api/v1/accounts/{id}/unfollow
  579. *
  580. * @param integer $id
  581. *
  582. * @return \App\Transformer\Api\RelationshipTransformer
  583. */
  584. public function accountUnfollowById(Request $request, $id)
  585. {
  586. abort_if(!$request->user(), 403);
  587. $user = $request->user();
  588. $target = Profile::where('id', '!=', $user->profile_id)
  589. ->whereNull('status')
  590. ->findOrFail($id);
  591. RelationshipService::refresh($user->profile_id, $target->id);
  592. $private = (bool) $target->is_private;
  593. $remote = (bool) $target->domain;
  594. $isFollowing = Follower::whereProfileId($user->profile_id)
  595. ->whereFollowingId($target->id)
  596. ->exists();
  597. if($isFollowing == false) {
  598. $resource = new Fractal\Resource\Item($target, new RelationshipTransformer());
  599. $res = $this->fractal->createData($resource)->toArray();
  600. return response()->json($res);
  601. }
  602. // Rate limits, follow 30 accounts per hour max
  603. if($user->profile->following()->where('followers.updated_at', '>', now()->subHour())->count() >= Follower::FOLLOW_PER_HOUR) {
  604. abort(400, 'You can only follow or unfollow ' . Follower::FOLLOW_PER_HOUR . ' users per hour');
  605. }
  606. FollowRequest::whereFollowerId($user->profile_id)
  607. ->whereFollowingId($target->id)
  608. ->delete();
  609. Follower::whereProfileId($user->profile_id)
  610. ->whereFollowingId($target->id)
  611. ->delete();
  612. if($remote == true && config('federation.activitypub.remoteFollow') == true) {
  613. (new FollowerController())->sendUndoFollow($user->profile, $target);
  614. }
  615. Cache::forget('profile:following:'.$target->id);
  616. Cache::forget('profile:followers:'.$target->id);
  617. Cache::forget('profile:following:'.$user->profile_id);
  618. Cache::forget('profile:followers:'.$user->profile_id);
  619. Cache::forget('api:local:exp:rec:'.$user->profile_id);
  620. Cache::forget('user:account:id:'.$target->user_id);
  621. Cache::forget('user:account:id:'.$user->id);
  622. $resource = new Fractal\Resource\Item($target, new RelationshipTransformer());
  623. $res = $this->fractal->createData($resource)->toArray();
  624. return response()->json($res);
  625. }
  626. /**
  627. * GET /api/v1/accounts/relationships
  628. *
  629. * @param array|integer $id
  630. *
  631. * @return \App\Services\RelationshipService
  632. */
  633. public function accountRelationshipsById(Request $request)
  634. {
  635. abort_if(!$request->user(), 403);
  636. $this->validate($request, [
  637. 'id' => 'required|array|min:1|max:20',
  638. 'id.*' => 'required|integer|min:1|max:' . PHP_INT_MAX
  639. ]);
  640. $pid = $request->user()->profile_id ?? $request->user()->profile->id;
  641. $res = collect($request->input('id'))
  642. ->filter(function($id) use($pid) {
  643. return $id != $pid;
  644. })
  645. ->map(function($id) use($pid) {
  646. return RelationshipService::get($pid, $id);
  647. });
  648. return response()->json($res);
  649. }
  650. /**
  651. * GET /api/v1/accounts/search
  652. *
  653. *
  654. *
  655. * @return \App\Transformer\Api\AccountTransformer
  656. */
  657. public function accountSearch(Request $request)
  658. {
  659. abort_if(!$request->user(), 403);
  660. $this->validate($request, [
  661. 'q' => 'required|string|min:1|max:255',
  662. 'limit' => 'nullable|integer|min:1|max:40',
  663. 'resolve' => 'nullable'
  664. ]);
  665. $user = $request->user();
  666. $query = $request->input('q');
  667. $limit = $request->input('limit') ?? 20;
  668. $resolve = (bool) $request->input('resolve', false);
  669. $q = '%' . $query . '%';
  670. $profiles = Profile::whereNull('status')
  671. ->where('username', 'like', $q)
  672. ->orWhere('name', 'like', $q)
  673. ->limit($limit)
  674. ->get();
  675. $resource = new Fractal\Resource\Collection($profiles, new AccountTransformer());
  676. $res = $this->fractal->createData($resource)->toArray();
  677. return response()->json($res);
  678. }
  679. /**
  680. * GET /api/v1/blocks
  681. *
  682. *
  683. *
  684. * @return \App\Transformer\Api\AccountTransformer
  685. */
  686. public function accountBlocks(Request $request)
  687. {
  688. abort_if(!$request->user(), 403);
  689. $this->validate($request, [
  690. 'limit' => 'nullable|integer|min:1|max:40',
  691. 'page' => 'nullable|integer|min:1|max:10'
  692. ]);
  693. $user = $request->user();
  694. $limit = $request->input('limit') ?? 40;
  695. $blocked = UserFilter::select('filterable_id','filterable_type','filter_type','user_id')
  696. ->whereUserId($user->profile_id)
  697. ->whereFilterableType('App\Profile')
  698. ->whereFilterType('block')
  699. ->simplePaginate($limit)
  700. ->pluck('filterable_id');
  701. $profiles = Profile::findOrFail($blocked);
  702. $resource = new Fractal\Resource\Collection($profiles, new AccountTransformer());
  703. $res = $this->fractal->createData($resource)->toArray();
  704. return response()->json($res);
  705. }
  706. /**
  707. * POST /api/v1/accounts/{id}/block
  708. *
  709. * @param integer $id
  710. *
  711. * @return \App\Transformer\Api\RelationshipTransformer
  712. */
  713. public function accountBlockById(Request $request, $id)
  714. {
  715. abort_if(!$request->user(), 403);
  716. $user = $request->user();
  717. $pid = $user->profile_id ?? $user->profile->id;
  718. if($id == $pid) {
  719. abort(400, 'You cannot block yourself');
  720. }
  721. $profile = Profile::findOrFail($id);
  722. if($profile->user->is_admin == true) {
  723. abort(400, 'You cannot block an admin');
  724. }
  725. Follower::whereProfileId($profile->id)->whereFollowingId($pid)->delete();
  726. Follower::whereProfileId($pid)->whereFollowingId($profile->id)->delete();
  727. Notification::whereProfileId($pid)->whereActorId($profile->id)->delete();
  728. $filter = UserFilter::firstOrCreate([
  729. 'user_id' => $pid,
  730. 'filterable_id' => $profile->id,
  731. 'filterable_type' => 'App\Profile',
  732. 'filter_type' => 'block',
  733. ]);
  734. Cache::forget("user:filter:list:$pid");
  735. Cache::forget("api:local:exp:rec:$pid");
  736. $resource = new Fractal\Resource\Item($profile, new RelationshipTransformer());
  737. $res = $this->fractal->createData($resource)->toArray();
  738. return response()->json($res);
  739. }
  740. /**
  741. * POST /api/v1/accounts/{id}/unblock
  742. *
  743. * @param integer $id
  744. *
  745. * @return \App\Transformer\Api\RelationshipTransformer
  746. */
  747. public function accountUnblockById(Request $request, $id)
  748. {
  749. abort_if(!$request->user(), 403);
  750. $user = $request->user();
  751. $pid = $user->profile_id ?? $user->profile->id;
  752. if($id == $pid) {
  753. abort(400, 'You cannot unblock yourself');
  754. }
  755. $profile = Profile::findOrFail($id);
  756. UserFilter::whereUserId($pid)
  757. ->whereFilterableId($profile->id)
  758. ->whereFilterableType('App\Profile')
  759. ->whereFilterType('block')
  760. ->delete();
  761. Cache::forget("user:filter:list:$pid");
  762. Cache::forget("api:local:exp:rec:$pid");
  763. $resource = new Fractal\Resource\Item($profile, new RelationshipTransformer());
  764. $res = $this->fractal->createData($resource)->toArray();
  765. return response()->json($res);
  766. }
  767. /**
  768. * GET /api/v1/custom_emojis
  769. *
  770. * Return empty array, we don't support custom emoji
  771. *
  772. * @return array
  773. */
  774. public function customEmojis()
  775. {
  776. return response()->json([]);
  777. }
  778. /**
  779. * GET /api/v1/domain_blocks
  780. *
  781. * Return empty array
  782. *
  783. * @return array
  784. */
  785. public function accountDomainBlocks(Request $request)
  786. {
  787. abort_if(!$request->user(), 403);
  788. return response()->json([]);
  789. }
  790. /**
  791. * GET /api/v1/endorsements
  792. *
  793. * Return empty array
  794. *
  795. * @return array
  796. */
  797. public function accountEndorsements(Request $request)
  798. {
  799. abort_if(!$request->user(), 403);
  800. return response()->json([]);
  801. }
  802. /**
  803. * GET /api/v1/favourites
  804. *
  805. * Returns collection of liked statuses
  806. *
  807. * @return \App\Transformer\Api\StatusTransformer
  808. */
  809. public function accountFavourites(Request $request)
  810. {
  811. abort_if(!$request->user(), 403);
  812. $this->validate($request, [
  813. 'limit' => 'sometimes|integer|min:1|max:20'
  814. ]);
  815. $user = $request->user();
  816. $maxId = $request->input('max_id');
  817. $minId = $request->input('min_id');
  818. $limit = $request->input('limit') ?? 10;
  819. $res = Like::whereProfileId($user->profile_id)
  820. ->when($maxId, function($q, $maxId) {
  821. return $q->where('id', '<', $maxId);
  822. })
  823. ->when($minId, function($q, $minId) {
  824. return $q->where('id', '>', $minId);
  825. })
  826. ->orderByDesc('id')
  827. ->limit($limit)
  828. ->get()
  829. ->map(function($like) {
  830. $status = StatusService::get($like['status_id'], false);
  831. $status['like_id'] = $like->id;
  832. $status['liked_at'] = $like->created_at->format('c');
  833. return $status;
  834. })
  835. ->filter(function($status) {
  836. return $status && isset($status['id'], $status['like_id']);
  837. })
  838. ->values();
  839. if($res->count()) {
  840. $ids = $res->map(function($status) {
  841. return $status['like_id'];
  842. });
  843. $max = $ids->max();
  844. $min = $ids->min();
  845. $baseUrl = config('app.url') . '/api/v1/favourites?limit=' . $limit . '&';
  846. $link = '<'.$baseUrl.'max_id='.$max.'>; rel="next",<'.$baseUrl.'min_id='.$min.'>; rel="prev"';
  847. return response()
  848. ->json($res)
  849. ->withHeaders([
  850. 'Link' => $link,
  851. ]);
  852. } else {
  853. return response()->json($res);
  854. }
  855. }
  856. /**
  857. * POST /api/v1/statuses/{id}/favourite
  858. *
  859. * @param integer $id
  860. *
  861. * @return \App\Transformer\Api\StatusTransformer
  862. */
  863. public function statusFavouriteById(Request $request, $id)
  864. {
  865. abort_if(!$request->user(), 403);
  866. $user = $request->user();
  867. $status = Status::findOrFail($id);
  868. if($status->profile_id !== $user->profile_id) {
  869. if($status->scope == 'private') {
  870. abort_if(!$status->profile->followedBy($user->profile), 403);
  871. } else {
  872. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  873. }
  874. }
  875. $like = Like::firstOrCreate([
  876. 'profile_id' => $user->profile_id,
  877. 'status_id' => $status->id
  878. ]);
  879. if($like->wasRecentlyCreated == true) {
  880. $like->status_profile_id = $status->profile_id;
  881. $like->is_comment = !empty($status->in_reply_to_id);
  882. $like->save();
  883. $status->likes_count = $status->likes()->count();
  884. $status->save();
  885. LikePipeline::dispatch($like);
  886. }
  887. $resource = new Fractal\Resource\Item($status, new StatusTransformer());
  888. $res = $this->fractal->createData($resource)->toArray();
  889. return response()->json($res);
  890. }
  891. /**
  892. * POST /api/v1/statuses/{id}/unfavourite
  893. *
  894. * @param integer $id
  895. *
  896. * @return \App\Transformer\Api\StatusTransformer
  897. */
  898. public function statusUnfavouriteById(Request $request, $id)
  899. {
  900. abort_if(!$request->user(), 403);
  901. $user = $request->user();
  902. $status = Status::findOrFail($id);
  903. if($status->profile_id !== $user->profile_id) {
  904. if($status->scope == 'private') {
  905. abort_if(!$status->profile->followedBy($user->profile), 403);
  906. } else {
  907. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  908. }
  909. }
  910. $like = Like::whereProfileId($user->profile_id)
  911. ->whereStatusId($status->id)
  912. ->first();
  913. if($like) {
  914. $like->forceDelete();
  915. $status->likes_count = $status->likes()->count();
  916. $status->save();
  917. }
  918. StatusService::del($status->id);
  919. $resource = new Fractal\Resource\Item($status, new StatusTransformer());
  920. $res = $this->fractal->createData($resource)->toArray();
  921. return response()->json($res);
  922. }
  923. /**
  924. * GET /api/v1/filters
  925. *
  926. * Return empty response since we filter server side
  927. *
  928. * @return array
  929. */
  930. public function accountFilters(Request $request)
  931. {
  932. abort_if(!$request->user(), 403);
  933. return response()->json([]);
  934. }
  935. /**
  936. * GET /api/v1/follow_requests
  937. *
  938. * Return array of Accounts that have sent follow requests
  939. *
  940. * @return \App\Transformer\Api\AccountTransformer
  941. */
  942. public function accountFollowRequests(Request $request)
  943. {
  944. abort_if(!$request->user(), 403);
  945. $user = $request->user();
  946. $followRequests = FollowRequest::whereFollowingId($user->profile->id)->pluck('follower_id');
  947. $profiles = Profile::find($followRequests);
  948. $resource = new Fractal\Resource\Collection($profiles, new AccountTransformer());
  949. $res = $this->fractal->createData($resource)->toArray();
  950. return response()->json($res);
  951. }
  952. /**
  953. * POST /api/v1/follow_requests/{id}/authorize
  954. *
  955. * @param integer $id
  956. *
  957. * @return null
  958. */
  959. public function accountFollowRequestAccept(Request $request, $id)
  960. {
  961. abort_if(!$request->user(), 403);
  962. // todo
  963. return response()->json([]);
  964. }
  965. /**
  966. * POST /api/v1/follow_requests/{id}/reject
  967. *
  968. * @param integer $id
  969. *
  970. * @return null
  971. */
  972. public function accountFollowRequestReject(Request $request, $id)
  973. {
  974. abort_if(!$request->user(), 403);
  975. // todo
  976. return response()->json([]);
  977. }
  978. /**
  979. * GET /api/v1/suggestions
  980. *
  981. * Return empty array as we don't support suggestions
  982. *
  983. * @return null
  984. */
  985. public function accountSuggestions(Request $request)
  986. {
  987. abort_if(!$request->user(), 403);
  988. // todo
  989. return response()->json([]);
  990. }
  991. /**
  992. * GET /api/v1/instance
  993. *
  994. * Information about the server.
  995. *
  996. * @return Instance
  997. */
  998. public function instance(Request $request)
  999. {
  1000. $res = Cache::remember('api:v1:instance-data', now()->addMinutes(15), function () {
  1001. $rules = config_cache('app.rules') ? collect(json_decode(config_cache('app.rules'), true))
  1002. ->map(function($rule, $key) {
  1003. $id = $key + 1;
  1004. return [
  1005. 'id' => "{$id}",
  1006. 'text' => $rule
  1007. ];
  1008. })
  1009. ->toArray() : [];
  1010. $res = [
  1011. 'approval_required' => false,
  1012. 'contact_account' => null,
  1013. 'description' => config_cache('app.description'),
  1014. 'email' => config('instance.email'),
  1015. 'invites_enabled' => false,
  1016. 'rules' => $rules,
  1017. 'short_description' => 'Pixelfed - Photo sharing for everyone',
  1018. 'languages' => ['en'],
  1019. 'max_toot_chars' => (int) config('pixelfed.max_caption_length'),
  1020. 'registrations' => (bool) config_cache('pixelfed.open_registration'),
  1021. 'stats' => [
  1022. 'user_count' => 0,
  1023. 'status_count' => 0,
  1024. 'domain_count' => 0
  1025. ],
  1026. 'thumbnail' => config('app.url') . '/img/pixelfed-icon-color.png',
  1027. 'title' => config_cache('app.name'),
  1028. 'uri' => config('pixelfed.domain.app'),
  1029. 'urls' => [],
  1030. 'version' => '2.7.2 (compatible; Pixelfed ' . config('pixelfed.version') . ')',
  1031. 'environment' => [
  1032. 'max_photo_size' => (int) config_cache('pixelfed.max_photo_size'),
  1033. 'max_avatar_size' => (int) config('pixelfed.max_avatar_size'),
  1034. 'max_caption_length' => (int) config('pixelfed.max_caption_length'),
  1035. 'max_bio_length' => (int) config('pixelfed.max_bio_length'),
  1036. 'max_album_length' => (int) config_cache('pixelfed.max_album_length'),
  1037. 'mobile_apis' => (bool) config_cache('pixelfed.oauth_enabled')
  1038. ]
  1039. ];
  1040. return $res;
  1041. });
  1042. return response()->json($res);
  1043. }
  1044. /**
  1045. * GET /api/v1/lists
  1046. *
  1047. * Return empty array as we don't support lists
  1048. *
  1049. * @return null
  1050. */
  1051. public function accountLists(Request $request)
  1052. {
  1053. abort_if(!$request->user(), 403);
  1054. return response()->json([]);
  1055. }
  1056. /**
  1057. * GET /api/v1/accounts/{id}/lists
  1058. *
  1059. * @param integer $id
  1060. *
  1061. * @return null
  1062. */
  1063. public function accountListsById(Request $request, $id)
  1064. {
  1065. abort_if(!$request->user(), 403);
  1066. return response()->json([]);
  1067. }
  1068. /**
  1069. * POST /api/v1/media
  1070. *
  1071. *
  1072. * @return MediaTransformer
  1073. */
  1074. public function mediaUpload(Request $request)
  1075. {
  1076. abort_if(!$request->user(), 403);
  1077. $this->validate($request, [
  1078. 'file.*' => function() {
  1079. return [
  1080. 'required',
  1081. 'mimes:' . config_cache('pixelfed.media_types'),
  1082. 'max:' . config_cache('pixelfed.max_photo_size'),
  1083. ];
  1084. },
  1085. 'filter_name' => 'nullable|string|max:24',
  1086. 'filter_class' => 'nullable|alpha_dash|max:24',
  1087. 'description' => 'nullable|string|max:' . config_cache('pixelfed.max_altext_length')
  1088. ]);
  1089. $user = $request->user();
  1090. if($user->last_active_at == null) {
  1091. return [];
  1092. }
  1093. $limitKey = 'compose:rate-limit:media-upload:' . $user->id;
  1094. $limitTtl = now()->addMinutes(15);
  1095. $limitReached = Cache::remember($limitKey, $limitTtl, function() use($user) {
  1096. $dailyLimit = Media::whereUserId($user->id)->where('created_at', '>', now()->subDays(1))->count();
  1097. return $dailyLimit >= 250;
  1098. });
  1099. abort_if($limitReached == true, 429);
  1100. $profile = $user->profile;
  1101. if(config_cache('pixelfed.enforce_account_limit') == true) {
  1102. $size = Cache::remember($user->storageUsedKey(), now()->addDays(3), function() use($user) {
  1103. return Media::whereUserId($user->id)->sum('size') / 1000;
  1104. });
  1105. $limit = (int) config_cache('pixelfed.max_account_size');
  1106. if ($size >= $limit) {
  1107. abort(403, 'Account size limit reached.');
  1108. }
  1109. }
  1110. $filterClass = in_array($request->input('filter_class'), Filter::classes()) ? $request->input('filter_class') : null;
  1111. $filterName = in_array($request->input('filter_name'), Filter::names()) ? $request->input('filter_name') : null;
  1112. $photo = $request->file('file');
  1113. $mimes = explode(',', config_cache('pixelfed.media_types'));
  1114. if(in_array($photo->getMimeType(), $mimes) == false) {
  1115. abort(403, 'Invalid or unsupported mime type.');
  1116. }
  1117. $storagePath = MediaPathService::get($user, 2);
  1118. $path = $photo->store($storagePath);
  1119. $hash = \hash_file('sha256', $photo);
  1120. $license = null;
  1121. $mime = $photo->getMimeType();
  1122. // if($photo->getMimeType() == 'image/heic') {
  1123. // abort_if(config('image.driver') !== 'imagick', 422, 'Invalid media type');
  1124. // abort_if(!in_array('HEIC', \Imagick::queryformats()), 422, 'Unsupported media type');
  1125. // $oldPath = $path;
  1126. // $path = str_replace('.heic', '.jpg', $path);
  1127. // $mime = 'image/jpeg';
  1128. // \Image::make($photo)->save(storage_path("app/{$path}"));
  1129. // @unlink(storage_path("app/{$oldPath}"));
  1130. // }
  1131. $settings = UserSetting::whereUserId($user->id)->first();
  1132. if($settings && !empty($settings->compose_settings)) {
  1133. $compose = json_decode($settings->compose_settings, true);
  1134. if(isset($compose['default_license']) && $compose['default_license'] != 1) {
  1135. $license = $compose['default_license'];
  1136. }
  1137. }
  1138. abort_if(MediaBlocklistService::exists($hash) == true, 451);
  1139. $media = new Media();
  1140. $media->status_id = null;
  1141. $media->profile_id = $profile->id;
  1142. $media->user_id = $user->id;
  1143. $media->media_path = $path;
  1144. $media->original_sha256 = $hash;
  1145. $media->size = $photo->getSize();
  1146. $media->mime = $mime;
  1147. $media->caption = $request->input('description');
  1148. $media->filter_class = $filterClass;
  1149. $media->filter_name = $filterName;
  1150. if($license) {
  1151. $media->license = $license;
  1152. }
  1153. $media->save();
  1154. switch ($media->mime) {
  1155. case 'image/jpeg':
  1156. case 'image/png':
  1157. ImageOptimize::dispatch($media);
  1158. break;
  1159. case 'video/mp4':
  1160. VideoThumbnail::dispatch($media);
  1161. $preview_url = '/storage/no-preview.png';
  1162. $url = '/storage/no-preview.png';
  1163. break;
  1164. }
  1165. Cache::forget($limitKey);
  1166. $resource = new Fractal\Resource\Item($media, new MediaTransformer());
  1167. $res = $this->fractal->createData($resource)->toArray();
  1168. $res['preview_url'] = $media->url(). '?cb=1&_v=' . time();
  1169. $res['url'] = $media->url(). '?cb=1&_v=' . time();
  1170. return response()->json($res);
  1171. }
  1172. /**
  1173. * PUT /api/v1/media/{id}
  1174. *
  1175. * @param integer $id
  1176. *
  1177. * @return MediaTransformer
  1178. */
  1179. public function mediaUpdate(Request $request, $id)
  1180. {
  1181. abort_if(!$request->user(), 403);
  1182. $this->validate($request, [
  1183. 'description' => 'nullable|string|max:' . config_cache('pixelfed.max_altext_length')
  1184. ]);
  1185. $user = $request->user();
  1186. $media = Media::whereUserId($user->id)
  1187. ->whereNull('status_id')
  1188. ->findOrFail($id);
  1189. $media->caption = $request->input('description');
  1190. $media->save();
  1191. $resource = new Fractal\Resource\Item($media, new MediaTransformer());
  1192. $res = $this->fractal->createData($resource)->toArray();
  1193. $res['preview_url'] = url('/storage/no-preview.png');
  1194. $res['url'] = url('/storage/no-preview.png');
  1195. return response()->json($res);
  1196. }
  1197. /**
  1198. * GET /api/v1/mutes
  1199. *
  1200. *
  1201. * @return AccountTransformer
  1202. */
  1203. public function accountMutes(Request $request)
  1204. {
  1205. abort_if(!$request->user(), 403);
  1206. $this->validate($request, [
  1207. 'limit' => 'nullable|integer|min:1|max:40'
  1208. ]);
  1209. $user = $request->user();
  1210. $limit = $request->input('limit') ?? 40;
  1211. $mutes = UserFilter::whereUserId($user->profile_id)
  1212. ->whereFilterableType('App\Profile')
  1213. ->whereFilterType('mute')
  1214. ->simplePaginate($limit)
  1215. ->pluck('filterable_id');
  1216. $accounts = Profile::find($mutes);
  1217. $resource = new Fractal\Resource\Collection($accounts, new AccountTransformer());
  1218. $res = $this->fractal->createData($resource)->toArray();
  1219. return response()->json($res);
  1220. }
  1221. /**
  1222. * POST /api/v1/accounts/{id}/mute
  1223. *
  1224. * @param integer $id
  1225. *
  1226. * @return RelationshipTransformer
  1227. */
  1228. public function accountMuteById(Request $request, $id)
  1229. {
  1230. abort_if(!$request->user(), 403);
  1231. $user = $request->user();
  1232. $pid = $user->profile_id;
  1233. $account = Profile::findOrFail($id);
  1234. $filter = UserFilter::firstOrCreate([
  1235. 'user_id' => $pid,
  1236. 'filterable_id' => $account->id,
  1237. 'filterable_type' => 'App\Profile',
  1238. 'filter_type' => 'mute',
  1239. ]);
  1240. Cache::forget("user:filter:list:$pid");
  1241. Cache::forget("feature:discover:posts:$pid");
  1242. Cache::forget("api:local:exp:rec:$pid");
  1243. $resource = new Fractal\Resource\Item($account, new RelationshipTransformer());
  1244. $res = $this->fractal->createData($resource)->toArray();
  1245. return response()->json($res);
  1246. }
  1247. /**
  1248. * POST /api/v1/accounts/{id}/unmute
  1249. *
  1250. * @param integer $id
  1251. *
  1252. * @return RelationshipTransformer
  1253. */
  1254. public function accountUnmuteById(Request $request, $id)
  1255. {
  1256. abort_if(!$request->user(), 403);
  1257. $user = $request->user();
  1258. $pid = $user->profile_id;
  1259. $account = Profile::findOrFail($id);
  1260. $filter = UserFilter::whereUserId($pid)
  1261. ->whereFilterableId($account->id)
  1262. ->whereFilterableType('App\Profile')
  1263. ->whereFilterType('mute')
  1264. ->first();
  1265. if($filter) {
  1266. $filter->delete();
  1267. Cache::forget("user:filter:list:$pid");
  1268. Cache::forget("feature:discover:posts:$pid");
  1269. Cache::forget("api:local:exp:rec:$pid");
  1270. }
  1271. $resource = new Fractal\Resource\Item($account, new RelationshipTransformer());
  1272. $res = $this->fractal->createData($resource)->toArray();
  1273. return response()->json($res);
  1274. }
  1275. /**
  1276. * GET /api/v1/notifications
  1277. *
  1278. *
  1279. * @return NotificationTransformer
  1280. */
  1281. public function accountNotifications(Request $request)
  1282. {
  1283. abort_if(!$request->user(), 403);
  1284. $this->validate($request, [
  1285. 'limit' => 'nullable|integer|min:1|max:80',
  1286. 'min_id' => 'nullable|integer|min:1|max:'.PHP_INT_MAX,
  1287. 'max_id' => 'nullable|integer|min:1|max:'.PHP_INT_MAX,
  1288. 'since_id' => 'nullable|integer|min:1|max:'.PHP_INT_MAX,
  1289. ]);
  1290. $pid = $request->user()->profile_id;
  1291. $limit = $request->input('limit', 20);
  1292. $since = $request->input('since_id');
  1293. $min = $request->input('min_id');
  1294. $max = $request->input('max_id');
  1295. if(!$since && !$min && !$max) {
  1296. $min = 1;
  1297. }
  1298. $maxId = null;
  1299. $minId = null;
  1300. if($max) {
  1301. $res = NotificationService::getMax($pid, $max, $limit);
  1302. $ids = NotificationService::getRankedMaxId($pid, $max, $limit);
  1303. if(!empty($ids)) {
  1304. $maxId = max($ids);
  1305. $minId = min($ids);
  1306. }
  1307. } else {
  1308. $res = NotificationService::getMin($pid, $min ?? $since, $limit);
  1309. $ids = NotificationService::getRankedMinId($pid, $min ?? $since, $limit);
  1310. if(!empty($ids)) {
  1311. $maxId = max($ids);
  1312. $minId = min($ids);
  1313. }
  1314. }
  1315. if(empty($res) && !Cache::has('pf:services:notifications:hasSynced:'.$pid)) {
  1316. Cache::put('pf:services:notifications:hasSynced:'.$pid, 1, 1209600);
  1317. NotificationService::warmCache($pid, 400, true);
  1318. }
  1319. $baseUrl = config('app.url') . '/api/v1/notifications?limit=' . $limit . '&';
  1320. if($minId == $maxId) {
  1321. $minId = null;
  1322. }
  1323. if($maxId) {
  1324. $link = '<'.$baseUrl.'max_id='.$maxId.'>; rel="next"';
  1325. }
  1326. if($minId) {
  1327. $link = '<'.$baseUrl.'min_id='.$minId.'>; rel="prev"';
  1328. }
  1329. if($maxId && $minId) {
  1330. $link = '<'.$baseUrl.'max_id='.$maxId.'>; rel="next",<'.$baseUrl.'min_id='.$minId.'>; rel="prev"';
  1331. }
  1332. $res = response()->json($res);
  1333. if(isset($link)) {
  1334. $res->withHeaders([
  1335. 'Link' => $link,
  1336. ]);
  1337. }
  1338. return $res;
  1339. }
  1340. /**
  1341. * GET /api/v1/timelines/home
  1342. *
  1343. *
  1344. * @return StatusTransformer
  1345. */
  1346. public function timelineHome(Request $request)
  1347. {
  1348. abort_if(!$request->user(), 403);
  1349. $this->validate($request,[
  1350. 'page' => 'nullable|integer|max:40',
  1351. 'min_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  1352. 'max_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  1353. 'limit' => 'nullable|integer|max:80'
  1354. ]);
  1355. $page = $request->input('page');
  1356. $min = $request->input('min_id');
  1357. $max = $request->input('max_id');
  1358. $limit = $request->input('limit') ?? 3;
  1359. $user = $request->user();
  1360. if($user->last_active_at) {
  1361. $key = 'user:last_active_at:id:'.$user->id;
  1362. $ttl = now()->addMinutes(5);
  1363. Cache::remember($key, $ttl, function() use($user) {
  1364. $user->last_active_at = now();
  1365. $user->save();
  1366. return;
  1367. });
  1368. }
  1369. $pid = $request->user()->profile_id;
  1370. $following = Cache::remember('profile:following:'.$pid, now()->addMinutes(1440), function() use($pid) {
  1371. $following = Follower::whereProfileId($pid)->pluck('following_id');
  1372. return $following->push($pid)->toArray();
  1373. });
  1374. if($min || $max) {
  1375. $dir = $min ? '>' : '<';
  1376. $id = $min ?? $max;
  1377. $timeline = Status::select(
  1378. 'id',
  1379. 'uri',
  1380. 'caption',
  1381. 'rendered',
  1382. 'profile_id',
  1383. 'type',
  1384. 'in_reply_to_id',
  1385. 'reblog_of_id',
  1386. 'is_nsfw',
  1387. 'scope',
  1388. 'local',
  1389. 'reply_count',
  1390. 'likes_count',
  1391. 'reblogs_count',
  1392. 'comments_disabled',
  1393. 'place_id',
  1394. 'created_at',
  1395. 'updated_at'
  1396. )->whereIn('type', ['photo', 'photo:album', 'video', 'video:album'])
  1397. ->with('profile', 'hashtags', 'mentions')
  1398. ->where('id', $dir, $id)
  1399. ->whereIn('profile_id', $following)
  1400. ->whereIn('visibility',['public', 'unlisted', 'private'])
  1401. ->latest()
  1402. ->limit($limit)
  1403. ->get();
  1404. } else {
  1405. $timeline = Status::select(
  1406. 'id',
  1407. 'uri',
  1408. 'caption',
  1409. 'rendered',
  1410. 'profile_id',
  1411. 'type',
  1412. 'in_reply_to_id',
  1413. 'reblog_of_id',
  1414. 'is_nsfw',
  1415. 'scope',
  1416. 'local',
  1417. 'reply_count',
  1418. 'comments_disabled',
  1419. 'likes_count',
  1420. 'reblogs_count',
  1421. 'place_id',
  1422. 'created_at',
  1423. 'updated_at'
  1424. )->whereIn('type', ['photo', 'photo:album', 'video', 'video:album'])
  1425. ->with('profile', 'hashtags', 'mentions')
  1426. ->whereIn('profile_id', $following)
  1427. ->whereIn('visibility',['public', 'unlisted', 'private'])
  1428. ->latest()
  1429. ->simplePaginate($limit);
  1430. }
  1431. $fractal = new Fractal\Resource\Collection($timeline, new StatusTransformer());
  1432. $res = $this->fractal->createData($fractal)->toArray();
  1433. return response()->json($res);
  1434. }
  1435. /**
  1436. * GET /api/v1/conversations
  1437. *
  1438. * Not implemented
  1439. *
  1440. * @return array
  1441. */
  1442. public function conversations(Request $request)
  1443. {
  1444. abort_if(!$request->user(), 403);
  1445. $this->validate($request, [
  1446. 'limit' => 'min:1|max:40',
  1447. 'scope' => 'nullable|in:inbox,sent,requests'
  1448. ]);
  1449. $limit = $request->input('limit', 20);
  1450. $scope = $request->input('scope', 'inbox');
  1451. $pid = $request->user()->profile_id;
  1452. $dms = DirectMessage::when($scope === 'inbox', function($q, $scope) use($pid) {
  1453. return $q->whereIsHidden(false)->whereToId($pid)->orWhere('from_id', $pid)->groupBy('to_id');
  1454. })
  1455. ->when($scope === 'sent', function($q, $scope) use($pid) {
  1456. return $q->whereFromId($pid)->groupBy('to_id');
  1457. })
  1458. ->when($scope === 'requests', function($q, $scope) use($pid) {
  1459. return $q->whereToId($pid)->whereIsHidden(true);
  1460. })
  1461. ->latest()
  1462. ->simplePaginate($limit)
  1463. ->map(function($dm) use($pid) {
  1464. $from = $pid == $dm->to_id ? $dm->from_id : $dm->to_id;
  1465. $res = [
  1466. 'id' => $dm->id,
  1467. 'unread' => false,
  1468. 'accounts' => [
  1469. AccountService::get($from)
  1470. ],
  1471. 'last_status' => StatusService::getDirectMessage($dm->status_id)
  1472. ];
  1473. return $res;
  1474. })
  1475. ->filter(function($dm) {
  1476. return isset($dm['accounts']) && count($dm['accounts']);
  1477. })
  1478. ->unique(function($item, $key) {
  1479. return $item['accounts'][0]['id'];
  1480. })
  1481. ->values();
  1482. return response()->json($dms);
  1483. }
  1484. /**
  1485. * GET /api/v1/timelines/public
  1486. *
  1487. *
  1488. * @return StatusTransformer
  1489. */
  1490. public function timelinePublic(Request $request)
  1491. {
  1492. $this->validate($request,[
  1493. 'min_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  1494. 'max_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  1495. 'limit' => 'nullable|integer|max:80'
  1496. ]);
  1497. $min = $request->input('min_id');
  1498. $max = $request->input('max_id');
  1499. $limit = $request->input('limit') ?? 3;
  1500. $user = $request->user();
  1501. $filtered = $user ? UserFilterService::filters($user->profile_id) : [];
  1502. Cache::remember('api:v1:timelines:public:cache_check', 10368000, function() {
  1503. if(PublicTimelineService::count() == 0) {
  1504. PublicTimelineService::warmCache(true, 400);
  1505. }
  1506. });
  1507. if ($max) {
  1508. $feed = PublicTimelineService::getRankedMaxId($max, $limit);
  1509. } else if ($min) {
  1510. $feed = PublicTimelineService::getRankedMinId($min, $limit);
  1511. } else {
  1512. $feed = PublicTimelineService::get(0, $limit);
  1513. }
  1514. $res = collect($feed)
  1515. ->map(function($k) use($user) {
  1516. $status = StatusService::get($k);
  1517. if($user) {
  1518. $status['favourited'] = (bool) LikeService::liked($user->profile_id, $k);
  1519. $status['relationship'] = RelationshipService::get($user->profile_id, $status['account']['id']);
  1520. }
  1521. return $status;
  1522. })
  1523. ->filter(function($s) use($filtered) {
  1524. return in_array($s['account']['id'], $filtered) == false;
  1525. })
  1526. ->toArray();
  1527. return response()->json($res);
  1528. }
  1529. /**
  1530. * GET /api/v1/statuses/{id}
  1531. *
  1532. * @param integer $id
  1533. *
  1534. * @return StatusTransformer
  1535. */
  1536. public function statusById(Request $request, $id)
  1537. {
  1538. abort_if(!$request->user(), 403);
  1539. $user = $request->user();
  1540. $status = Status::findOrFail($id);
  1541. if($status->profile_id !== $user->profile_id) {
  1542. if($status->scope == 'private') {
  1543. abort_if(!$status->profile->followedBy($user->profile), 403);
  1544. } else {
  1545. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  1546. }
  1547. }
  1548. $resource = new Fractal\Resource\Item($status, new StatusTransformer());
  1549. $res = $this->fractal->createData($resource)->toArray();
  1550. return response()->json($res);
  1551. }
  1552. /**
  1553. * GET /api/v1/statuses/{id}/context
  1554. *
  1555. * @param integer $id
  1556. *
  1557. * @return StatusTransformer
  1558. */
  1559. public function statusContext(Request $request, $id)
  1560. {
  1561. abort_if(!$request->user(), 403);
  1562. $user = $request->user();
  1563. $status = Status::findOrFail($id);
  1564. if($status->profile_id !== $user->profile_id) {
  1565. if($status->scope == 'private') {
  1566. abort_if(!$status->profile->followedBy($user->profile), 403);
  1567. } else {
  1568. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  1569. }
  1570. }
  1571. if($status->comments_disabled) {
  1572. $res = [
  1573. 'ancestors' => [],
  1574. 'descendants' => []
  1575. ];
  1576. } else {
  1577. $ancestors = $status->parent();
  1578. if($ancestors) {
  1579. $ares = new Fractal\Resource\Item($ancestors, new StatusTransformer());
  1580. $ancestors = [
  1581. $this->fractal->createData($ares)->toArray()
  1582. ];
  1583. } else {
  1584. $ancestors = [];
  1585. }
  1586. $descendants = Status::whereInReplyToId($id)->latest()->limit(20)->get();
  1587. $dres = new Fractal\Resource\Collection($descendants, new StatusTransformer());
  1588. $descendants = $this->fractal->createData($dres)->toArray();
  1589. $res = [
  1590. 'ancestors' => $ancestors,
  1591. 'descendants' => $descendants
  1592. ];
  1593. }
  1594. return response()->json($res);
  1595. }
  1596. /**
  1597. * GET /api/v1/statuses/{id}/card
  1598. *
  1599. * @param integer $id
  1600. *
  1601. * @return StatusTransformer
  1602. */
  1603. public function statusCard(Request $request, $id)
  1604. {
  1605. abort_if(!$request->user(), 403);
  1606. $user = $request->user();
  1607. $status = Status::findOrFail($id);
  1608. if($status->profile_id !== $user->profile_id) {
  1609. if($status->scope == 'private') {
  1610. abort_if(!$status->profile->followedBy($user->profile), 403);
  1611. } else {
  1612. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  1613. }
  1614. }
  1615. // Return empty response since we don't handle support cards
  1616. $res = [];
  1617. return response()->json($res);
  1618. }
  1619. /**
  1620. * GET /api/v1/statuses/{id}/reblogged_by
  1621. *
  1622. * @param integer $id
  1623. *
  1624. * @return AccountTransformer
  1625. */
  1626. public function statusRebloggedBy(Request $request, $id)
  1627. {
  1628. abort_if(!$request->user(), 403);
  1629. $this->validate($request, [
  1630. 'page' => 'nullable|integer|min:1|max:40',
  1631. 'limit' => 'nullable|integer|min:1|max:80'
  1632. ]);
  1633. $limit = $request->input('limit') ?? 40;
  1634. $user = $request->user();
  1635. $status = Status::findOrFail($id);
  1636. if($status->profile_id !== $user->profile_id) {
  1637. if($status->scope == 'private') {
  1638. abort_if(!$status->profile->followedBy($user->profile), 403);
  1639. } else {
  1640. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  1641. }
  1642. }
  1643. $shared = $status->sharedBy()->latest()->simplePaginate($limit);
  1644. $resource = new Fractal\Resource\Collection($shared, new AccountTransformer());
  1645. $res = $this->fractal->createData($resource)->toArray();
  1646. $url = $request->url();
  1647. $page = $request->input('page', 1);
  1648. $next = $page < 40 ? $page + 1 : 40;
  1649. $prev = $page > 1 ? $page - 1 : 1;
  1650. $links = '<'.$url.'?page='.$next.'&limit='.$limit.'>; rel="next", <'.$url.'?page='.$prev.'&limit='.$limit.'>; rel="prev"';
  1651. return response()->json($res, 200, ['Link' => $links]);
  1652. }
  1653. /**
  1654. * GET /api/v1/statuses/{id}/favourited_by
  1655. *
  1656. * @param integer $id
  1657. *
  1658. * @return AccountTransformer
  1659. */
  1660. public function statusFavouritedBy(Request $request, $id)
  1661. {
  1662. abort_if(!$request->user(), 403);
  1663. $this->validate($request, [
  1664. 'page' => 'nullable|integer|min:1|max:40',
  1665. 'limit' => 'nullable|integer|min:1|max:80'
  1666. ]);
  1667. $page = $request->input('page', 1);
  1668. $limit = $request->input('limit') ?? 40;
  1669. $user = $request->user();
  1670. $status = Status::findOrFail($id);
  1671. $offset = $page == 1 ? 0 : ($page * $limit - $limit);
  1672. if($offset > 100) {
  1673. if($user->profile_id != $status->profile_id) {
  1674. return [];
  1675. }
  1676. }
  1677. if($status->profile_id !== $user->profile_id) {
  1678. if($status->scope == 'private') {
  1679. abort_if(!$status->profile->followedBy($user->profile), 403);
  1680. } else {
  1681. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  1682. }
  1683. }
  1684. $res = DB::table('likes')
  1685. ->select('likes.id', 'likes.profile_id', 'likes.status_id', 'followers.created_at')
  1686. ->leftJoin('followers', function($join) use($user, $status) {
  1687. return $join->on('likes.profile_id', '=', 'followers.following_id')
  1688. ->where('followers.profile_id', $user->profile_id)
  1689. ->where('likes.status_id', $status->id);
  1690. })
  1691. ->whereStatusId($status->id)
  1692. ->orderByDesc('followers.created_at')
  1693. ->offset($offset)
  1694. ->limit($limit)
  1695. ->get()
  1696. ->map(function($like) {
  1697. $account = AccountService::get($like->profile_id);
  1698. $account['follows'] = isset($like->created_at);
  1699. return $account;
  1700. })
  1701. ->filter(function($account) use($user) {
  1702. return $account && isset($account['id']) && $account['id'] != $user->profile_id;
  1703. })
  1704. ->values();
  1705. $url = $request->url();
  1706. $page = $request->input('page', 1);
  1707. $next = $page < 40 ? $page + 1 : 40;
  1708. $prev = $page > 1 ? $page - 1 : 1;
  1709. $links = '<'.$url.'?page='.$next.'&limit='.$limit.'>; rel="next", <'.$url.'?page='.$prev.'&limit='.$limit.'>; rel="prev"';
  1710. return response()->json($res, 200, ['Link' => $links]);
  1711. }
  1712. /**
  1713. * POST /api/v1/statuses
  1714. *
  1715. *
  1716. * @return StatusTransformer
  1717. */
  1718. public function statusCreate(Request $request)
  1719. {
  1720. abort_if(!$request->user(), 403);
  1721. $this->validate($request, [
  1722. 'status' => 'nullable|string',
  1723. 'in_reply_to_id' => 'nullable|integer',
  1724. 'media_ids' => 'array|max:' . config_cache('pixelfed.max_album_length'),
  1725. 'media_ids.*' => 'integer|min:1',
  1726. 'sensitive' => 'nullable|boolean',
  1727. 'visibility' => 'string|in:private,unlisted,public',
  1728. ]);
  1729. if(config('costar.enabled') == true) {
  1730. $blockedKeywords = config('costar.keyword.block');
  1731. if($blockedKeywords !== null && $request->status) {
  1732. $keywords = config('costar.keyword.block');
  1733. foreach($keywords as $kw) {
  1734. if(Str::contains($request->status, $kw) == true) {
  1735. abort(400, 'Invalid object. Contains banned keyword.');
  1736. }
  1737. }
  1738. }
  1739. }
  1740. if(!$request->filled('media_ids') && !$request->filled('in_reply_to_id')) {
  1741. abort(403, 'Empty statuses are not allowed');
  1742. }
  1743. $ids = $request->input('media_ids');
  1744. $in_reply_to_id = $request->input('in_reply_to_id');
  1745. $user = $request->user();
  1746. $profile = $user->profile;
  1747. $limitKey = 'compose:rate-limit:store:' . $user->id;
  1748. $limitTtl = now()->addMinutes(15);
  1749. $limitReached = Cache::remember($limitKey, $limitTtl, function() use($user) {
  1750. $dailyLimit = Status::whereProfileId($user->profile_id)
  1751. ->whereNull('in_reply_to_id')
  1752. ->whereNull('reblog_of_id')
  1753. ->where('created_at', '>', now()->subDays(1))
  1754. ->count();
  1755. return $dailyLimit >= 100;
  1756. });
  1757. abort_if($limitReached == true, 429);
  1758. $visibility = $profile->is_private ? 'private' : (
  1759. $profile->unlisted == true &&
  1760. $request->input('visibility', 'public') == 'public' ?
  1761. 'unlisted' :
  1762. $request->input('visibility', 'public'));
  1763. if($user->last_active_at == null) {
  1764. return [];
  1765. }
  1766. if($in_reply_to_id) {
  1767. $parent = Status::findOrFail($in_reply_to_id);
  1768. $status = new Status;
  1769. $status->caption = strip_tags($request->input('status'));
  1770. $status->scope = $visibility;
  1771. $status->visibility = $visibility;
  1772. $status->profile_id = $user->profile_id;
  1773. $status->is_nsfw = $user->profile->cw == true ? true : $request->input('sensitive', false);
  1774. $status->in_reply_to_id = $parent->id;
  1775. $status->in_reply_to_profile_id = $parent->profile_id;
  1776. $status->save();
  1777. StatusService::del($parent->id);
  1778. } else if($ids) {
  1779. if(Media::whereUserId($user->id)
  1780. ->whereNull('status_id')
  1781. ->find($ids)
  1782. ->count() == 0
  1783. ) {
  1784. abort(400, 'Invalid media_ids');
  1785. }
  1786. $status = new Status;
  1787. $status->caption = strip_tags($request->input('status'));
  1788. $status->profile_id = $user->profile_id;
  1789. $status->scope = 'draft';
  1790. $status->is_nsfw = $user->profile->cw == true ? true : $request->input('sensitive', false);
  1791. $status->save();
  1792. $mimes = [];
  1793. foreach($ids as $k => $v) {
  1794. if($k + 1 > config_cache('pixelfed.max_album_length')) {
  1795. continue;
  1796. }
  1797. $m = Media::whereUserId($user->id)->whereNull('status_id')->findOrFail($v);
  1798. if($m->profile_id !== $user->profile_id || $m->status_id) {
  1799. abort(403, 'Invalid media id');
  1800. }
  1801. $m->status_id = $status->id;
  1802. $m->save();
  1803. array_push($mimes, $m->mime);
  1804. }
  1805. if(empty($mimes)) {
  1806. $status->delete();
  1807. abort(400, 'Invalid media ids');
  1808. }
  1809. $status->scope = $visibility;
  1810. $status->visibility = $visibility;
  1811. $status->type = StatusController::mimeTypeCheck($mimes);
  1812. $status->save();
  1813. }
  1814. if(!$status) {
  1815. abort(500, 'An error occured.');
  1816. }
  1817. NewStatusPipeline::dispatch($status);
  1818. Cache::forget('user:account:id:'.$user->id);
  1819. Cache::forget('_api:statuses:recent_9:'.$user->profile_id);
  1820. Cache::forget('profile:status_count:'.$user->profile_id);
  1821. Cache::forget($user->storageUsedKey());
  1822. Cache::forget('profile:embed:' . $status->profile_id);
  1823. Cache::forget($limitKey);
  1824. $resource = new Fractal\Resource\Item($status, new StatusTransformer());
  1825. $res = $this->fractal->createData($resource)->toArray();
  1826. return response()->json($res);
  1827. }
  1828. /**
  1829. * DELETE /api/v1/statuses
  1830. *
  1831. * @param integer $id
  1832. *
  1833. * @return null
  1834. */
  1835. public function statusDelete(Request $request, $id)
  1836. {
  1837. abort_if(!$request->user(), 403);
  1838. $status = Status::whereProfileId($request->user()->profile->id)
  1839. ->findOrFail($id);
  1840. $resource = new Fractal\Resource\Item($status, new StatusTransformer());
  1841. Cache::forget('profile:status_count:'.$status->profile_id);
  1842. StatusDelete::dispatch($status);
  1843. $res = $this->fractal->createData($resource)->toArray();
  1844. $res['text'] = $res['content'];
  1845. unset($res['content']);
  1846. return response()->json($res);
  1847. }
  1848. /**
  1849. * POST /api/v1/statuses/{id}/reblog
  1850. *
  1851. * @param integer $id
  1852. *
  1853. * @return StatusTransformer
  1854. */
  1855. public function statusShare(Request $request, $id)
  1856. {
  1857. abort_if(!$request->user(), 403);
  1858. $user = $request->user();
  1859. $status = Status::findOrFail($id);
  1860. if($status->profile_id !== $user->profile_id) {
  1861. if($status->scope == 'private') {
  1862. abort_if(!$status->profile->followedBy($user->profile), 403);
  1863. } else {
  1864. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  1865. }
  1866. }
  1867. $share = Status::firstOrCreate([
  1868. 'profile_id' => $user->profile_id,
  1869. 'reblog_of_id' => $status->id,
  1870. 'in_reply_to_profile_id' => $status->profile_id,
  1871. 'scope' => 'public',
  1872. 'visibility' => 'public'
  1873. ]);
  1874. if($share->wasRecentlyCreated == true) {
  1875. SharePipeline::dispatch($share);
  1876. }
  1877. StatusService::del($status->id);
  1878. $resource = new Fractal\Resource\Item($status, new StatusTransformer());
  1879. $res = $this->fractal->createData($resource)->toArray();
  1880. return response()->json($res);
  1881. }
  1882. /**
  1883. * POST /api/v1/statuses/{id}/unreblog
  1884. *
  1885. * @param integer $id
  1886. *
  1887. * @return StatusTransformer
  1888. */
  1889. public function statusUnshare(Request $request, $id)
  1890. {
  1891. abort_if(!$request->user(), 403);
  1892. $user = $request->user();
  1893. $status = Status::findOrFail($id);
  1894. if($status->profile_id !== $user->profile_id) {
  1895. if($status->scope == 'private') {
  1896. abort_if(!$status->profile->followedBy($user->profile), 403);
  1897. } else {
  1898. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  1899. }
  1900. }
  1901. $reblog = Status::whereProfileId($user->profile_id)
  1902. ->whereReblogOfId($status->id)
  1903. ->first();
  1904. if(!$reblog) {
  1905. $resource = new Fractal\Resource\Item($status, new StatusTransformer());
  1906. $res = $this->fractal->createData($resource)->toArray();
  1907. return response()->json($res);
  1908. }
  1909. UndoSharePipeline::dispatch($reblog);
  1910. $resource = new Fractal\Resource\Item($status, new StatusTransformer());
  1911. $res = $this->fractal->createData($resource)->toArray();
  1912. return response()->json($res);
  1913. }
  1914. /**
  1915. * GET /api/v1/timelines/tag/{hashtag}
  1916. *
  1917. * @param string $hashtag
  1918. *
  1919. * @return StatusTransformer
  1920. */
  1921. public function timelineHashtag(Request $request, $hashtag)
  1922. {
  1923. $this->validate($request,[
  1924. 'page' => 'nullable|integer|max:40',
  1925. 'min_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  1926. 'max_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  1927. 'limit' => 'nullable|integer|max:40'
  1928. ]);
  1929. $tag = Hashtag::whereName($hashtag)
  1930. ->orWhere('slug', $hashtag)
  1931. ->first();
  1932. if(!$tag) {
  1933. return response()->json([]);
  1934. }
  1935. $min = $request->input('min_id');
  1936. $max = $request->input('max_id');
  1937. $limit = $request->input('limit', 20);
  1938. if(!$min && !$max) {
  1939. $id = 1;
  1940. $dir = '>';
  1941. } else {
  1942. $dir = $min ? '>' : '<';
  1943. $id = $min ?? $max;
  1944. }
  1945. $res = StatusHashtag::whereHashtagId($tag->id)
  1946. ->whereStatusVisibility('public')
  1947. ->whereHas('media')
  1948. ->where('status_id', $dir, $id)
  1949. ->latest()
  1950. ->limit($limit)
  1951. ->pluck('status_id')
  1952. ->filter(function($i) {
  1953. return StatusService::get($i);
  1954. })
  1955. ->map(function ($i) {
  1956. return StatusService::get($i);
  1957. })
  1958. ->filter()
  1959. ->values()
  1960. ->toArray();
  1961. return response()->json($res, 200, [], JSON_PRETTY_PRINT);
  1962. }
  1963. /**
  1964. * GET /api/v1/bookmarks
  1965. *
  1966. *
  1967. *
  1968. * @return StatusTransformer
  1969. */
  1970. public function bookmarks(Request $request)
  1971. {
  1972. abort_if(!$request->user(), 403);
  1973. $this->validate($request, [
  1974. 'limit' => 'nullable|integer|min:1|max:40',
  1975. 'max_id' => 'nullable|integer|min:0',
  1976. 'since_id' => 'nullable|integer|min:0',
  1977. 'min_id' => 'nullable|integer|min:0'
  1978. ]);
  1979. $pid = $request->user()->profile_id;
  1980. $limit = $request->input('limit') ?? 20;
  1981. $max_id = $request->input('max_id');
  1982. $since_id = $request->input('since_id');
  1983. $min_id = $request->input('min_id');
  1984. $dir = $min_id ? '>' : '<';
  1985. $id = $min_id ?? $max_id;
  1986. if($id) {
  1987. $bookmarks = Bookmark::whereProfileId($pid)
  1988. ->where('status_id', $dir, $id)
  1989. ->limit($limit)
  1990. ->pluck('status_id');
  1991. } else {
  1992. $bookmarks = Bookmark::whereProfileId($pid)
  1993. ->latest()
  1994. ->limit($limit)
  1995. ->pluck('status_id');
  1996. }
  1997. $res = [];
  1998. foreach($bookmarks as $id) {
  1999. $res[] = \App\Services\StatusService::get($id);
  2000. }
  2001. return $res;
  2002. }
  2003. /**
  2004. * POST /api/v1/statuses/{id}/bookmark
  2005. *
  2006. *
  2007. *
  2008. * @return StatusTransformer
  2009. */
  2010. public function bookmarkStatus(Request $request, $id)
  2011. {
  2012. abort_if(!$request->user(), 403);
  2013. $status = Status::whereNull('uri')
  2014. ->whereScope('public')
  2015. ->findOrFail($id);
  2016. Bookmark::firstOrCreate([
  2017. 'status_id' => $status->id,
  2018. 'profile_id' => $request->user()->profile_id
  2019. ]);
  2020. $resource = new Fractal\Resource\Item($status, new StatusTransformer());
  2021. $res = $this->fractal->createData($resource)->toArray();
  2022. return response()->json($res);
  2023. }
  2024. /**
  2025. * POST /api/v1/statuses/{id}/unbookmark
  2026. *
  2027. *
  2028. *
  2029. * @return StatusTransformer
  2030. */
  2031. public function unbookmarkStatus(Request $request, $id)
  2032. {
  2033. abort_if(!$request->user(), 403);
  2034. $status = Status::whereNull('uri')
  2035. ->whereScope('public')
  2036. ->findOrFail($id);
  2037. Bookmark::firstOrCreate([
  2038. 'status_id' => $status->id,
  2039. 'profile_id' => $request->user()->profile_id
  2040. ]);
  2041. $bookmark = Bookmark::whereStatusId($status->id)
  2042. ->whereProfileId($request->user()->profile_id)
  2043. ->firstOrFail();
  2044. $bookmark->delete();
  2045. $resource = new Fractal\Resource\Item($status, new StatusTransformer());
  2046. $res = $this->fractal->createData($resource)->toArray();
  2047. return response()->json($res);
  2048. }
  2049. /**
  2050. * GET /api/v2/search
  2051. *
  2052. *
  2053. * @return array
  2054. */
  2055. public function searchV2(Request $request)
  2056. {
  2057. abort_if(!$request->user(), 403);
  2058. $this->validate($request, [
  2059. 'q' => 'required|string|min:1|max:80',
  2060. 'account_id' => 'nullable|string',
  2061. 'max_id' => 'nullable|string',
  2062. 'min_id' => 'nullable|string',
  2063. 'type' => 'nullable|in:accounts,hashtags,statuses',
  2064. 'exclude_unreviewed' => 'nullable',
  2065. 'resolve' => 'nullable',
  2066. 'limit' => 'nullable|integer|max:40',
  2067. 'offset' => 'nullable|integer',
  2068. 'following' => 'nullable'
  2069. ]);
  2070. return SearchApiV2Service::query($request);
  2071. }
  2072. /**
  2073. * GET /api/v1/discover/posts
  2074. *
  2075. *
  2076. * @return array
  2077. */
  2078. public function discoverPosts(Request $request)
  2079. {
  2080. abort_if(!$request->user(), 403);
  2081. $this->validate($request, [
  2082. 'limit' => 'integer|min:1|max:40'
  2083. ]);
  2084. $limit = $request->input('limit', 40);
  2085. $profile = Auth::user()->profile;
  2086. $pid = $profile->id;
  2087. $following = Cache::remember('feature:discover:following:'.$pid, now()->addMinutes(15), function() use ($pid) {
  2088. return Follower::whereProfileId($pid)->pluck('following_id')->toArray();
  2089. });
  2090. $filters = Cache::remember("user:filter:list:$pid", now()->addMinutes(15), function() use($pid) {
  2091. $private = Profile::whereIsPrivate(true)
  2092. ->orWhere('unlisted', true)
  2093. ->orWhere('status', '!=', null)
  2094. ->pluck('id')
  2095. ->toArray();
  2096. $filters = UserFilter::whereUserId($pid)
  2097. ->whereFilterableType('App\Profile')
  2098. ->whereIn('filter_type', ['mute', 'block'])
  2099. ->pluck('filterable_id')
  2100. ->toArray();
  2101. return array_merge($private, $filters);
  2102. });
  2103. $following = array_merge($following, $filters);
  2104. $sql = config('database.default') !== 'pgsql';
  2105. $min_id = SnowflakeService::byDate(now()->subMonths(3));
  2106. $res = Status::select(
  2107. 'id',
  2108. 'is_nsfw',
  2109. 'profile_id',
  2110. 'type',
  2111. 'uri',
  2112. )
  2113. ->whereNull('uri')
  2114. ->whereIn('type', ['photo','photo:album', 'video'])
  2115. ->whereIsNsfw(false)
  2116. ->whereVisibility('public')
  2117. ->whereNotIn('profile_id', $following)
  2118. ->where('id', '>', $min_id)
  2119. ->inRandomOrder()
  2120. ->take($limit)
  2121. ->pluck('id')
  2122. ->map(function($post) {
  2123. return StatusService::get($post);
  2124. })
  2125. ->filter(function($post) {
  2126. return $post && isset($post['id']);
  2127. })
  2128. ->values()
  2129. ->toArray();
  2130. return response()->json($res);
  2131. }
  2132. }