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