ApiV1Controller.php 67 KB

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