ApiV1Controller.php 76 KB

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