ApiV1Controller.php 158 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536
  1. <?php
  2. namespace App\Http\Controllers\Api;
  3. use App\Avatar;
  4. use App\Bookmark;
  5. use App\Collection;
  6. use App\CollectionItem;
  7. use App\DirectMessage;
  8. use App\Follower;
  9. use App\FollowRequest;
  10. use App\Hashtag;
  11. use App\Http\Controllers\AccountController;
  12. use App\Http\Controllers\Controller;
  13. use App\Http\Controllers\FollowerController;
  14. use App\Http\Controllers\StatusController;
  15. use App\Instance;
  16. use App\Jobs\AvatarPipeline\AvatarOptimize;
  17. use App\Jobs\CommentPipeline\CommentPipeline;
  18. use App\Jobs\FollowPipeline\FollowAcceptPipeline;
  19. use App\Jobs\FollowPipeline\FollowPipeline;
  20. use App\Jobs\FollowPipeline\FollowRejectPipeline;
  21. use App\Jobs\FollowPipeline\UnfollowPipeline;
  22. use App\Jobs\HomeFeedPipeline\FeedWarmCachePipeline;
  23. use App\Jobs\ImageOptimizePipeline\ImageOptimize;
  24. use App\Jobs\LikePipeline\LikePipeline;
  25. use App\Jobs\MediaPipeline\MediaDeletePipeline;
  26. use App\Jobs\MediaPipeline\MediaSyncLicensePipeline;
  27. use App\Jobs\NotificationPipeline\NotificationWarmUserCache;
  28. use App\Jobs\SharePipeline\SharePipeline;
  29. use App\Jobs\SharePipeline\UndoSharePipeline;
  30. use App\Jobs\StatusPipeline\NewStatusPipeline;
  31. use App\Jobs\StatusPipeline\StatusDelete;
  32. use App\Jobs\VideoPipeline\VideoThumbnail;
  33. use App\Like;
  34. use App\Media;
  35. use App\Models\Conversation;
  36. use App\Models\CustomFilter;
  37. use App\Notification;
  38. use App\Profile;
  39. use App\Services\AccountService;
  40. use App\Services\AdminShadowFilterService;
  41. use App\Services\BookmarkService;
  42. use App\Services\BouncerService;
  43. use App\Services\CollectionService;
  44. use App\Services\CustomEmojiService;
  45. use App\Services\DiscoverService;
  46. use App\Services\FollowerService;
  47. use App\Services\HomeTimelineService;
  48. use App\Services\InstanceService;
  49. use App\Services\LikeService;
  50. use App\Services\MarkerService;
  51. use App\Services\MediaBlocklistService;
  52. use App\Services\MediaPathService;
  53. use App\Services\MediaService;
  54. use App\Services\NetworkTimelineService;
  55. use App\Services\NotificationService;
  56. use App\Services\PublicTimelineService;
  57. use App\Services\ReblogService;
  58. use App\Services\RelationshipService;
  59. use App\Services\SnowflakeService;
  60. use App\Services\StatusService;
  61. use App\Services\UserFilterService;
  62. use App\Services\UserRoleService;
  63. use App\Services\UserStorageService;
  64. use App\Status;
  65. use App\StatusHashtag;
  66. use App\Transformer\Api\Mastodon\v1\AccountTransformer;
  67. use App\Transformer\Api\Mastodon\v1\MediaTransformer;
  68. use App\Transformer\Api\Mastodon\v1\NotificationTransformer;
  69. use App\Transformer\Api\Mastodon\v1\StatusTransformer;
  70. use App\Transformer\Api\RelationshipTransformer;
  71. use App\User;
  72. use App\UserFilter;
  73. use App\UserSetting;
  74. use App\Util\Lexer\Autolink;
  75. use App\Util\Lexer\PrettyNumber;
  76. use App\Util\Localization\Localization;
  77. use App\Util\Media\Filter;
  78. use App\Util\Media\License;
  79. use Cache;
  80. use Carbon\Carbon;
  81. use DB;
  82. use Illuminate\Http\Request;
  83. use Illuminate\Support\Facades\RateLimiter;
  84. use Illuminate\Support\Str;
  85. use Laravel\Passport\Passport;
  86. use League\Fractal;
  87. use League\Fractal\Serializer\ArraySerializer;
  88. use Purify;
  89. use Storage;
  90. class ApiV1Controller extends Controller
  91. {
  92. protected $fractal;
  93. const PF_API_ENTITY_KEY = '_pe';
  94. public function __construct()
  95. {
  96. $this->fractal = new Fractal\Manager;
  97. $this->fractal->setSerializer(new ArraySerializer);
  98. }
  99. public function json($res, $code = 200, $headers = [])
  100. {
  101. return response()->json($res, $code, $headers, JSON_UNESCAPED_SLASHES);
  102. }
  103. /**
  104. * GET /api/v1/apps/verify_credentials
  105. */
  106. public function getApp(Request $request)
  107. {
  108. // FIXME: /api/v1/apps/verify_credentials should be accessible with any
  109. // valid Access Token, not just a user's access token (i.e., client
  110. // credentails grant flow access tokens)
  111. abort_if(! $request->user() || ! $request->user()->token(), 403);
  112. $client = $request->user()->token()->client;
  113. $res = [
  114. 'name' => $client->name,
  115. 'website' => null,
  116. 'vapid_key' => null,
  117. ];
  118. return $this->json($res);
  119. }
  120. /**
  121. * POST /api/v1/apps
  122. */
  123. public function apps(Request $request)
  124. {
  125. abort_if(! (bool) config_cache('pixelfed.oauth_enabled'), 404);
  126. $this->validate($request, [
  127. 'client_name' => 'required',
  128. 'redirect_uris' => 'required',
  129. ]);
  130. $uris = collect(explode("\n", $request->redirect_uris))
  131. ->map('urldecode')
  132. ->filter()
  133. ->join(',');
  134. $client = Passport::client()->forceFill([
  135. 'user_id' => null,
  136. 'name' => e($request->client_name),
  137. 'secret' => Str::random(40),
  138. 'redirect' => $uris,
  139. 'personal_access_client' => false,
  140. 'password_client' => false,
  141. 'revoked' => false,
  142. ]);
  143. $client->save();
  144. $res = [
  145. 'id' => (string) $client->id,
  146. 'name' => $client->name,
  147. 'website' => null,
  148. 'redirect_uri' => $client->redirect,
  149. 'client_id' => (string) $client->id,
  150. 'client_secret' => $client->secret,
  151. 'vapid_key' => null,
  152. ];
  153. return $this->json($res, 200, [
  154. 'Access-Control-Allow-Origin' => '*',
  155. ]);
  156. }
  157. /**
  158. * GET /api/v1/accounts/verify_credentials
  159. *
  160. *
  161. * @return \App\Transformer\Api\AccountTransformer
  162. */
  163. public function verifyCredentials(Request $request)
  164. {
  165. abort_if(! $request->user() || ! $request->user()->token(), 403);
  166. abort_unless($request->user()->tokenCan('read'), 403);
  167. $user = $request->user();
  168. abort_if($user->status != null, 403);
  169. AccountService::setLastActive($user->id);
  170. $res = $request->has(self::PF_API_ENTITY_KEY) ? AccountService::get($user->profile_id) : AccountService::getMastodon($user->profile_id);
  171. $res['source'] = [
  172. 'privacy' => $res['locked'] ? 'private' : 'public',
  173. 'sensitive' => false,
  174. 'language' => $user->language ?? 'en',
  175. 'note' => strip_tags($res['note']),
  176. 'fields' => [],
  177. ];
  178. if ($request->has(self::PF_API_ENTITY_KEY)) {
  179. $res['settings'] = AccountService::getAccountSettings($user->profile_id);
  180. }
  181. return $this->json($res);
  182. }
  183. /**
  184. * GET /api/v1/accounts/{id}
  185. *
  186. * @param int $id
  187. * @return \App\Transformer\Api\AccountTransformer
  188. */
  189. public function accountById(Request $request, $id)
  190. {
  191. abort_if(! $request->user() || ! $request->user()->token(), 403);
  192. abort_unless($request->user()->tokenCan('read'), 403);
  193. $withInstanceMeta = $request->has('_wim');
  194. $res = $request->has(self::PF_API_ENTITY_KEY) ? AccountService::get($id, true) : AccountService::getMastodon($id, true);
  195. if (! $res) {
  196. return response()->json(['error' => 'Record not found'], 404);
  197. }
  198. if ($res && strpos($res['acct'], '@') != -1) {
  199. $domain = parse_url($res['url'], PHP_URL_HOST);
  200. abort_if(in_array($domain, InstanceService::getBannedDomains()), 404);
  201. }
  202. return $this->json($res);
  203. }
  204. /**
  205. * PATCH /api/v1/accounts/update_credentials
  206. *
  207. * @return \App\Transformer\Api\AccountTransformer
  208. */
  209. public function accountUpdateCredentials(Request $request)
  210. {
  211. abort_if(! $request->user() || ! $request->user()->token(), 403);
  212. abort_unless($request->user()->tokenCan('write'), 403);
  213. if (config('pixelfed.bouncer.cloud_ips.ban_api')) {
  214. abort_if(BouncerService::checkIp($request->ip()), 404);
  215. }
  216. $this->validate($request, [
  217. 'avatar' => 'sometimes|mimetypes:image/jpeg,image/png|max:'.config('pixelfed.max_avatar_size'),
  218. 'display_name' => 'nullable|string|max:30',
  219. 'note' => 'nullable|string|max:200',
  220. 'locked' => 'nullable',
  221. 'website' => 'nullable|string|max:120',
  222. // 'source.privacy' => 'nullable|in:unlisted,public,private',
  223. // 'source.sensitive' => 'nullable|boolean'
  224. ], [
  225. 'required' => 'The :attribute field is required.',
  226. 'avatar.mimetypes' => 'The file must be in jpeg or png format',
  227. 'avatar.max' => 'The :attribute exceeds the file size limit of '.PrettyNumber::size(config('pixelfed.max_avatar_size'), true, false),
  228. ]);
  229. $user = $request->user();
  230. AccountService::setLastActive($user->id);
  231. $profile = $user->profile;
  232. $settings = $user->settings;
  233. $changes = false;
  234. $other = array_merge(AccountService::defaultSettings()['other'], $settings->other ?? []);
  235. $syncLicenses = false;
  236. $licenseChanged = false;
  237. $composeSettings = array_merge(AccountService::defaultSettings()['compose_settings'], $settings->compose_settings ?? []);
  238. if ($request->has('avatar')) {
  239. $av = Avatar::whereProfileId($profile->id)->first();
  240. if ($av) {
  241. $currentAvatar = storage_path('app/'.$av->media_path);
  242. $file = $request->file('avatar');
  243. $path = "public/avatars/{$profile->id}";
  244. $name = strtolower(str_random(6)).'.'.$file->guessExtension();
  245. $request->file('avatar')->storePubliclyAs($path, $name);
  246. $av->media_path = "{$path}/{$name}";
  247. $av->save();
  248. Cache::forget("avatar:{$profile->id}");
  249. Cache::forget('user:account:id:'.$user->id);
  250. AvatarOptimize::dispatch($user->profile, $currentAvatar);
  251. }
  252. $changes = true;
  253. }
  254. if ($request->has('source[language]')) {
  255. $lang = $request->input('source[language]');
  256. if (in_array($lang, Localization::languages())) {
  257. $user->language = $lang;
  258. $changes = true;
  259. $other['language'] = $lang;
  260. }
  261. }
  262. if ($request->has('website')) {
  263. $website = $request->input('website');
  264. if ($website != $profile->website) {
  265. if ($website) {
  266. if (! strpos($website, '.')) {
  267. $website = null;
  268. }
  269. if ($website && ! strpos($website, '://')) {
  270. $website = 'https://'.$website;
  271. }
  272. $host = parse_url($website, PHP_URL_HOST);
  273. $bannedInstances = InstanceService::getBannedDomains();
  274. if (in_array($host, $bannedInstances)) {
  275. $website = null;
  276. }
  277. }
  278. $profile->website = $website ? $website : null;
  279. $changes = true;
  280. }
  281. }
  282. if ($request->has('display_name')) {
  283. $displayName = $request->input('display_name');
  284. if ($displayName !== $user->name) {
  285. $user->name = $displayName;
  286. $profile->name = $displayName;
  287. $changes = true;
  288. }
  289. }
  290. if ($request->has('note')) {
  291. $note = $request->input('note');
  292. if ($note !== strip_tags($profile->bio)) {
  293. $profile->bio = Autolink::create()->autolink(strip_tags($note));
  294. $changes = true;
  295. }
  296. }
  297. if ($request->has('locked')) {
  298. $locked = $request->boolean('locked');
  299. if ($profile->is_private != $locked) {
  300. $profile->is_private = $locked;
  301. $changes = true;
  302. }
  303. }
  304. if ($request->has('reduce_motion')) {
  305. $reduced = $request->boolean('reduce_motion');
  306. if ($settings->reduce_motion != $reduced) {
  307. $settings->reduce_motion = $reduced;
  308. $changes = true;
  309. }
  310. }
  311. if ($request->has('high_contrast_mode')) {
  312. $contrast = $request->boolean('high_contrast_mode');
  313. if ($settings->high_contrast_mode != $contrast) {
  314. $settings->high_contrast_mode = $contrast;
  315. $changes = true;
  316. }
  317. }
  318. if ($request->has('video_autoplay')) {
  319. $autoplay = $request->boolean('video_autoplay');
  320. if ($settings->video_autoplay != $autoplay) {
  321. $settings->video_autoplay = $autoplay;
  322. $changes = true;
  323. }
  324. }
  325. if ($request->has('license')) {
  326. $license = $request->input('license');
  327. abort_if(! in_array($license, License::keys()), 422, 'Invalid media license id');
  328. $syncLicenses = $request->input('sync_licenses') == true;
  329. abort_if($syncLicenses && Cache::get('pf:settings:mls_recently:'.$user->id) == 2, 422, 'You can only sync licenses twice per 24 hours');
  330. if ($composeSettings['default_license'] != $license) {
  331. $composeSettings['default_license'] = $license;
  332. $licenseChanged = true;
  333. $changes = true;
  334. }
  335. }
  336. if ($request->has('media_descriptions')) {
  337. $md = $request->boolean('media_descriptions');
  338. if ($composeSettings['media_descriptions'] != $md) {
  339. $composeSettings['media_descriptions'] = $md;
  340. $changes = true;
  341. }
  342. }
  343. if ($request->has('crawlable')) {
  344. $crawlable = $request->boolean('crawlable');
  345. if ($settings->crawlable != $crawlable) {
  346. $settings->crawlable = $crawlable;
  347. $changes = true;
  348. }
  349. }
  350. if ($request->has('show_profile_follower_count')) {
  351. $show_profile_follower_count = $request->boolean('show_profile_follower_count');
  352. if ($settings->show_profile_follower_count != $show_profile_follower_count) {
  353. $settings->show_profile_follower_count = $show_profile_follower_count;
  354. $changes = true;
  355. Cache::forget('pf:acct-trans:hideFollowers:'.$profile->id);
  356. }
  357. }
  358. if ($request->has('show_profile_following_count')) {
  359. $show_profile_following_count = $request->boolean('show_profile_following_count');
  360. if ($settings->show_profile_following_count != $show_profile_following_count) {
  361. $settings->show_profile_following_count = $show_profile_following_count;
  362. $changes = true;
  363. Cache::forget('pf:acct-trans:hideFollowing:'.$profile->id);
  364. }
  365. }
  366. if ($request->has('public_dm')) {
  367. $public_dm = $request->boolean('public_dm');
  368. if ($settings->public_dm != $public_dm) {
  369. $settings->public_dm = $public_dm;
  370. $changes = true;
  371. }
  372. }
  373. if ($request->has('source[privacy]')) {
  374. $scope = $request->input('source[privacy]');
  375. if (in_array($scope, ['public', 'private', 'unlisted'])) {
  376. if ($composeSettings['default_scope'] != $scope) {
  377. $composeSettings['default_scope'] = $profile->is_private ? 'private' : $scope;
  378. $changes = true;
  379. }
  380. }
  381. }
  382. if ($request->has('disable_embeds')) {
  383. $disabledEmbeds = $request->boolean('disable_embeds');
  384. if ($other['disable_embeds'] != $disabledEmbeds) {
  385. $other['disable_embeds'] = $disabledEmbeds;
  386. $changes = true;
  387. }
  388. }
  389. if ($changes) {
  390. $settings->other = $other;
  391. $settings->compose_settings = $composeSettings;
  392. $settings->save();
  393. $user->save();
  394. $profile->save();
  395. Cache::forget('profile:settings:'.$profile->id);
  396. Cache::forget('user:account:id:'.$profile->user_id);
  397. Cache::forget('profile:follower_count:'.$profile->id);
  398. Cache::forget('profile:following_count:'.$profile->id);
  399. Cache::forget('profile:embed:'.$profile->id);
  400. Cache::forget('profile:compose:settings:'.$user->id);
  401. Cache::forget('profile:view:'.$profile->username);
  402. Cache::forget('profile:atom:enabled:'.$profile->id);
  403. Cache::forget('pfc:cached-user:wt:'.strtolower($profile->username));
  404. Cache::forget('pfc:cached-user:wot:'.strtolower($profile->username));
  405. Cache::forget('pf:acct:settings:hidden-followers:'.$profile->id);
  406. Cache::forget('pf:acct:settings:hidden-following:'.$profile->id);
  407. Cache::forget('pf:acct-trans:hideFollowing:'.$profile->id);
  408. Cache::forget('pf:acct-trans:hideFollowers:'.$profile->id);
  409. AccountService::del($user->profile_id);
  410. AccountService::forgetAccountSettings($profile->id);
  411. }
  412. if ($syncLicenses && $licenseChanged) {
  413. $key = 'pf:settings:mls_recently:'.$user->id;
  414. $val = Cache::has($key) ? 2 : 1;
  415. Cache::put($key, $val, 86400);
  416. MediaSyncLicensePipeline::dispatch($user->id, $request->input('license'));
  417. }
  418. if ($request->has(self::PF_API_ENTITY_KEY)) {
  419. $res = AccountService::get($user->profile_id, true);
  420. } else {
  421. $res = AccountService::getMastodon($user->profile_id, true);
  422. $res['bio'] = strip_tags($res['note']);
  423. $res = array_merge($res, $other);
  424. }
  425. return $this->json($res);
  426. }
  427. /**
  428. * GET /api/v1/accounts/{id}/followers
  429. *
  430. * @param int $id
  431. * @return \App\Transformer\Api\AccountTransformer
  432. */
  433. public function accountFollowersById(Request $request, $id)
  434. {
  435. abort_if(! $request->user() || ! $request->user()->token(), 403);
  436. abort_unless($request->user()->tokenCan('read'), 403);
  437. $account = AccountService::get($id);
  438. abort_if(! $account, 404);
  439. abort_if(isset($account['moved'], $account['moved']['id']), 404, 'Account moved');
  440. $pid = $request->user()->profile_id;
  441. $this->validate($request, [
  442. 'limit' => 'sometimes|integer|min:1',
  443. ]);
  444. $limit = $request->input('limit', 10);
  445. if ($limit > 80) {
  446. $limit = 80;
  447. }
  448. $napi = $request->has(self::PF_API_ENTITY_KEY);
  449. if ($account && strpos($account['acct'], '@') != -1) {
  450. $domain = parse_url($account['url'], PHP_URL_HOST);
  451. abort_if(in_array($domain, InstanceService::getBannedDomains()), 404);
  452. }
  453. if (intval($pid) !== intval($account['id'])) {
  454. if ($account['locked']) {
  455. if (! FollowerService::follows($pid, $account['id'])) {
  456. return [];
  457. }
  458. }
  459. if (AccountService::hiddenFollowers($id)) {
  460. return [];
  461. }
  462. if ($request->has('page') && $request->user()->is_admin == false) {
  463. $page = (int) $request->input('page');
  464. if (($page * $limit) >= 100) {
  465. return [];
  466. }
  467. }
  468. }
  469. if ($request->has('page')) {
  470. $res = DB::table('followers')
  471. ->select('id', 'profile_id', 'following_id')
  472. ->whereFollowingId($account['id'])
  473. ->orderByDesc('id')
  474. ->simplePaginate($limit)
  475. ->map(function ($follower) use ($napi) {
  476. return $napi ? AccountService::get($follower->profile_id, true) : AccountService::getMastodon($follower->profile_id, true);
  477. })
  478. ->filter(function ($account) {
  479. return $account && isset($account['id']);
  480. })
  481. ->values()
  482. ->toArray();
  483. return $this->json($res);
  484. }
  485. $paginator = DB::table('followers')
  486. ->select('id', 'profile_id', 'following_id')
  487. ->whereFollowingId($account['id'])
  488. ->orderByDesc('id')
  489. ->cursorPaginate($limit)
  490. ->withQueryString();
  491. $link = null;
  492. if ($paginator->onFirstPage()) {
  493. if ($paginator->hasMorePages()) {
  494. $link = '<'.$paginator->nextPageUrl().'>; rel="prev"';
  495. }
  496. } else {
  497. if ($paginator->previousPageUrl()) {
  498. $link = '<'.$paginator->previousPageUrl().'>; rel="next"';
  499. }
  500. if ($paginator->hasMorePages()) {
  501. $link .= ($link ? ', ' : '').'<'.$paginator->nextPageUrl().'>; rel="prev"';
  502. }
  503. }
  504. $res = $paginator->map(function ($follower) use ($napi) {
  505. return $napi ? AccountService::get($follower->profile_id, true) : AccountService::getMastodon($follower->profile_id, true);
  506. })
  507. ->filter(function ($account) {
  508. return $account && isset($account['id']);
  509. })
  510. ->values()
  511. ->toArray();
  512. $headers = isset($link) ? ['Link' => $link] : [];
  513. return $this->json($res, 200, $headers);
  514. }
  515. /**
  516. * GET /api/v1/accounts/{id}/following
  517. *
  518. * @param int $id
  519. * @return \App\Transformer\Api\AccountTransformer
  520. */
  521. public function accountFollowingById(Request $request, $id)
  522. {
  523. abort_if(! $request->user() || ! $request->user()->token(), 403);
  524. abort_unless($request->user()->tokenCan('read'), 403);
  525. $account = AccountService::get($id);
  526. abort_if(! $account, 404);
  527. abort_if(isset($account['moved'], $account['moved']['id']), 404, 'Account moved');
  528. $pid = $request->user()->profile_id;
  529. $this->validate($request, [
  530. 'limit' => 'sometimes|integer|min:1',
  531. ]);
  532. $limit = $request->input('limit', 10);
  533. if ($limit > 80) {
  534. $limit = 80;
  535. }
  536. $napi = $request->has(self::PF_API_ENTITY_KEY);
  537. if ($account && strpos($account['acct'], '@') != -1) {
  538. $domain = parse_url($account['url'], PHP_URL_HOST);
  539. abort_if(in_array($domain, InstanceService::getBannedDomains()), 404);
  540. }
  541. if (intval($pid) !== intval($account['id'])) {
  542. if ($account['locked']) {
  543. if (! FollowerService::follows($pid, $account['id'])) {
  544. return [];
  545. }
  546. }
  547. if (AccountService::hiddenFollowing($id)) {
  548. return [];
  549. }
  550. if ($request->has('page') && $request->user()->is_admin == false) {
  551. $page = (int) $request->input('page');
  552. if (($page * $limit) >= 100) {
  553. return [];
  554. }
  555. }
  556. }
  557. if ($request->has('page')) {
  558. $res = DB::table('followers')
  559. ->select('id', 'profile_id', 'following_id')
  560. ->whereProfileId($account['id'])
  561. ->orderByDesc('id')
  562. ->simplePaginate($limit)
  563. ->map(function ($follower) use ($napi) {
  564. return $napi ? AccountService::get($follower->following_id, true) : AccountService::getMastodon($follower->following_id, true);
  565. })
  566. ->filter(function ($account) {
  567. return $account && isset($account['id']);
  568. })
  569. ->values()
  570. ->toArray();
  571. return $this->json($res);
  572. }
  573. $paginator = DB::table('followers')
  574. ->select('id', 'profile_id', 'following_id')
  575. ->whereProfileId($account['id'])
  576. ->orderByDesc('id')
  577. ->cursorPaginate($limit)
  578. ->withQueryString();
  579. $link = null;
  580. if ($paginator->onFirstPage()) {
  581. if ($paginator->hasMorePages()) {
  582. $link = '<'.$paginator->nextPageUrl().'>; rel="prev"';
  583. }
  584. } else {
  585. if ($paginator->previousPageUrl()) {
  586. $link = '<'.$paginator->previousPageUrl().'>; rel="next"';
  587. }
  588. if ($paginator->hasMorePages()) {
  589. $link .= ($link ? ', ' : '').'<'.$paginator->nextPageUrl().'>; rel="prev"';
  590. }
  591. }
  592. $res = $paginator->map(function ($follower) use ($napi) {
  593. return $napi ? AccountService::get($follower->following_id, true) : AccountService::getMastodon($follower->following_id, true);
  594. })
  595. ->filter(function ($account) {
  596. return $account && isset($account['id']);
  597. })
  598. ->values()
  599. ->toArray();
  600. $headers = isset($link) ? ['Link' => $link] : [];
  601. return $this->json($res, 200, $headers);
  602. }
  603. /**
  604. * GET /api/v1/accounts/{id}/statuses
  605. *
  606. * @param int $id
  607. * @return \App\Transformer\Api\StatusTransformer
  608. */
  609. public function accountStatusesById(Request $request, $id)
  610. {
  611. abort_if(! $request->user() || ! $request->user()->token(), 403);
  612. abort_unless($request->user()->tokenCan('read'), 403);
  613. $user = $request->user();
  614. $this->validate($request, [
  615. 'only_media' => 'nullable',
  616. 'media_type' => 'sometimes|string|in:photo,video',
  617. 'pinned' => 'nullable',
  618. 'exclude_replies' => 'nullable',
  619. 'max_id' => 'nullable|integer|min:0|max:'.PHP_INT_MAX,
  620. 'since_id' => 'nullable|integer|min:0|max:'.PHP_INT_MAX,
  621. 'min_id' => 'nullable|integer|min:0|max:'.PHP_INT_MAX,
  622. 'limit' => 'nullable|integer|min:1',
  623. ]);
  624. $napi = $request->has(self::PF_API_ENTITY_KEY);
  625. $profile = $napi ? AccountService::get($id, true) : AccountService::getMastodon($id, true);
  626. if (! $profile || ! isset($profile['id']) || ! $user) {
  627. return $this->json(['error' => 'Account not found'], 404);
  628. }
  629. if ($profile && strpos($profile['acct'], '@') != -1) {
  630. $domain = parse_url($profile['url'], PHP_URL_HOST);
  631. abort_if(in_array($domain, InstanceService::getBannedDomains()), 404);
  632. }
  633. $limit = $request->input('limit') ?? 20;
  634. if ($limit > 40) {
  635. $limit = 40;
  636. }
  637. $max_id = $request->max_id;
  638. $min_id = $request->min_id;
  639. if (! $max_id && ! $min_id) {
  640. $min_id = 1;
  641. }
  642. $pid = $request->user()->profile_id;
  643. $scope = $request->only_media == true ?
  644. ['photo', 'photo:album', 'video', 'video:album'] :
  645. ['photo', 'photo:album', 'video', 'video:album', 'share', 'reply'];
  646. if ($request->only_media && $request->has('media_type')) {
  647. $mt = $request->input('media_type');
  648. if ($mt == 'video') {
  649. $scope = ['video', 'video:album'];
  650. }
  651. }
  652. if (intval($pid) === intval($profile['id'])) {
  653. $visibility = ['public', 'unlisted', 'private'];
  654. } elseif ($profile['locked']) {
  655. $following = FollowerService::follows($pid, $profile['id']);
  656. if (! $following) {
  657. return response()->json([]);
  658. }
  659. $visibility = ['public', 'unlisted', 'private'];
  660. } else {
  661. $following = FollowerService::follows($pid, $profile['id']);
  662. $visibility = $following ? ['public', 'unlisted', 'private'] : ['public', 'unlisted'];
  663. }
  664. $dir = $min_id ? '>' : '<';
  665. $id = $min_id ?? $max_id;
  666. $res = Status::select(
  667. 'profile_id',
  668. 'in_reply_to_id',
  669. 'reblog_of_id',
  670. 'type',
  671. 'id',
  672. 'scope',
  673. 'pinned_order'
  674. )
  675. ->whereProfileId($profile['id'])
  676. ->whereNull('in_reply_to_id')
  677. ->whereNull('reblog_of_id')
  678. ->whereIn('type', $scope)
  679. ->where('id', $dir, $id)
  680. ->whereIn('scope', $visibility)
  681. ->limit($limit)
  682. ->orderByDesc('id')
  683. ->get()
  684. ->map(function ($s) use ($user, $napi, $profile) {
  685. try {
  686. $status = $napi ? StatusService::get($s->id, false) : StatusService::getMastodon($s->id, false);
  687. } catch (\Exception $e) {
  688. return false;
  689. }
  690. if ($profile) {
  691. $status['account'] = $profile;
  692. }
  693. if ($user && $status) {
  694. $status['favourited'] = (bool) LikeService::liked($user->profile_id, $s->id);
  695. $status['reblogged'] = (bool) ReblogService::get($user->profile_id, $s->id);
  696. $status['bookmarked'] = (bool) BookmarkService::get($user->profile_id, $s->id);
  697. }
  698. return $status;
  699. })
  700. ->filter(function ($s) {
  701. return $s;
  702. })
  703. ->values();
  704. return $this->json($res);
  705. }
  706. /**
  707. * POST /api/v1/accounts/{id}/follow
  708. *
  709. * @param int $id
  710. * @return \App\Transformer\Api\RelationshipTransformer
  711. */
  712. public function accountFollowById(Request $request, $id)
  713. {
  714. abort_if(! $request->user() || ! $request->user()->token(), 403);
  715. abort_unless($request->user()->tokenCan('follow'), 403);
  716. $user = $request->user();
  717. abort_if($user->profile_id == $id, 400, 'Invalid profile');
  718. abort_if($user->has_roles && ! UserRoleService::can('can-follow', $user->id), 403, 'Invalid permissions for this action');
  719. AccountService::setLastActive($user->id);
  720. $target = Profile::whereNull('status')->findOrFail($id);
  721. abort_if($target && $target->moved_to_profile_id, 400, 'Cannot follow an account that has moved!');
  722. if ($target && $target->domain) {
  723. $domain = $target->domain;
  724. abort_if(in_array($domain, InstanceService::getBannedDomains()), 404);
  725. }
  726. $private = (bool) $target->is_private;
  727. $remote = (bool) $target->domain;
  728. $blocked = UserFilter::whereUserId($target->id)
  729. ->whereFilterType('block')
  730. ->whereFilterableId($user->profile_id)
  731. ->whereFilterableType('App\Profile')
  732. ->exists();
  733. if ($blocked == true) {
  734. abort(400, 'You cannot follow this user.');
  735. }
  736. $isFollowing = Follower::whereProfileId($user->profile_id)
  737. ->whereFollowingId($target->id)
  738. ->exists();
  739. // Following already, return empty relationship
  740. if ($isFollowing == true) {
  741. $res = RelationshipService::get($user->profile_id, $target->id) ?? [];
  742. return $this->json($res);
  743. }
  744. // Rate limits, max 7500 followers per account
  745. if ($user->profile->following_count && $user->profile->following_count >= Follower::MAX_FOLLOWING) {
  746. abort(400, 'You cannot follow more than '.Follower::MAX_FOLLOWING.' accounts');
  747. }
  748. if ($private == true) {
  749. $follow = FollowRequest::firstOrCreate([
  750. 'follower_id' => $user->profile_id,
  751. 'following_id' => $target->id,
  752. ]);
  753. if ($remote == true && config('federation.activitypub.remoteFollow') == true) {
  754. (new FollowerController)->sendFollow($user->profile, $target);
  755. }
  756. } elseif ($remote == true) {
  757. $follow = FollowRequest::firstOrCreate([
  758. 'follower_id' => $user->profile_id,
  759. 'following_id' => $target->id,
  760. ]);
  761. if (config('federation.activitypub.remoteFollow') == true) {
  762. (new FollowerController)->sendFollow($user->profile, $target);
  763. }
  764. } else {
  765. $follower = Follower::firstOrCreate([
  766. 'profile_id' => $user->profile_id,
  767. 'following_id' => $target->id,
  768. ]);
  769. FollowPipeline::dispatch($follower)->onQueue('high');
  770. }
  771. RelationshipService::refresh($user->profile_id, $target->id);
  772. Cache::forget('profile:following:'.$target->id);
  773. Cache::forget('profile:followers:'.$target->id);
  774. Cache::forget('profile:following:'.$user->profile_id);
  775. Cache::forget('profile:followers:'.$user->profile_id);
  776. Cache::forget('api:local:exp:rec:'.$user->profile_id);
  777. Cache::forget('user:account:id:'.$target->user_id);
  778. Cache::forget('user:account:id:'.$user->id);
  779. Cache::forget('profile:follower_count:'.$target->id);
  780. Cache::forget('profile:follower_count:'.$user->profile_id);
  781. Cache::forget('profile:following_count:'.$target->id);
  782. Cache::forget('profile:following_count:'.$user->profile_id);
  783. AccountService::del($user->profile_id);
  784. AccountService::del($target->id);
  785. $res = RelationshipService::get($user->profile_id, $target->id);
  786. return $this->json($res);
  787. }
  788. /**
  789. * POST /api/v1/accounts/{id}/unfollow
  790. *
  791. * @param int $id
  792. * @return \App\Transformer\Api\RelationshipTransformer
  793. */
  794. public function accountUnfollowById(Request $request, $id)
  795. {
  796. abort_if(! $request->user() || ! $request->user()->token(), 403);
  797. abort_unless($request->user()->tokenCan('follow'), 403);
  798. $user = $request->user();
  799. abort_if($user->profile_id == $id, 400, 'Invalid profile');
  800. AccountService::setLastActive($user->id);
  801. $target = Profile::whereNull('status')
  802. ->findOrFail($id);
  803. $private = (bool) $target->is_private;
  804. $remote = (bool) $target->domain;
  805. $isFollowing = Follower::whereProfileId($user->profile_id)
  806. ->whereFollowingId($target->id)
  807. ->exists();
  808. if ($isFollowing == false) {
  809. $followRequest = FollowRequest::whereFollowerId($user->profile_id)
  810. ->whereFollowingId($target->id)
  811. ->first();
  812. if ($followRequest) {
  813. $followRequest->delete();
  814. RelationshipService::refresh($target->id, $user->profile_id);
  815. if ($target->domain) {
  816. UnfollowPipeline::dispatch($user->profile_id, $target->id)->onQueue('high');
  817. }
  818. }
  819. $resource = new Fractal\Resource\Item($target, new RelationshipTransformer);
  820. $res = $this->fractal->createData($resource)->toArray();
  821. return $this->json($res);
  822. }
  823. Follower::whereProfileId($user->profile_id)
  824. ->whereFollowingId($target->id)
  825. ->delete();
  826. UnfollowPipeline::dispatch($user->profile_id, $target->id)->onQueue('high');
  827. if ($remote == true && config('federation.activitypub.remoteFollow') == true) {
  828. (new FollowerController)->sendUndoFollow($user->profile, $target);
  829. }
  830. RelationshipService::refresh($user->profile_id, $target->id);
  831. Cache::forget('profile:following:'.$target->id);
  832. Cache::forget('profile:followers:'.$target->id);
  833. Cache::forget('profile:following:'.$user->profile_id);
  834. Cache::forget('profile:followers:'.$user->profile_id);
  835. Cache::forget('api:local:exp:rec:'.$user->profile_id);
  836. Cache::forget('user:account:id:'.$target->user_id);
  837. Cache::forget('user:account:id:'.$user->id);
  838. Cache::forget('profile:follower_count:'.$target->id);
  839. Cache::forget('profile:follower_count:'.$user->profile_id);
  840. Cache::forget('profile:following_count:'.$target->id);
  841. Cache::forget('profile:following_count:'.$user->profile_id);
  842. AccountService::del($user->profile_id);
  843. AccountService::del($target->id);
  844. $res = RelationshipService::get($user->profile_id, $target->id);
  845. return $this->json($res);
  846. }
  847. /**
  848. * GET /api/v1/accounts/relationships
  849. *
  850. * @param array|int $id
  851. * @return \App\Services\RelationshipService
  852. */
  853. public function accountRelationshipsById(Request $request)
  854. {
  855. abort_if(! $request->user(), 403);
  856. $this->validate($request, [
  857. 'id' => 'required|array|min:1',
  858. 'id.*' => 'required|integer|min:1|max:'.PHP_INT_MAX,
  859. ]);
  860. $ids = $request->input('id');
  861. if (count($ids) > 20) {
  862. $ids = collect($ids)->take(20)->toArray();
  863. }
  864. $napi = $request->has(self::PF_API_ENTITY_KEY);
  865. $pid = $request->user()->profile_id ?? $request->user()->profile->id;
  866. $res = collect($ids)
  867. ->map(function ($id) use ($pid, $napi) {
  868. if (intval($id) === intval($pid)) {
  869. return [
  870. 'id' => $id,
  871. 'following' => false,
  872. 'followed_by' => false,
  873. 'blocking' => false,
  874. 'muting' => false,
  875. 'muting_notifications' => false,
  876. 'requested' => false,
  877. 'domain_blocking' => false,
  878. 'showing_reblogs' => false,
  879. 'endorsed' => false,
  880. ];
  881. }
  882. return $napi ?
  883. RelationshipService::getWithDate($pid, $id) :
  884. RelationshipService::get($pid, $id);
  885. });
  886. return $this->json($res);
  887. }
  888. /**
  889. * GET /api/v1/accounts/search
  890. *
  891. *
  892. *
  893. * @return \App\Transformer\Api\AccountTransformer
  894. */
  895. public function accountSearch(Request $request)
  896. {
  897. abort_if(! $request->user() || ! $request->user()->token(), 403);
  898. abort_unless($request->user()->tokenCan('read'), 403);
  899. $this->validate($request, [
  900. 'q' => 'required|string|min:1|max:30',
  901. 'limit' => 'nullable|integer|min:1',
  902. 'resolve' => 'nullable',
  903. ]);
  904. $user = $request->user();
  905. abort_if($user->has_roles && ! UserRoleService::can('can-view-discover', $user->id), 403, 'Invalid permissions for this action');
  906. AccountService::setLastActive($user->id);
  907. $query = $request->input('q');
  908. $limit = $request->input('limit') ?? 20;
  909. if ($limit > 20) {
  910. $limit = 20;
  911. }
  912. $resolve = $request->boolean('resolve', false);
  913. $q = $query.'%';
  914. $profiles = Profile::where('username', 'like', $q)
  915. ->orderByDesc('followers_count')
  916. ->limit($limit)
  917. ->pluck('id')
  918. ->map(function ($id) {
  919. return AccountService::getMastodon($id);
  920. })
  921. ->filter(function ($account) {
  922. return $account && isset($account['id']);
  923. })
  924. ->values();
  925. return $this->json($profiles);
  926. }
  927. /**
  928. * GET /api/v1/blocks
  929. *
  930. *
  931. *
  932. * @return \App\Transformer\Api\AccountTransformer
  933. */
  934. public function accountBlocks(Request $request)
  935. {
  936. abort_if(! $request->user() || ! $request->user()->token(), 403);
  937. abort_unless($request->user()->tokenCan('read'), 403);
  938. $this->validate($request, [
  939. 'limit' => 'sometimes|integer|min:1',
  940. 'page' => 'sometimes|integer|min:1',
  941. ]);
  942. $user = $request->user();
  943. $limit = $request->input('limit') ?? 40;
  944. if ($limit > 80) {
  945. $limit = 80;
  946. }
  947. $blocks = UserFilter::select('filterable_id', 'filterable_type', 'filter_type', 'user_id')
  948. ->whereUserId($user->profile_id)
  949. ->whereFilterableType('App\Profile')
  950. ->whereFilterType('block')
  951. ->orderByDesc('id')
  952. ->simplePaginate($limit)
  953. ->withQueryString();
  954. $res = $blocks->pluck('filterable_id')
  955. ->map(function ($id) {
  956. return AccountService::get($id, true);
  957. })
  958. ->filter(function ($account) {
  959. return $account && isset($account['id']);
  960. })
  961. ->values();
  962. $baseUrl = config('app.url').'/api/v1/blocks?limit='.$limit.'&';
  963. $next = $blocks->nextPageUrl();
  964. $prev = $blocks->previousPageUrl();
  965. if ($next && ! $prev) {
  966. $link = '<'.$next.'>; rel="next"';
  967. }
  968. if (! $next && $prev) {
  969. $link = '<'.$prev.'>; rel="prev"';
  970. }
  971. if ($next && $prev) {
  972. $link = '<'.$next.'>; rel="next",<'.$prev.'>; rel="prev"';
  973. }
  974. $headers = isset($link) ? ['Link' => $link] : [];
  975. return $this->json($res, 200, $headers);
  976. }
  977. /**
  978. * POST /api/v1/accounts/{id}/block
  979. *
  980. * @param int $id
  981. * @return \App\Transformer\Api\RelationshipTransformer
  982. */
  983. public function accountBlockById(Request $request, $id)
  984. {
  985. abort_if(! $request->user() || ! $request->user()->token(), 403);
  986. abort_unless($request->user()->tokenCan('write'), 403);
  987. $user = $request->user();
  988. $pid = $user->profile_id ?? $user->profile->id;
  989. AccountService::setLastActive($user->id);
  990. if (intval($id) === intval($pid)) {
  991. abort(400, 'You cannot block yourself');
  992. }
  993. $profile = Profile::findOrFail($id);
  994. abort_if($profile->moved_to_profile_id, 422, 'Cannot block an account that has migrated!');
  995. if ($profile->user && $profile->user->is_admin == true) {
  996. abort(400, 'You cannot block an admin');
  997. }
  998. $count = UserFilterService::blockCount($pid);
  999. $maxLimit = (int) config_cache('instance.user_filters.max_user_blocks');
  1000. if ($count == 0) {
  1001. $filterCount = UserFilter::whereUserId($pid)
  1002. ->whereFilterType('block')
  1003. ->get()
  1004. ->map(function ($rec) {
  1005. return AccountService::get($rec->filterable_id, true);
  1006. })
  1007. ->filter(function ($account) {
  1008. return $account && isset($account['id']);
  1009. })
  1010. ->values()
  1011. ->count();
  1012. abort_if($filterCount >= $maxLimit, 422, AccountController::FILTER_LIMIT_BLOCK_TEXT.$maxLimit.' accounts');
  1013. } else {
  1014. abort_if($count >= $maxLimit, 422, AccountController::FILTER_LIMIT_BLOCK_TEXT.$maxLimit.' accounts');
  1015. }
  1016. $followed = Follower::whereProfileId($profile->id)->whereFollowingId($pid)->first();
  1017. if ($followed) {
  1018. $followed->delete();
  1019. $profile->following_count = Follower::whereProfileId($profile->id)->count();
  1020. $profile->save();
  1021. $selfProfile = $user->profile;
  1022. $selfProfile->followers_count = Follower::whereFollowingId($pid)->count();
  1023. $selfProfile->save();
  1024. FollowerService::remove($profile->id, $pid);
  1025. AccountService::del($pid);
  1026. AccountService::del($profile->id);
  1027. }
  1028. $following = Follower::whereProfileId($pid)->whereFollowingId($profile->id)->first();
  1029. if ($following) {
  1030. $following->delete();
  1031. $profile->followers_count = Follower::whereFollowingId($profile->id)->count();
  1032. $profile->save();
  1033. $selfProfile = $user->profile;
  1034. $selfProfile->following_count = Follower::whereProfileId($pid)->count();
  1035. $selfProfile->save();
  1036. FollowerService::remove($pid, $profile->pid);
  1037. AccountService::del($pid);
  1038. AccountService::del($profile->id);
  1039. }
  1040. Notification::whereProfileId($pid)
  1041. ->whereActorId($profile->id)
  1042. ->get()
  1043. ->map(function ($n) use ($pid) {
  1044. NotificationService::del($pid, $n['id']);
  1045. $n->forceDelete();
  1046. });
  1047. $filter = UserFilter::firstOrCreate([
  1048. 'user_id' => $pid,
  1049. 'filterable_id' => $profile->id,
  1050. 'filterable_type' => 'App\Profile',
  1051. 'filter_type' => 'block',
  1052. ]);
  1053. UserFilterService::block($pid, $id);
  1054. RelationshipService::refresh($pid, $id);
  1055. $resource = new Fractal\Resource\Item($profile, new RelationshipTransformer);
  1056. $res = $this->fractal->createData($resource)->toArray();
  1057. return $this->json($res);
  1058. }
  1059. /**
  1060. * POST /api/v1/accounts/{id}/unblock
  1061. *
  1062. * @param int $id
  1063. * @return \App\Transformer\Api\RelationshipTransformer
  1064. */
  1065. public function accountUnblockById(Request $request, $id)
  1066. {
  1067. abort_if(! $request->user() || ! $request->user()->token(), 403);
  1068. abort_unless($request->user()->tokenCan('write'), 403);
  1069. $user = $request->user();
  1070. $pid = $user->profile_id ?? $user->profile->id;
  1071. AccountService::setLastActive($user->id);
  1072. if (intval($id) === intval($pid)) {
  1073. abort(400, 'You cannot unblock yourself');
  1074. }
  1075. $profile = Profile::findOrFail($id);
  1076. abort_if($profile->moved_to_profile_id, 422, 'Cannot unblock an account that has migrated!');
  1077. $filter = UserFilter::whereUserId($pid)
  1078. ->whereFilterableId($profile->id)
  1079. ->whereFilterableType('App\Profile')
  1080. ->whereFilterType('block')
  1081. ->first();
  1082. if ($filter) {
  1083. $filter->delete();
  1084. UserFilterService::unblock($pid, $profile->id);
  1085. }
  1086. RelationshipService::refresh($pid, $id);
  1087. $resource = new Fractal\Resource\Item($profile, new RelationshipTransformer);
  1088. $res = $this->fractal->createData($resource)->toArray();
  1089. return $this->json($res);
  1090. }
  1091. /**
  1092. * GET /api/v1/custom_emojis
  1093. *
  1094. * Return custom emoji
  1095. *
  1096. * @return array
  1097. */
  1098. public function customEmojis()
  1099. {
  1100. return response(CustomEmojiService::all())->header('Content-Type', 'application/json');
  1101. }
  1102. /**
  1103. * GET /api/v1/domain_blocks
  1104. *
  1105. * Return empty array
  1106. *
  1107. * @return array
  1108. */
  1109. public function accountDomainBlocks(Request $request)
  1110. {
  1111. abort_if(! $request->user() || ! $request->user()->token(), 403);
  1112. abort_unless($request->user()->tokenCan('read'), 403);
  1113. return response()->json([]);
  1114. }
  1115. /**
  1116. * GET /api/v1/endorsements
  1117. *
  1118. * Return empty array
  1119. *
  1120. * @return array
  1121. */
  1122. public function accountEndorsements(Request $request)
  1123. {
  1124. abort_if(! $request->user() || ! $request->user()->token(), 403);
  1125. abort_unless($request->user()->tokenCan('read'), 403);
  1126. return response()->json([]);
  1127. }
  1128. /**
  1129. * GET /api/v1/favourites
  1130. *
  1131. * Returns collection of liked statuses
  1132. *
  1133. * @return \App\Transformer\Api\StatusTransformer
  1134. */
  1135. public function accountFavourites(Request $request)
  1136. {
  1137. abort_if(! $request->user() || ! $request->user()->token(), 403);
  1138. abort_unless($request->user()->tokenCan('read'), 403);
  1139. $this->validate($request, [
  1140. 'limit' => 'sometimes|integer|min:1',
  1141. ]);
  1142. $user = $request->user();
  1143. $maxId = $request->input('max_id');
  1144. $minId = $request->input('min_id');
  1145. $limit = $request->input('limit') ?? 10;
  1146. if ($limit > 40) {
  1147. $limit = 40;
  1148. }
  1149. $res = Like::whereProfileId($user->profile_id)
  1150. ->when($maxId, function ($q, $maxId) {
  1151. return $q->where('id', '<', $maxId);
  1152. })
  1153. ->when($minId, function ($q, $minId) {
  1154. return $q->where('id', '>', $minId);
  1155. })
  1156. ->orderByDesc('id')
  1157. ->limit($limit)
  1158. ->get()
  1159. ->map(function ($like) {
  1160. $status = StatusService::getMastodon($like['status_id'], false);
  1161. $status['favourited'] = true;
  1162. $status['like_id'] = $like->id;
  1163. $status['liked_at'] = str_replace('+00:00', 'Z', $like->created_at->format(DATE_RFC3339_EXTENDED));
  1164. return $status;
  1165. })
  1166. ->filter(function ($status) {
  1167. return $status && isset($status['id'], $status['like_id']);
  1168. })
  1169. ->values();
  1170. if ($res->count()) {
  1171. $ids = $res->map(function ($status) {
  1172. return $status['like_id'];
  1173. })->filter();
  1174. $max = $ids->min() - 1;
  1175. $min = $ids->max();
  1176. $baseUrl = config('app.url').'/api/v1/favourites?limit='.$limit.'&';
  1177. if ($maxId) {
  1178. $link = '<'.$baseUrl.'max_id='.$max.'>; rel="next",<'.$baseUrl.'min_id='.$min.'>; rel="prev"';
  1179. } else {
  1180. $link = '<'.$baseUrl.'max_id='.$max.'>; rel="next"';
  1181. }
  1182. return $this->json($res, 200, ['Link' => $link]);
  1183. } else {
  1184. return $this->json($res);
  1185. }
  1186. }
  1187. /**
  1188. * POST /api/v1/statuses/{id}/favourite
  1189. *
  1190. * @param int $id
  1191. * @return \App\Transformer\Api\StatusTransformer
  1192. */
  1193. public function statusFavouriteById(Request $request, $id)
  1194. {
  1195. abort_if(! $request->user() || ! $request->user()->token(), 403);
  1196. abort_unless($request->user()->tokenCan('write'), 403);
  1197. $user = $request->user();
  1198. abort_if($user->has_roles && ! UserRoleService::can('can-like', $user->id), 403, 'Invalid permissions for this action');
  1199. $napi = $request->has(self::PF_API_ENTITY_KEY);
  1200. $status = $napi ? StatusService::get($id, false) : StatusService::getMastodon($id, false);
  1201. abort_unless($status, 404);
  1202. abort_if(isset($status['moved'], $status['moved']['id']), 422, 'Cannot like a post from an account that has migrated');
  1203. if ($status && isset($status['account'], $status['account']['acct']) && strpos($status['account']['acct'], '@') != -1) {
  1204. $domain = parse_url($status['account']['url'], PHP_URL_HOST);
  1205. abort_if(in_array($domain, InstanceService::getBannedDomains()), 404);
  1206. }
  1207. $spid = $status['account']['id'];
  1208. AccountService::setLastActive($user->id);
  1209. if (intval($spid) !== intval($user->profile_id)) {
  1210. if ($status['visibility'] == 'private') {
  1211. abort_if(! FollowerService::follows($user->profile_id, $spid), 403);
  1212. } else {
  1213. abort_if(! in_array($status['visibility'], ['public', 'unlisted']), 403);
  1214. }
  1215. }
  1216. abort_if(
  1217. Like::whereProfileId($user->profile_id)
  1218. ->where('created_at', '>', now()->subDay())
  1219. ->count() >= Like::MAX_PER_DAY,
  1220. 429
  1221. );
  1222. $blocks = UserFilterService::blocks($spid);
  1223. if ($blocks && in_array($user->profile_id, $blocks)) {
  1224. abort(422);
  1225. }
  1226. $like = Like::firstOrCreate([
  1227. 'profile_id' => $user->profile_id,
  1228. 'status_id' => $status['id'],
  1229. ]);
  1230. if ($like->wasRecentlyCreated == true) {
  1231. $like->status_profile_id = $spid;
  1232. $like->is_comment = ! empty($status['in_reply_to_id']);
  1233. $like->save();
  1234. Status::findOrFail($status['id'])->update([
  1235. 'likes_count' => ($status['favourites_count'] ?? 0) + 1,
  1236. ]);
  1237. LikePipeline::dispatch($like)->onQueue('feed');
  1238. }
  1239. $status['favourited'] = true;
  1240. $status['favourites_count'] = $status['favourites_count'] + 1;
  1241. $status['bookmarked'] = BookmarkService::get($user->profile_id, $status['id']);
  1242. $status['reblogged'] = ReblogService::get($user->profile_id, $status['id']);
  1243. return $this->json($status);
  1244. }
  1245. /**
  1246. * POST /api/v1/statuses/{id}/unfavourite
  1247. *
  1248. * @param int $id
  1249. * @return \App\Transformer\Api\StatusTransformer
  1250. */
  1251. public function statusUnfavouriteById(Request $request, $id)
  1252. {
  1253. abort_if(! $request->user() || ! $request->user()->token(), 403);
  1254. abort_unless($request->user()->tokenCan('write'), 403);
  1255. $user = $request->user();
  1256. abort_if($user->has_roles && ! UserRoleService::can('can-like', $user->id), 403, 'Invalid permissions for this action');
  1257. $napi = $request->has(self::PF_API_ENTITY_KEY);
  1258. $status = $napi ? StatusService::get($id, false) : StatusService::getMastodon($id, false);
  1259. abort_unless($status && isset($status['account']), 404);
  1260. abort_if(isset($status['moved'], $status['moved']['id']), 422, 'Cannot unlike a post from an account that has migrated');
  1261. if ($status && isset($status['account'], $status['account']['acct']) && strpos($status['account']['acct'], '@') != -1) {
  1262. $domain = parse_url($status['account']['url'], PHP_URL_HOST);
  1263. abort_if(in_array($domain, InstanceService::getBannedDomains()), 404);
  1264. }
  1265. $spid = $status['account']['id'];
  1266. AccountService::setLastActive($user->id);
  1267. if (intval($spid) !== intval($user->profile_id)) {
  1268. if ($status['visibility'] == 'private') {
  1269. abort_if(! FollowerService::follows($user->profile_id, $spid), 403);
  1270. } else {
  1271. abort_if(! in_array($status['visibility'], ['public', 'unlisted']), 403);
  1272. }
  1273. }
  1274. $like = Like::whereProfileId($user->profile_id)
  1275. ->whereStatusId($status['id'])
  1276. ->first();
  1277. if ($like) {
  1278. $like->forceDelete();
  1279. $ogStatus = Status::find($status['id']);
  1280. if ($ogStatus) {
  1281. $ogStatus->likes_count = $ogStatus->likes_count > 1 ? $ogStatus->likes_count - 1 : 0;
  1282. $ogStatus->save();
  1283. }
  1284. }
  1285. StatusService::del($status['id']);
  1286. $status['favourited'] = false;
  1287. $status['favourites_count'] = isset($ogStatus) ? $ogStatus->likes_count : $status['favourites_count'] - 1;
  1288. $status['bookmarked'] = BookmarkService::get($user->profile_id, $status['id']);
  1289. $status['reblogged'] = ReblogService::get($user->profile_id, $status['id']);
  1290. return $this->json($status);
  1291. }
  1292. /**
  1293. * GET /api/v1/filters
  1294. *
  1295. * Return empty response since we filter server side
  1296. *
  1297. * @return array
  1298. */
  1299. public function accountFilters(Request $request)
  1300. {
  1301. abort_if(! $request->user() || ! $request->user()->token(), 403);
  1302. abort_unless($request->user()->tokenCan('read'), 403);
  1303. return response()->json([]);
  1304. }
  1305. /**
  1306. * GET /api/v1/follow_requests
  1307. *
  1308. * Return array of Accounts that have sent follow requests
  1309. *
  1310. * @return \App\Transformer\Api\AccountTransformer
  1311. */
  1312. public function accountFollowRequests(Request $request)
  1313. {
  1314. abort_if(! $request->user() || ! $request->user()->token(), 403);
  1315. abort_unless($request->user()->tokenCan('read'), 403);
  1316. $this->validate($request, [
  1317. 'limit' => 'sometimes|integer|min:1|max:100',
  1318. ]);
  1319. $user = $request->user();
  1320. $res = FollowRequest::whereFollowingId($user->profile_id)
  1321. ->limit($request->input('limit', 40))
  1322. ->pluck('follower_id')
  1323. ->map(function ($id) {
  1324. return AccountService::getMastodon($id, true);
  1325. })
  1326. ->filter(function ($acct) {
  1327. return $acct && isset($acct['id']);
  1328. })
  1329. ->values();
  1330. return $this->json($res);
  1331. }
  1332. /**
  1333. * POST /api/v1/follow_requests/{id}/authorize
  1334. *
  1335. * @param int $id
  1336. * @return null
  1337. */
  1338. public function accountFollowRequestAccept(Request $request, $id)
  1339. {
  1340. abort_if(! $request->user() || ! $request->user()->token(), 403);
  1341. abort_unless($request->user()->tokenCan('follow'), 403);
  1342. $pid = $request->user()->profile_id;
  1343. $target = AccountService::getMastodon($id);
  1344. abort_if(isset($target['moved'], $target['moved']['id']), 422, 'Cannot accept a request from an account that has migrated!');
  1345. if (! $target) {
  1346. return response()->json(['error' => 'Record not found'], 404);
  1347. }
  1348. if ($target && strpos($target['acct'], '@') != -1) {
  1349. $domain = parse_url($target['url'], PHP_URL_HOST);
  1350. abort_if(in_array($domain, InstanceService::getBannedDomains()), 404);
  1351. }
  1352. $followRequest = FollowRequest::whereFollowingId($pid)->whereFollowerId($id)->first();
  1353. if (! $followRequest) {
  1354. return response()->json(['error' => 'Record not found'], 404);
  1355. }
  1356. $follower = $followRequest->follower;
  1357. $follow = new Follower;
  1358. $follow->profile_id = $follower->id;
  1359. $follow->following_id = $pid;
  1360. $follow->save();
  1361. $profile = Profile::findOrFail($pid);
  1362. $profile->followers_count++;
  1363. $profile->save();
  1364. AccountService::del($profile->id);
  1365. $profile = Profile::findOrFail($follower->id);
  1366. $profile->following_count++;
  1367. $profile->save();
  1368. AccountService::del($profile->id);
  1369. if ($follower->domain != null && $follower->private_key === null) {
  1370. FollowAcceptPipeline::dispatch($followRequest)->onQueue('follow');
  1371. } else {
  1372. FollowPipeline::dispatch($follow);
  1373. $followRequest->delete();
  1374. }
  1375. RelationshipService::refresh($pid, $id);
  1376. $res = RelationshipService::get($pid, $id);
  1377. $res['followed_by'] = true;
  1378. return $this->json($res);
  1379. }
  1380. /**
  1381. * POST /api/v1/follow_requests/{id}/reject
  1382. *
  1383. * @param int $id
  1384. * @return null
  1385. */
  1386. public function accountFollowRequestReject(Request $request, $id)
  1387. {
  1388. abort_if(! $request->user() || ! $request->user()->token(), 403);
  1389. abort_unless($request->user()->tokenCan('follow'), 403);
  1390. $pid = $request->user()->profile_id;
  1391. $target = AccountService::getMastodon($id);
  1392. if (! $target) {
  1393. return response()->json(['error' => 'Record not found'], 404);
  1394. }
  1395. abort_if(isset($target['moved'], $target['moved']['id']), 422, 'Cannot reject a request from an account that has migrated!');
  1396. $followRequest = FollowRequest::whereFollowingId($pid)->whereFollowerId($id)->first();
  1397. if (! $followRequest) {
  1398. return response()->json(['error' => 'Record not found'], 404);
  1399. }
  1400. $follower = $followRequest->follower;
  1401. if ($follower->domain != null && $follower->private_key === null) {
  1402. FollowRejectPipeline::dispatch($followRequest)->onQueue('follow');
  1403. } else {
  1404. $followRequest->delete();
  1405. }
  1406. RelationshipService::refresh($pid, $id);
  1407. $res = RelationshipService::get($pid, $id);
  1408. return $this->json($res);
  1409. }
  1410. /**
  1411. * GET /api/v1/suggestions
  1412. *
  1413. * Return empty array as we don't support suggestions
  1414. *
  1415. * @return null
  1416. */
  1417. public function accountSuggestions(Request $request)
  1418. {
  1419. abort_if(! $request->user() || ! $request->user()->token(), 403);
  1420. abort_unless($request->user()->tokenCan('read'), 403);
  1421. // todo
  1422. return response()->json([]);
  1423. }
  1424. /**
  1425. * GET /api/v1/instance
  1426. *
  1427. * Information about the server.
  1428. *
  1429. * @return Instance
  1430. */
  1431. public function instance(Request $request)
  1432. {
  1433. $res = Cache::remember('api:v1:instance-data-response-v1', 1800, function () {
  1434. $contact = Cache::remember('api:v1:instance-data:contact', 604800, function () {
  1435. if (config_cache('instance.admin.pid')) {
  1436. return AccountService::getMastodon(config_cache('instance.admin.pid'), true);
  1437. }
  1438. $admin = User::whereIsAdmin(true)->first();
  1439. return $admin && isset($admin->profile_id) ?
  1440. AccountService::getMastodon($admin->profile_id, true) :
  1441. null;
  1442. });
  1443. $stats = Cache::remember('api:v1:instance-data:stats:v0', 43200, function () {
  1444. return [
  1445. 'user_count' => (int) User::count(),
  1446. 'status_count' => (int) StatusService::totalLocalStatuses(),
  1447. 'domain_count' => (int) Instance::count(),
  1448. ];
  1449. });
  1450. $rules = Cache::remember('api:v1:instance-data:rules', 604800, function () {
  1451. return config_cache('app.rules') ?
  1452. collect(json_decode(config_cache('app.rules'), true))
  1453. ->map(function ($rule, $key) {
  1454. $id = $key + 1;
  1455. return [
  1456. 'id' => "{$id}",
  1457. 'text' => $rule,
  1458. ];
  1459. })
  1460. ->toArray() : [];
  1461. });
  1462. return [
  1463. 'uri' => config('pixelfed.domain.app'),
  1464. 'title' => config_cache('app.name'),
  1465. 'short_description' => config_cache('app.short_description'),
  1466. 'description' => config_cache('app.description'),
  1467. 'email' => config('instance.email'),
  1468. 'version' => '3.5.3 (compatible; Pixelfed '.config('pixelfed.version').')',
  1469. 'urls' => [
  1470. 'streaming_api' => null,
  1471. ],
  1472. 'stats' => $stats,
  1473. 'thumbnail' => config_cache('app.banner_image') ?? url(Storage::url('public/headers/default.jpg')),
  1474. 'languages' => [config('app.locale')],
  1475. 'registrations' => (bool) config_cache('pixelfed.open_registration'),
  1476. 'approval_required' => (bool) config_cache('instance.curated_registration.enabled'),
  1477. 'contact_account' => $contact,
  1478. 'rules' => $rules,
  1479. 'mobile_registration' => (bool) config_cache('pixelfed.open_registration') && config('auth.in_app_registration'),
  1480. 'configuration' => [
  1481. 'media_attachments' => [
  1482. 'image_matrix_limit' => 2073600,
  1483. 'image_size_limit' => config_cache('pixelfed.max_photo_size') * 1024,
  1484. 'supported_mime_types' => explode(',', config_cache('pixelfed.media_types')),
  1485. 'video_frame_rate_limit' => 120,
  1486. 'video_matrix_limit' => 2073600,
  1487. 'video_size_limit' => config_cache('pixelfed.max_photo_size') * 1024,
  1488. ],
  1489. 'polls' => [
  1490. 'max_characters_per_option' => 50,
  1491. 'max_expiration' => 2629746,
  1492. 'max_options' => 4,
  1493. 'min_expiration' => 300,
  1494. ],
  1495. 'statuses' => [
  1496. 'characters_reserved_per_url' => 23,
  1497. 'max_characters' => (int) config_cache('pixelfed.max_caption_length'),
  1498. 'max_media_attachments' => (int) config_cache('pixelfed.max_album_length'),
  1499. ],
  1500. ],
  1501. ];
  1502. });
  1503. return $this->json($res);
  1504. }
  1505. /**
  1506. * GET /api/v1/lists
  1507. *
  1508. * Return empty array as we don't support lists
  1509. *
  1510. * @return null
  1511. */
  1512. public function accountLists(Request $request)
  1513. {
  1514. abort_if(! $request->user() || ! $request->user()->token(), 403);
  1515. abort_unless($request->user()->tokenCan('read'), 403);
  1516. return response()->json([]);
  1517. }
  1518. /**
  1519. * GET /api/v1/accounts/{id}/lists
  1520. *
  1521. * @param int $id
  1522. * @return null
  1523. */
  1524. public function accountListsById(Request $request, $id)
  1525. {
  1526. abort_if(! $request->user() || ! $request->user()->token(), 403);
  1527. abort_unless($request->user()->tokenCan('read'), 403);
  1528. return response()->json([]);
  1529. }
  1530. /**
  1531. * POST /api/v1/media
  1532. *
  1533. *
  1534. * @return MediaTransformer
  1535. */
  1536. public function mediaUpload(Request $request)
  1537. {
  1538. abort_if(! $request->user() || ! $request->user()->token(), 403);
  1539. abort_unless($request->user()->tokenCan('write'), 403);
  1540. $this->validate($request, [
  1541. 'file.*' => [
  1542. 'required_without:file',
  1543. 'mimetypes:'.config_cache('pixelfed.media_types'),
  1544. 'max:'.config_cache('pixelfed.max_photo_size'),
  1545. ],
  1546. 'file' => [
  1547. 'required_without:file.*',
  1548. 'mimetypes:'.config_cache('pixelfed.media_types'),
  1549. 'max:'.config_cache('pixelfed.max_photo_size'),
  1550. ],
  1551. 'filter_name' => 'nullable|string|max:24',
  1552. 'filter_class' => 'nullable|alpha_dash|max:24',
  1553. 'description' => 'nullable|string|max:'.config_cache('pixelfed.max_altext_length'),
  1554. ]);
  1555. $user = $request->user();
  1556. abort_if($user->has_roles && ! UserRoleService::can('can-post', $user->id), 403, 'Invalid permissions for this action');
  1557. AccountService::setLastActive($user->id);
  1558. if ($user->last_active_at == null) {
  1559. return [];
  1560. }
  1561. if (empty($request->file('file'))) {
  1562. return response('', 422);
  1563. }
  1564. $limitKey = 'compose:rate-limit:media-upload:'.$user->id;
  1565. $limitTtl = now()->addMinutes(15);
  1566. $limitReached = Cache::remember($limitKey, $limitTtl, function () use ($user) {
  1567. $dailyLimit = Media::whereUserId($user->id)->where('created_at', '>', now()->subDays(1))->count();
  1568. return $dailyLimit >= 1250;
  1569. });
  1570. abort_if($limitReached == true, 429);
  1571. $profile = $user->profile;
  1572. $accountSize = UserStorageService::get($user->id);
  1573. abort_if($accountSize === -1, 403, 'Invalid request.');
  1574. $photo = $request->file('file');
  1575. $fileSize = $photo->getSize();
  1576. $sizeInKbs = (int) ceil($fileSize / 1000);
  1577. $updatedAccountSize = (int) $accountSize + (int) $sizeInKbs;
  1578. if ((bool) config_cache('pixelfed.enforce_account_limit') == true) {
  1579. $limit = (int) config_cache('pixelfed.max_account_size');
  1580. if ($updatedAccountSize >= $limit) {
  1581. abort(403, 'Account size limit reached.');
  1582. }
  1583. }
  1584. $filterClass = in_array($request->input('filter_class'), Filter::classes()) ? $request->input('filter_class') : null;
  1585. $filterName = in_array($request->input('filter_name'), Filter::names()) ? $request->input('filter_name') : null;
  1586. $mimes = explode(',', config_cache('pixelfed.media_types'));
  1587. if (in_array($photo->getMimeType(), $mimes) == false) {
  1588. abort(403, 'Invalid or unsupported mime type.');
  1589. }
  1590. $storagePath = MediaPathService::get($user, 2);
  1591. $path = $photo->storePublicly($storagePath);
  1592. $hash = \hash_file('sha256', $photo);
  1593. $license = null;
  1594. $mime = $photo->getMimeType();
  1595. // if($photo->getMimeType() == 'image/heic') {
  1596. // abort_if(config('image.driver') !== 'imagick', 422, 'Invalid media type');
  1597. // abort_if(!in_array('HEIC', \Imagick::queryformats()), 422, 'Unsupported media type');
  1598. // $oldPath = $path;
  1599. // $path = str_replace('.heic', '.jpg', $path);
  1600. // $mime = 'image/jpeg';
  1601. // \Image::make($photo)->save(storage_path("app/{$path}"));
  1602. // @unlink(storage_path("app/{$oldPath}"));
  1603. // }
  1604. $settings = UserSetting::whereUserId($user->id)->first();
  1605. if ($settings && ! empty($settings->compose_settings)) {
  1606. $compose = $settings->compose_settings;
  1607. if (isset($compose['default_license']) && $compose['default_license'] != 1) {
  1608. $license = $compose['default_license'];
  1609. }
  1610. }
  1611. abort_if(MediaBlocklistService::exists($hash) == true, 451);
  1612. $media = new Media;
  1613. $media->status_id = null;
  1614. $media->profile_id = $profile->id;
  1615. $media->user_id = $user->id;
  1616. $media->media_path = $path;
  1617. $media->original_sha256 = $hash;
  1618. $media->size = $photo->getSize();
  1619. $media->mime = $mime;
  1620. $media->caption = $request->input('description') ?? '';
  1621. $media->filter_class = $filterClass;
  1622. $media->filter_name = $filterName;
  1623. if ($license) {
  1624. $media->license = $license;
  1625. }
  1626. $media->save();
  1627. switch ($media->mime) {
  1628. case 'image/jpeg':
  1629. case 'image/png':
  1630. case 'image/webp':
  1631. case 'image/avif':
  1632. ImageOptimize::dispatch($media)->onQueue('mmo');
  1633. break;
  1634. case 'video/mp4':
  1635. VideoThumbnail::dispatch($media)->onQueue('mmo');
  1636. $preview_url = '/storage/no-preview.png';
  1637. $url = '/storage/no-preview.png';
  1638. break;
  1639. }
  1640. $user->storage_used = (int) $updatedAccountSize;
  1641. $user->storage_used_updated_at = now();
  1642. $user->save();
  1643. Cache::forget($limitKey);
  1644. $resource = new Fractal\Resource\Item($media, new MediaTransformer);
  1645. $res = $this->fractal->createData($resource)->toArray();
  1646. $res['preview_url'] = $media->url().'?v='.time();
  1647. $res['url'] = $media->url().'?v='.time();
  1648. return $this->json($res);
  1649. }
  1650. /**
  1651. * PUT /api/v1/media/{id}
  1652. *
  1653. * @param int $id
  1654. * @return MediaTransformer
  1655. */
  1656. public function mediaUpdate(Request $request, $id)
  1657. {
  1658. abort_if(! $request->user() || ! $request->user()->token(), 403);
  1659. abort_unless($request->user()->tokenCan('write'), 403);
  1660. $this->validate($request, [
  1661. 'description' => 'nullable|string|max:'.config_cache('pixelfed.max_altext_length'),
  1662. ]);
  1663. $user = $request->user();
  1664. abort_if($user->has_roles && ! UserRoleService::can('can-post', $user->id), 403, 'Invalid permissions for this action');
  1665. AccountService::setLastActive($user->id);
  1666. $media = Media::whereUserId($user->id)
  1667. ->whereProfileId($user->profile_id)
  1668. ->findOrFail($id);
  1669. $executed = RateLimiter::attempt(
  1670. 'media:update:'.$user->id,
  1671. 10,
  1672. function () use ($media, $request) {
  1673. $caption = Purify::clean($request->input('description'));
  1674. if ($caption != $media->caption) {
  1675. $media->caption = $caption;
  1676. $media->save();
  1677. if ($media->status_id) {
  1678. MediaService::del($media->status_id);
  1679. StatusService::del($media->status_id);
  1680. }
  1681. }
  1682. });
  1683. if (! $executed) {
  1684. return response()->json([
  1685. 'error' => 'Too many attempts. Try again in a few minutes.',
  1686. ], 429);
  1687. }
  1688. $fractal = new Fractal\Manager;
  1689. $fractal->setSerializer(new ArraySerializer);
  1690. $resource = new Fractal\Resource\Item($media, new MediaTransformer);
  1691. return $this->json($fractal->createData($resource)->toArray());
  1692. }
  1693. /**
  1694. * GET /api/v1/media/{id}
  1695. *
  1696. * @param int $id
  1697. * @return MediaTransformer
  1698. */
  1699. public function mediaGet(Request $request, $id)
  1700. {
  1701. abort_if(! $request->user() || ! $request->user()->token(), 403);
  1702. abort_unless($request->user()->tokenCan('read'), 403);
  1703. $user = $request->user();
  1704. abort_if($user->has_roles && ! UserRoleService::can('can-post', $user->id), 403, 'Invalid permissions for this action');
  1705. AccountService::setLastActive($user->id);
  1706. $media = Media::whereUserId($user->id)
  1707. ->whereNull('status_id')
  1708. ->findOrFail($id);
  1709. $resource = new Fractal\Resource\Item($media, new MediaTransformer);
  1710. $res = $this->fractal->createData($resource)->toArray();
  1711. return $this->json($res);
  1712. }
  1713. /**
  1714. * POST /api/v2/media
  1715. *
  1716. *
  1717. * @return MediaTransformer
  1718. */
  1719. public function mediaUploadV2(Request $request)
  1720. {
  1721. abort_if(! $request->user() || ! $request->user()->token(), 403);
  1722. abort_unless($request->user()->tokenCan('write'), 403);
  1723. $this->validate($request, [
  1724. 'file.*' => [
  1725. 'required_without:file',
  1726. 'mimetypes:'.config_cache('pixelfed.media_types'),
  1727. 'max:'.config_cache('pixelfed.max_photo_size'),
  1728. ],
  1729. 'file' => [
  1730. 'required_without:file.*',
  1731. 'mimetypes:'.config_cache('pixelfed.media_types'),
  1732. 'max:'.config_cache('pixelfed.max_photo_size'),
  1733. ],
  1734. 'filter_name' => 'nullable|string|max:24',
  1735. 'filter_class' => 'nullable|alpha_dash|max:24',
  1736. 'description' => 'nullable|string|max:'.config_cache('pixelfed.max_altext_length'),
  1737. 'replace_id' => 'sometimes',
  1738. ]);
  1739. $user = $request->user();
  1740. abort_if($user->has_roles && ! UserRoleService::can('can-post', $user->id), 403, 'Invalid permissions for this action');
  1741. if ($user->last_active_at == null) {
  1742. return [];
  1743. }
  1744. AccountService::setLastActive($user->id);
  1745. if (empty($request->file('file'))) {
  1746. return response('', 422);
  1747. }
  1748. $limitKey = 'compose:rate-limit:media-upload:'.$user->id;
  1749. $limitTtl = now()->addMinutes(15);
  1750. $limitReached = Cache::remember($limitKey, $limitTtl, function () use ($user) {
  1751. $dailyLimit = Media::whereUserId($user->id)->where('created_at', '>', now()->subDays(1))->count();
  1752. return $dailyLimit >= 1250;
  1753. });
  1754. abort_if($limitReached == true, 429);
  1755. $profile = $user->profile;
  1756. $accountSize = UserStorageService::get($user->id);
  1757. abort_if($accountSize === -1, 403, 'Invalid request.');
  1758. $photo = $request->file('file');
  1759. $fileSize = $photo->getSize();
  1760. $sizeInKbs = (int) ceil($fileSize / 1000);
  1761. $updatedAccountSize = (int) $accountSize + (int) $sizeInKbs;
  1762. if ((bool) config_cache('pixelfed.enforce_account_limit') == true) {
  1763. $limit = (int) config_cache('pixelfed.max_account_size');
  1764. if ($updatedAccountSize >= $limit) {
  1765. abort(403, 'Account size limit reached.');
  1766. }
  1767. }
  1768. $filterClass = in_array($request->input('filter_class'), Filter::classes()) ? $request->input('filter_class') : null;
  1769. $filterName = in_array($request->input('filter_name'), Filter::names()) ? $request->input('filter_name') : null;
  1770. $mimes = explode(',', config_cache('pixelfed.media_types'));
  1771. if (in_array($photo->getMimeType(), $mimes) == false) {
  1772. abort(403, 'Invalid or unsupported mime type.');
  1773. }
  1774. $storagePath = MediaPathService::get($user, 2);
  1775. $path = $photo->storePublicly($storagePath);
  1776. $hash = \hash_file('sha256', $photo);
  1777. $license = null;
  1778. $mime = $photo->getMimeType();
  1779. $settings = UserSetting::whereUserId($user->id)->first();
  1780. if ($settings && ! empty($settings->compose_settings)) {
  1781. $compose = $settings->compose_settings;
  1782. if (isset($compose['default_license']) && $compose['default_license'] != 1) {
  1783. $license = $compose['default_license'];
  1784. }
  1785. }
  1786. abort_if(MediaBlocklistService::exists($hash) == true, 451);
  1787. if ($request->has('replace_id')) {
  1788. $rpid = $request->input('replace_id');
  1789. $removeMedia = Media::whereNull('status_id')
  1790. ->whereUserId($user->id)
  1791. ->whereProfileId($profile->id)
  1792. ->where('created_at', '>', now()->subHours(2))
  1793. ->find($rpid);
  1794. if ($removeMedia) {
  1795. $dateTime = Carbon::now();
  1796. MediaDeletePipeline::dispatch($removeMedia)
  1797. ->onQueue('mmo')
  1798. ->delay($dateTime->addMinutes(15));
  1799. }
  1800. }
  1801. $media = new Media;
  1802. $media->status_id = null;
  1803. $media->profile_id = $profile->id;
  1804. $media->user_id = $user->id;
  1805. $media->media_path = $path;
  1806. $media->original_sha256 = $hash;
  1807. $media->size = $photo->getSize();
  1808. $media->mime = $mime;
  1809. $media->caption = $request->input('description') ?? '';
  1810. $media->filter_class = $filterClass;
  1811. $media->filter_name = $filterName;
  1812. if ($license) {
  1813. $media->license = $license;
  1814. }
  1815. $media->save();
  1816. switch ($media->mime) {
  1817. case 'image/jpeg':
  1818. case 'image/png':
  1819. case 'image/webp':
  1820. case 'image/avif':
  1821. ImageOptimize::dispatch($media)->onQueue('mmo');
  1822. break;
  1823. case 'video/mp4':
  1824. VideoThumbnail::dispatch($media)->onQueue('mmo');
  1825. $preview_url = '/storage/no-preview.png';
  1826. $url = '/storage/no-preview.png';
  1827. break;
  1828. }
  1829. $user->storage_used = (int) $updatedAccountSize;
  1830. $user->storage_used_updated_at = now();
  1831. $user->save();
  1832. Cache::forget($limitKey);
  1833. $resource = new Fractal\Resource\Item($media, new MediaTransformer);
  1834. $res = $this->fractal->createData($resource)->toArray();
  1835. $res['preview_url'] = $media->url().'?v='.time();
  1836. $res['url'] = null;
  1837. return $this->json($res, 202);
  1838. }
  1839. /**
  1840. * GET /api/v1/mutes
  1841. *
  1842. *
  1843. * @return AccountTransformer
  1844. */
  1845. public function accountMutes(Request $request)
  1846. {
  1847. abort_if(! $request->user() || ! $request->user()->token(), 403);
  1848. abort_unless($request->user()->tokenCan('read'), 403);
  1849. $this->validate($request, [
  1850. 'limit' => 'sometimes|integer|min:1',
  1851. ]);
  1852. $user = $request->user();
  1853. $limit = $request->input('limit', 40);
  1854. if ($limit > 80) {
  1855. $limit = 80;
  1856. }
  1857. $mutes = UserFilter::whereUserId($user->profile_id)
  1858. ->whereFilterableType('App\Profile')
  1859. ->whereFilterType('mute')
  1860. ->orderByDesc('id')
  1861. ->simplePaginate($limit)
  1862. ->withQueryString();
  1863. $res = $mutes->pluck('filterable_id')
  1864. ->map(function ($id) {
  1865. return AccountService::get($id, true);
  1866. })
  1867. ->filter(function ($account) {
  1868. return $account && isset($account['id']);
  1869. })
  1870. ->values();
  1871. $baseUrl = config('app.url').'/api/v1/mutes?limit='.$limit.'&';
  1872. $next = $mutes->nextPageUrl();
  1873. $prev = $mutes->previousPageUrl();
  1874. if ($next && ! $prev) {
  1875. $link = '<'.$next.'>; rel="next"';
  1876. }
  1877. if (! $next && $prev) {
  1878. $link = '<'.$prev.'>; rel="prev"';
  1879. }
  1880. if ($next && $prev) {
  1881. $link = '<'.$next.'>; rel="next",<'.$prev.'>; rel="prev"';
  1882. }
  1883. $headers = isset($link) ? ['Link' => $link] : [];
  1884. return $this->json($res, 200, $headers);
  1885. }
  1886. /**
  1887. * POST /api/v1/accounts/{id}/mute
  1888. *
  1889. * @param int $id
  1890. * @return RelationshipTransformer
  1891. */
  1892. public function accountMuteById(Request $request, $id)
  1893. {
  1894. abort_if(! $request->user() || ! $request->user()->token(), 403);
  1895. abort_unless($request->user()->tokenCan('write'), 403);
  1896. $user = $request->user();
  1897. $pid = $user->profile_id;
  1898. if (intval($pid) === intval($id)) {
  1899. return $this->json(['error' => 'You cannot mute yourself'], 500);
  1900. }
  1901. $account = Profile::findOrFail($id);
  1902. abort_if($account->moved_to_profile_id, 422, 'Cannot mute an account that has migrated!');
  1903. if ($account && $account->domain) {
  1904. $domain = $account->domain;
  1905. abort_if(in_array($domain, InstanceService::getBannedDomains()), 404);
  1906. }
  1907. $count = UserFilterService::muteCount($pid);
  1908. $maxLimit = (int) config_cache('instance.user_filters.max_user_mutes');
  1909. if ($count == 0) {
  1910. $filterCount = UserFilter::whereUserId($pid)
  1911. ->whereFilterType('mute')
  1912. ->get()
  1913. ->map(function ($rec) {
  1914. return AccountService::get($rec->filterable_id, true);
  1915. })
  1916. ->filter(function ($account) {
  1917. return $account && isset($account['id']);
  1918. })
  1919. ->values()
  1920. ->count();
  1921. abort_if($filterCount >= $maxLimit, 422, AccountController::FILTER_LIMIT_MUTE_TEXT.$maxLimit.' accounts');
  1922. } else {
  1923. abort_if($count >= $maxLimit, 422, AccountController::FILTER_LIMIT_MUTE_TEXT.$maxLimit.' accounts');
  1924. }
  1925. $filter = UserFilter::firstOrCreate([
  1926. 'user_id' => $pid,
  1927. 'filterable_id' => $account->id,
  1928. 'filterable_type' => 'App\Profile',
  1929. 'filter_type' => 'mute',
  1930. ]);
  1931. RelationshipService::refresh($pid, $id);
  1932. $resource = new Fractal\Resource\Item($account, new RelationshipTransformer);
  1933. $res = $this->fractal->createData($resource)->toArray();
  1934. return $this->json($res);
  1935. }
  1936. /**
  1937. * POST /api/v1/accounts/{id}/unmute
  1938. *
  1939. * @param int $id
  1940. * @return RelationshipTransformer
  1941. */
  1942. public function accountUnmuteById(Request $request, $id)
  1943. {
  1944. abort_if(! $request->user() || ! $request->user()->token(), 403);
  1945. abort_unless($request->user()->tokenCan('write'), 403);
  1946. $user = $request->user();
  1947. $pid = $user->profile_id;
  1948. if (intval($pid) === intval($id)) {
  1949. return $this->json(['error' => 'You cannot unmute yourself'], 500);
  1950. }
  1951. $profile = Profile::findOrFail($id);
  1952. abort_if($profile->moved_to_profile_id, 422, 'Cannot unmute an account that has migrated!');
  1953. $filter = UserFilter::whereUserId($pid)
  1954. ->whereFilterableId($profile->id)
  1955. ->whereFilterableType('App\Profile')
  1956. ->whereFilterType('mute')
  1957. ->first();
  1958. if ($filter) {
  1959. $filter->delete();
  1960. UserFilterService::unmute($pid, $profile->id);
  1961. }
  1962. RelationshipService::refresh($pid, $id);
  1963. $resource = new Fractal\Resource\Item($profile, new RelationshipTransformer);
  1964. $res = $this->fractal->createData($resource)->toArray();
  1965. return $this->json($res);
  1966. }
  1967. /**
  1968. * GET /api/v1/notifications
  1969. *
  1970. *
  1971. * @return NotificationTransformer
  1972. */
  1973. public function accountNotifications(Request $request)
  1974. {
  1975. abort_if(! $request->user() || ! $request->user()->token(), 403);
  1976. abort_unless($request->user()->tokenCan('read'), 403);
  1977. $this->validate($request, [
  1978. 'limit' => 'sometimes|integer|min:1',
  1979. 'min_id' => 'nullable|integer|min:1|max:'.PHP_INT_MAX,
  1980. 'max_id' => 'nullable|integer|min:1|max:'.PHP_INT_MAX,
  1981. 'since_id' => 'nullable|integer|min:1|max:'.PHP_INT_MAX,
  1982. 'types[]' => 'sometimes|array',
  1983. 'types[].*' => 'string|in:mention,reblog,follow,favourite',
  1984. 'type' => 'sometimes|string|in:mention,reblog,follow,favourite',
  1985. '_pe' => 'sometimes',
  1986. ]);
  1987. $pid = $request->user()->profile_id;
  1988. $limit = $request->input('limit', 20);
  1989. $ogLimit = $request->input('limit', 20);
  1990. if ($limit > 40) {
  1991. $limit = 40;
  1992. $ogLimit = 40;
  1993. }
  1994. $since = $request->input('since_id');
  1995. $min = $request->input('min_id');
  1996. $max = $request->input('max_id');
  1997. $pe = $request->filled('_pe');
  1998. if (! $since && ! $min && ! $max) {
  1999. $min = 1;
  2000. }
  2001. if ($since) {
  2002. $min = $since + 1;
  2003. }
  2004. $types = $request->input('types');
  2005. if ($request->has('types')) {
  2006. $limit = 150;
  2007. }
  2008. $maxId = null;
  2009. $minId = null;
  2010. AccountService::setLastActive($request->user()->id);
  2011. $res = $max ?
  2012. NotificationService::getMaxMastodon($pid, $max, $limit) :
  2013. NotificationService::getMinMastodon($pid, $min ?? $since, $limit);
  2014. $ids = $max ?
  2015. NotificationService::getRankedMaxId($pid, $max, $limit) :
  2016. NotificationService::getRankedMinId($pid, $min ?? $since, $limit);
  2017. if (! empty($ids)) {
  2018. $maxId = max($ids);
  2019. $minId = min($ids);
  2020. }
  2021. if (empty($res)) {
  2022. if (! Cache::has('pf:services:notifications:hasSynced:'.$pid)) {
  2023. Cache::put('pf:services:notifications:hasSynced:'.$pid, 1, 1209600);
  2024. NotificationWarmUserCache::dispatch($pid);
  2025. }
  2026. }
  2027. if ($request->has('types')) {
  2028. $typesParams = collect($types)->implode('&types[]=');
  2029. $baseUrl = config('app.url').'/api/v1/notifications?types[]='.$typesParams.'&limit='.$ogLimit.'&';
  2030. } else {
  2031. $baseUrl = config('app.url').'/api/v1/notifications?limit='.$ogLimit.'&';
  2032. }
  2033. if ($minId == $maxId) {
  2034. $minId = null;
  2035. }
  2036. $res = collect($res)
  2037. ->map(function ($n) use ($pe) {
  2038. if (! $pe) {
  2039. if ($n['type'] == 'comment') {
  2040. $n['type'] = 'mention';
  2041. return $n;
  2042. }
  2043. return $n;
  2044. }
  2045. return $n;
  2046. })
  2047. ->filter(function ($n) use ($pe) {
  2048. if (in_array($n['type'], ['mention', 'reblog', 'favourite'])) {
  2049. return isset($n['status'], $n['status']['id']);
  2050. }
  2051. if (! $pe) {
  2052. if (in_array($n['type'], [
  2053. 'tagged',
  2054. 'modlog',
  2055. 'story:react',
  2056. 'story:comment',
  2057. 'group:comment',
  2058. 'group:join:approved',
  2059. 'group:join:rejected',
  2060. ])) {
  2061. return false;
  2062. }
  2063. return isset($n['account'], $n['account']['id']);
  2064. }
  2065. return true;
  2066. })
  2067. ->map(function ($n) use ($pid) {
  2068. if (isset($n['status'])) {
  2069. $n['status']['favourited'] = (bool) LikeService::liked($pid, $n['status']['id']);
  2070. $n['status']['reblogged'] = (bool) ReblogService::get($pid, $n['status']['id']);
  2071. $n['status']['bookmarked'] = (bool) BookmarkService::get($pid, $n['status']['id']);
  2072. }
  2073. return $n;
  2074. })
  2075. ->filter(function ($n) use ($types) {
  2076. if (! $types) {
  2077. return true;
  2078. }
  2079. return in_array($n['type'], $types);
  2080. })
  2081. ->take($ogLimit)
  2082. ->values();
  2083. if ($maxId) {
  2084. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next"';
  2085. }
  2086. if ($minId) {
  2087. $link = '<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  2088. }
  2089. if ($maxId && $minId) {
  2090. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next",<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  2091. }
  2092. $headers = isset($link) ? ['Link' => $link] : [];
  2093. return $this->json($res, 200, $headers);
  2094. }
  2095. /**
  2096. * GET /api/v1/timelines/home
  2097. *
  2098. *
  2099. * @return StatusTransformer
  2100. */
  2101. public function timelineHome(Request $request)
  2102. {
  2103. abort_if(! $request->user() || ! $request->user()->token(), 403);
  2104. abort_unless($request->user()->tokenCan('read'), 403);
  2105. $this->validate($request, [
  2106. 'page' => 'sometimes|integer|max:40',
  2107. 'min_id' => 'sometimes|integer|min:0|max:'.PHP_INT_MAX,
  2108. 'max_id' => 'sometimes|integer|min:0|max:'.PHP_INT_MAX,
  2109. 'limit' => 'sometimes|integer|min:1',
  2110. 'include_reblogs' => 'sometimes',
  2111. ]);
  2112. $napi = $request->has(self::PF_API_ENTITY_KEY);
  2113. $page = $request->input('page');
  2114. $min = $request->input('min_id');
  2115. $max = $request->input('max_id');
  2116. $limit = $request->input('limit') ?? 20;
  2117. if ($limit > 40) {
  2118. $limit = 40;
  2119. }
  2120. $pid = $request->user()->profile_id;
  2121. $includeReblogs = $request->filled('include_reblogs') ? $request->boolean('include_reblogs') : false;
  2122. $nullFields = $includeReblogs ?
  2123. ['in_reply_to_id'] :
  2124. ['in_reply_to_id', 'reblog_of_id'];
  2125. $inTypes = $includeReblogs ?
  2126. ['photo', 'photo:album', 'video', 'video:album', 'photo:video:album', 'share'] :
  2127. ['photo', 'photo:album', 'video', 'video:album', 'photo:video:album'];
  2128. AccountService::setLastActive($request->user()->id);
  2129. $cachedFilters = CustomFilter::getCachedFiltersForAccount($pid);
  2130. $homeFilters = array_filter($cachedFilters, function ($item) {
  2131. [$filter, $rules] = $item;
  2132. return in_array('home', $filter->context);
  2133. });
  2134. if (config('exp.cached_home_timeline')) {
  2135. $paddedLimit = $includeReblogs ? $limit + 10 : $limit + 50;
  2136. if ($min || $max) {
  2137. if ($request->has('min_id')) {
  2138. $res = HomeTimelineService::getRankedMinId($pid, $min ?? 0, $paddedLimit);
  2139. } else {
  2140. $res = HomeTimelineService::getRankedMaxId($pid, $max ?? 0, $paddedLimit);
  2141. }
  2142. } else {
  2143. $res = HomeTimelineService::get($pid, 0, $paddedLimit);
  2144. }
  2145. if (! $res) {
  2146. $res = Cache::has('pf:services:apiv1:home:cached:coldbootcheck:'.$pid);
  2147. if (! $res) {
  2148. Cache::set('pf:services:apiv1:home:cached:coldbootcheck:'.$pid, 1, 86400);
  2149. FeedWarmCachePipeline::dispatchSync($pid);
  2150. return response()->json([], 206);
  2151. } else {
  2152. Cache::set('pf:services:apiv1:home:cached:coldbootcheck:'.$pid, 1, 86400);
  2153. return response()->json([], 206);
  2154. }
  2155. }
  2156. $res = collect($res)
  2157. ->map(function ($id) use ($napi) {
  2158. return $napi ? StatusService::get($id, false) : StatusService::getMastodon($id, false);
  2159. })
  2160. ->filter(function ($res) {
  2161. return $res && isset($res['account']);
  2162. })
  2163. ->filter(function ($s) use ($includeReblogs) {
  2164. return $includeReblogs ? true : $s['reblog'] == null;
  2165. })
  2166. ->filter(function ($s) use ($homeFilters) {
  2167. $filterResults = CustomFilter::applyCachedFilters($homeFilters, $s);
  2168. if (! empty($filterResults)) {
  2169. $shouldHide = collect($filterResults)->contains(function ($result) {
  2170. return $result['filter']->action === CustomFilter::ACTION_HIDE;
  2171. });
  2172. if ($shouldHide) {
  2173. return false;
  2174. }
  2175. }
  2176. return true;
  2177. })
  2178. ->take($limit)
  2179. ->map(function ($status) use ($pid) {
  2180. if ($pid) {
  2181. $status['favourited'] = (bool) LikeService::liked($pid, $status['id']);
  2182. $status['reblogged'] = (bool) ReblogService::get($pid, $status['id']);
  2183. $status['bookmarked'] = (bool) BookmarkService::get($pid, $status['id']);
  2184. }
  2185. return $status;
  2186. })
  2187. ->values();
  2188. $baseUrl = config('app.url').'/api/v1/timelines/home?limit='.$limit.'&';
  2189. $minId = $res->map(function ($s) {
  2190. return ['id' => $s['id']];
  2191. })->min('id');
  2192. $maxId = $res->map(function ($s) {
  2193. return ['id' => $s['id']];
  2194. })->max('id');
  2195. if ($minId == $maxId) {
  2196. $minId = null;
  2197. }
  2198. if ($maxId && $res->count() >= $limit) {
  2199. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next"';
  2200. }
  2201. if ($minId) {
  2202. $link = '<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  2203. }
  2204. if ($maxId && $minId) {
  2205. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next",<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  2206. }
  2207. $headers = isset($link) ? ['Link' => $link] : [];
  2208. return $this->json($res->toArray(), 200, $headers);
  2209. }
  2210. $following = Cache::remember('profile:following:'.$pid, 1209600, function () use ($pid) {
  2211. $following = Follower::whereProfileId($pid)->pluck('following_id');
  2212. return $following->push($pid)->toArray();
  2213. });
  2214. $muted = UserFilterService::mutes($pid);
  2215. if ($muted && count($muted)) {
  2216. $following = array_diff($following, $muted);
  2217. }
  2218. if ($min || $max) {
  2219. $dir = $min ? '>' : '<';
  2220. $id = $min ?? $max;
  2221. $res = Status::select(
  2222. 'id',
  2223. 'profile_id',
  2224. 'type',
  2225. 'visibility',
  2226. 'in_reply_to_id',
  2227. 'reblog_of_id'
  2228. )
  2229. ->where('id', $dir, $id)
  2230. ->whereNull($nullFields)
  2231. ->whereIntegerInRaw('profile_id', $following)
  2232. ->whereIn('type', $inTypes)
  2233. ->whereIn('visibility', ['public', 'unlisted', 'private'])
  2234. ->orderByDesc('id')
  2235. ->take(($limit * 2))
  2236. ->get()
  2237. ->map(function ($s) use ($pid, $napi) {
  2238. try {
  2239. $account = $napi ? AccountService::get($s['profile_id'], true) : AccountService::getMastodon($s['profile_id'], true);
  2240. if (! $account) {
  2241. return false;
  2242. }
  2243. $status = $napi ? StatusService::get($s['id'], false) : StatusService::getMastodon($s['id'], false);
  2244. if (! $status || ! isset($status['account']) || ! isset($status['account']['id'])) {
  2245. return false;
  2246. }
  2247. } catch (\Exception $e) {
  2248. return false;
  2249. }
  2250. $status['account'] = $account;
  2251. if ($pid) {
  2252. $status['favourited'] = (bool) LikeService::liked($pid, $s['id']);
  2253. $status['reblogged'] = (bool) ReblogService::get($pid, $status['id']);
  2254. $status['bookmarked'] = (bool) BookmarkService::get($pid, $status['id']);
  2255. }
  2256. return $status;
  2257. })
  2258. ->filter(function ($status) {
  2259. return $status && isset($status['account']);
  2260. })
  2261. ->map(function ($status) use ($pid) {
  2262. if (! empty($status['reblog'])) {
  2263. $status['reblog']['favourited'] = (bool) LikeService::liked($pid, $status['reblog']['id']);
  2264. $status['reblog']['reblogged'] = (bool) ReblogService::get($pid, $status['reblog']['id']);
  2265. $status['bookmarked'] = (bool) BookmarkService::get($pid, $status['id']);
  2266. }
  2267. return $status;
  2268. })
  2269. ->take($limit)
  2270. ->values();
  2271. } else {
  2272. $res = Status::select(
  2273. 'id',
  2274. 'profile_id',
  2275. 'type',
  2276. 'visibility',
  2277. 'in_reply_to_id',
  2278. 'reblog_of_id',
  2279. )
  2280. ->whereNull($nullFields)
  2281. ->whereIntegerInRaw('profile_id', $following)
  2282. ->whereIn('type', $inTypes)
  2283. ->whereIn('visibility', ['public', 'unlisted', 'private'])
  2284. ->orderByDesc('id')
  2285. ->take(($limit * 2))
  2286. ->get()
  2287. ->map(function ($s) use ($pid, $napi) {
  2288. try {
  2289. $account = $napi ? AccountService::get($s['profile_id'], true) : AccountService::getMastodon($s['profile_id'], true);
  2290. if (! $account) {
  2291. return false;
  2292. }
  2293. $status = $napi ? StatusService::get($s['id'], false) : StatusService::getMastodon($s['id'], false);
  2294. if (! $status || ! isset($status['account']) || ! isset($status['account']['id'])) {
  2295. return false;
  2296. }
  2297. } catch (\Exception $e) {
  2298. return false;
  2299. }
  2300. $status['account'] = $account;
  2301. if ($pid) {
  2302. $status['favourited'] = (bool) LikeService::liked($pid, $s['id']);
  2303. $status['reblogged'] = (bool) ReblogService::get($pid, $status['id']);
  2304. $status['bookmarked'] = (bool) BookmarkService::get($pid, $status['id']);
  2305. }
  2306. return $status;
  2307. })
  2308. ->filter(function ($status) {
  2309. return $status && isset($status['account']);
  2310. })
  2311. ->map(function ($status) use ($pid) {
  2312. if (! empty($status['reblog'])) {
  2313. $status['reblog']['favourited'] = (bool) LikeService::liked($pid, $status['reblog']['id']);
  2314. $status['reblog']['reblogged'] = (bool) ReblogService::get($pid, $status['reblog']['id']);
  2315. $status['bookmarked'] = (bool) BookmarkService::get($pid, $status['id']);
  2316. }
  2317. return $status;
  2318. })
  2319. ->take($limit)
  2320. ->values();
  2321. }
  2322. $baseUrl = config('app.url').'/api/v1/timelines/home?limit='.$limit.'&';
  2323. $minId = $res->map(function ($s) {
  2324. return ['id' => $s['id']];
  2325. })->min('id');
  2326. $maxId = $res->map(function ($s) {
  2327. return ['id' => $s['id']];
  2328. })->max('id');
  2329. if ($minId == $maxId) {
  2330. $minId = null;
  2331. }
  2332. if ($maxId) {
  2333. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next"';
  2334. }
  2335. if ($minId) {
  2336. $link = '<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  2337. }
  2338. if ($maxId && $minId) {
  2339. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next",<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  2340. }
  2341. $headers = isset($link) ? ['Link' => $link] : [];
  2342. return $this->json($res->toArray(), 200, $headers);
  2343. }
  2344. /**
  2345. * GET /api/v1/timelines/public
  2346. *
  2347. *
  2348. * @return StatusTransformer
  2349. */
  2350. public function timelinePublic(Request $request)
  2351. {
  2352. $this->validate($request, [
  2353. 'min_id' => 'nullable|integer|min:0|max:'.PHP_INT_MAX,
  2354. 'max_id' => 'nullable|integer|min:0|max:'.PHP_INT_MAX,
  2355. 'limit' => 'sometimes|integer|min:1',
  2356. 'remote' => 'sometimes',
  2357. 'local' => 'sometimes',
  2358. ]);
  2359. $napi = $request->has(self::PF_API_ENTITY_KEY);
  2360. $min = $request->input('min_id');
  2361. $max = $request->input('max_id');
  2362. if ($max == 0) {
  2363. $min = 1;
  2364. }
  2365. $minOrMax = $request->anyFilled(['max_id', 'min_id']);
  2366. $limit = $request->input('limit') ?? 20;
  2367. if ($limit > 40) {
  2368. $limit = 40;
  2369. }
  2370. $user = $request->user();
  2371. $remote = $request->has('remote') && $request->boolean('remote');
  2372. $local = $request->boolean('local');
  2373. $userRoleKey = $remote ? 'can-view-network-feed' : 'can-view-public-feed';
  2374. if ($user->has_roles && ! UserRoleService::can($userRoleKey, $user->id)) {
  2375. return [];
  2376. }
  2377. $filtered = $user ? UserFilterService::filters($user->profile_id) : [];
  2378. AccountService::setLastActive($user->id);
  2379. $domainBlocks = UserFilterService::domainBlocks($user->profile_id);
  2380. $hideNsfw = config('instance.hide_nsfw_on_public_feeds');
  2381. $amin = SnowflakeService::byDate(now()->subDays(config('federation.network_timeline_days_falloff')));
  2382. $asf = AdminShadowFilterService::getHideFromPublicFeedsList();
  2383. if ($local && $remote) {
  2384. $feed = Status::select(
  2385. 'id',
  2386. 'uri',
  2387. 'type',
  2388. 'scope',
  2389. 'created_at',
  2390. 'profile_id',
  2391. 'in_reply_to_id',
  2392. 'reblog_of_id'
  2393. )
  2394. ->when($minOrMax, function ($q, $minOrMax) use ($min, $max) {
  2395. $dir = $min ? '>' : '<';
  2396. $id = $min ?? $max;
  2397. return $q->where('id', $dir, $id);
  2398. })
  2399. ->whereNull(['in_reply_to_id', 'reblog_of_id'])
  2400. ->when($hideNsfw, function ($q, $hideNsfw) {
  2401. return $q->where('is_nsfw', false);
  2402. })
  2403. ->whereIn('type', ['photo', 'photo:album', 'video', 'video:album', 'photo:video:album'])
  2404. ->whereScope('public')
  2405. ->where('id', '>', $amin)
  2406. ->orderByDesc('id')
  2407. ->limit(($limit * 2))
  2408. ->pluck('id')
  2409. ->values()
  2410. ->toArray();
  2411. } elseif ($remote && ! $local) {
  2412. if (config('instance.timeline.network.cached')) {
  2413. Cache::remember('api:v1:timelines:network:cache_check', 10368000, function () {
  2414. if (NetworkTimelineService::count() == 0) {
  2415. NetworkTimelineService::warmCache(true, config('instance.timeline.network.cache_dropoff'));
  2416. }
  2417. });
  2418. if ($max) {
  2419. $feed = NetworkTimelineService::getRankedMaxId($max, $limit + 5);
  2420. } elseif ($min) {
  2421. $feed = NetworkTimelineService::getRankedMinId($min, $limit + 5);
  2422. } else {
  2423. $feed = NetworkTimelineService::get(0, $limit + 5);
  2424. }
  2425. } else {
  2426. $feed = Status::select(
  2427. 'id',
  2428. 'uri',
  2429. 'type',
  2430. 'scope',
  2431. 'local',
  2432. 'created_at',
  2433. 'profile_id',
  2434. 'in_reply_to_id',
  2435. 'reblog_of_id'
  2436. )
  2437. ->when($minOrMax, function ($q, $minOrMax) use ($min, $max) {
  2438. $dir = $min ? '>' : '<';
  2439. $id = $min ?? $max;
  2440. return $q->where('id', $dir, $id);
  2441. })
  2442. ->whereNull(['in_reply_to_id', 'reblog_of_id'])
  2443. ->when($hideNsfw, function ($q, $hideNsfw) {
  2444. return $q->where('is_nsfw', false);
  2445. })
  2446. ->whereIn('type', ['photo', 'photo:album', 'video', 'video:album', 'photo:video:album'])
  2447. ->whereLocal(false)
  2448. ->whereScope('public')
  2449. ->where('id', '>', $amin)
  2450. ->orderByDesc('id')
  2451. ->limit(($limit * 2))
  2452. ->pluck('id')
  2453. ->values()
  2454. ->toArray();
  2455. }
  2456. } else {
  2457. if (config('instance.timeline.local.cached')) {
  2458. Cache::remember('api:v1:timelines:public:cache_check', 10368000, function () {
  2459. if (PublicTimelineService::count() == 0) {
  2460. PublicTimelineService::warmCache(true, 400);
  2461. }
  2462. });
  2463. if ($max) {
  2464. $feed = PublicTimelineService::getRankedMaxId($max, $limit + 5);
  2465. } elseif ($min) {
  2466. $feed = PublicTimelineService::getRankedMinId($min, $limit + 5);
  2467. } else {
  2468. $feed = PublicTimelineService::get(0, $limit + 5);
  2469. }
  2470. } else {
  2471. $feed = Status::select(
  2472. 'id',
  2473. 'uri',
  2474. 'type',
  2475. 'scope',
  2476. 'local',
  2477. 'created_at',
  2478. 'profile_id',
  2479. 'in_reply_to_id',
  2480. 'reblog_of_id'
  2481. )
  2482. ->when($minOrMax, function ($q, $minOrMax) use ($min, $max) {
  2483. $dir = $min ? '>' : '<';
  2484. $id = $min ?? $max;
  2485. return $q->where('id', $dir, $id);
  2486. })
  2487. ->whereNull(['in_reply_to_id', 'reblog_of_id'])
  2488. ->when($hideNsfw, function ($q, $hideNsfw) {
  2489. return $q->where('is_nsfw', false);
  2490. })
  2491. ->whereIn('type', ['photo', 'photo:album', 'video', 'video:album', 'photo:video:album'])
  2492. ->whereLocal(true)
  2493. ->whereScope('public')
  2494. ->where('id', '>', $amin)
  2495. ->orderByDesc('id')
  2496. ->limit(($limit * 2))
  2497. ->pluck('id')
  2498. ->values()
  2499. ->toArray();
  2500. }
  2501. }
  2502. $res = collect($feed)
  2503. ->filter(function ($k) use ($min, $max) {
  2504. if (! $min && ! $max) {
  2505. return true;
  2506. }
  2507. if ($min) {
  2508. return $min != $k;
  2509. }
  2510. if ($max) {
  2511. return $max != $k;
  2512. }
  2513. })
  2514. ->map(function ($k) use ($user, $napi) {
  2515. try {
  2516. $status = $napi ? StatusService::get($k) : StatusService::getMastodon($k);
  2517. if (! $status || ! isset($status['account']) || ! isset($status['account']['id'])) {
  2518. return false;
  2519. }
  2520. } catch (\Exception $e) {
  2521. return false;
  2522. }
  2523. $account = $napi ? AccountService::get($status['account']['id'], true) : AccountService::getMastodon($status['account']['id'], true);
  2524. if (! $account) {
  2525. return false;
  2526. }
  2527. $status['account'] = $account;
  2528. if ($user) {
  2529. $status['favourited'] = (bool) LikeService::liked($user->profile_id, $k);
  2530. $status['reblogged'] = (bool) ReblogService::get($user->profile_id, $status['id']);
  2531. $status['bookmarked'] = (bool) BookmarkService::get($user->profile_id, $status['id']);
  2532. }
  2533. return $status;
  2534. })
  2535. ->filter(function ($s) use ($filtered) {
  2536. return $s && isset($s['account']) && in_array($s['account']['id'], $filtered) == false;
  2537. })
  2538. ->filter(function ($s) use ($domainBlocks) {
  2539. if (! $domainBlocks || ! count($domainBlocks)) {
  2540. return $s;
  2541. }
  2542. $domain = strtolower(parse_url($s['url'], PHP_URL_HOST));
  2543. return ! in_array($domain, $domainBlocks);
  2544. })
  2545. ->filter(function ($s) use ($asf, $user) {
  2546. if (! $asf || count($asf) === 0) {
  2547. return true;
  2548. }
  2549. if (in_array($s['account']['id'], $asf)) {
  2550. if ($user->profile_id == $s['account']['id']) {
  2551. return true;
  2552. }
  2553. return false;
  2554. }
  2555. return true;
  2556. })
  2557. ->take($limit)
  2558. ->values();
  2559. $baseUrl = config('app.url').'/api/v1/timelines/public?limit='.$limit.'&';
  2560. if ($remote) {
  2561. $baseUrl .= 'remote=1&';
  2562. }
  2563. if ($local) {
  2564. $baseUrl .= 'local=1&';
  2565. }
  2566. $minId = $res->map(function ($s) {
  2567. return ['id' => $s['id']];
  2568. })->min('id');
  2569. $maxId = $res->map(function ($s) {
  2570. return ['id' => $s['id']];
  2571. })->max('id');
  2572. if ($minId == $maxId) {
  2573. $minId = null;
  2574. }
  2575. if ($maxId && $res->count() >= $limit) {
  2576. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next"';
  2577. }
  2578. if ($minId) {
  2579. $link = '<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  2580. }
  2581. if ($maxId && $minId) {
  2582. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next",<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  2583. }
  2584. $headers = isset($link) ? ['Link' => $link] : [];
  2585. return $this->json($res->toArray(), 200, $headers);
  2586. }
  2587. /**
  2588. * GET /api/v1/conversations
  2589. *
  2590. * Not implemented
  2591. *
  2592. * @return array
  2593. */
  2594. public function conversations(Request $request)
  2595. {
  2596. abort_if(! $request->user() || ! $request->user()->token(), 403);
  2597. abort_unless($request->user()->tokenCan('read'), 403);
  2598. $this->validate($request, [
  2599. 'limit' => 'sometimes|integer|min:1|max:40',
  2600. 'scope' => 'nullable|in:inbox,sent,requests',
  2601. 'min_id' => 'nullable|integer',
  2602. 'max_id' => 'nullable|integer',
  2603. 'since_id' => 'nullable|integer',
  2604. ]);
  2605. $limit = $request->input('limit', 20);
  2606. if ($limit > 20) {
  2607. $limit = 20;
  2608. }
  2609. $scope = $request->input('scope', 'inbox');
  2610. $user = $request->user();
  2611. $min_id = $request->input('min_id');
  2612. $max_id = $request->input('max_id');
  2613. $since_id = $request->input('since_id');
  2614. if ($user->has_roles && ! UserRoleService::can('can-direct-message', $user->id)) {
  2615. return [];
  2616. }
  2617. $pid = $user->profile_id;
  2618. $isPgsql = config('database.default') == 'pgsql';
  2619. if ($isPgsql) {
  2620. $dms = DirectMessage::when($scope === 'inbox', function ($q) use ($pid) {
  2621. return $q->whereIsHidden(false)
  2622. ->where(function ($query) use ($pid) {
  2623. $query->where('to_id', $pid)
  2624. ->orWhere('from_id', $pid);
  2625. });
  2626. })
  2627. ->when($scope === 'sent', function ($q) use ($pid) {
  2628. return $q->whereFromId($pid)
  2629. ->groupBy(['to_id', 'id']);
  2630. })
  2631. ->when($scope === 'requests', function ($q) use ($pid) {
  2632. return $q->whereToId($pid)
  2633. ->whereIsHidden(true);
  2634. });
  2635. } else {
  2636. $dms = Conversation::when($scope === 'inbox', function ($q) use ($pid) {
  2637. return $q->whereIsHidden(false)
  2638. ->where(function ($query) use ($pid) {
  2639. $query->where('to_id', $pid)
  2640. ->orWhere('from_id', $pid);
  2641. })
  2642. ->orderByDesc('status_id')
  2643. ->groupBy(['to_id', 'from_id']);
  2644. })
  2645. ->when($scope === 'sent', function ($q) use ($pid) {
  2646. return $q->whereFromId($pid)
  2647. ->groupBy('to_id');
  2648. })
  2649. ->when($scope === 'requests', function ($q) use ($pid) {
  2650. return $q->whereToId($pid)
  2651. ->whereIsHidden(true);
  2652. });
  2653. }
  2654. if ($min_id) {
  2655. $dms = $dms->where('id', '>', $min_id);
  2656. }
  2657. if ($max_id) {
  2658. $dms = $dms->where('id', '<', $max_id);
  2659. }
  2660. if ($since_id) {
  2661. $dms = $dms->where('id', '>', $since_id);
  2662. }
  2663. $dms = $dms->orderByDesc('status_id')->orderBy('id');
  2664. $dmResults = $dms->limit($limit + 1)->get();
  2665. $hasNextPage = $dmResults->count() > $limit;
  2666. if ($hasNextPage) {
  2667. $dmResults = $dmResults->take($limit);
  2668. }
  2669. $transformedDms = $dmResults->map(function ($dm) use ($pid) {
  2670. $from = $pid == $dm->to_id ? $dm->from_id : $dm->to_id;
  2671. return [
  2672. 'id' => $dm->id,
  2673. 'unread' => false,
  2674. 'accounts' => [
  2675. AccountService::getMastodon($from, true),
  2676. ],
  2677. 'last_status' => StatusService::getDirectMessage($dm->status_id),
  2678. ];
  2679. })
  2680. ->filter(function ($dm) {
  2681. return $dm
  2682. && ! empty($dm['last_status'])
  2683. && isset($dm['accounts'])
  2684. && count($dm['accounts'])
  2685. && isset($dm['accounts'][0])
  2686. && isset($dm['accounts'][0]['id']);
  2687. })
  2688. ->unique(function ($item) {
  2689. return $item['accounts'][0]['id'];
  2690. })
  2691. ->values();
  2692. $links = [];
  2693. if (! $transformedDms->isEmpty()) {
  2694. $baseUrl = url()->current().'?'.http_build_query(array_merge(
  2695. $request->except(['min_id', 'max_id', 'since_id']),
  2696. ['limit' => $limit]
  2697. ));
  2698. $firstId = $transformedDms->first()['id'];
  2699. $lastId = $transformedDms->last()['id'];
  2700. $firstLink = $baseUrl;
  2701. $links[] = '<'.$firstLink.'>; rel="first"';
  2702. if ($hasNextPage) {
  2703. $nextLink = $baseUrl.'&max_id='.$lastId;
  2704. $links[] = '<'.$nextLink.'>; rel="next"';
  2705. }
  2706. if ($max_id || $since_id) {
  2707. $prevLink = $baseUrl.'&min_id='.$firstId;
  2708. $links[] = '<'.$prevLink.'>; rel="prev"';
  2709. }
  2710. }
  2711. if (! empty($links)) {
  2712. return response()->json($transformedDms->toArray())
  2713. ->header('Link', implode(', ', $links));
  2714. }
  2715. return $this->json($transformedDms);
  2716. }
  2717. /**
  2718. * GET /api/v1/statuses/{id}
  2719. *
  2720. * @param int $id
  2721. * @return StatusTransformer
  2722. */
  2723. public function statusById(Request $request, $id)
  2724. {
  2725. abort_if(! $request->user() || ! $request->user()->token(), 403);
  2726. abort_unless($request->user()->tokenCan('read'), 403);
  2727. AccountService::setLastActive($request->user()->id);
  2728. $pid = $request->user()->profile_id;
  2729. $res = $request->has(self::PF_API_ENTITY_KEY) ? StatusService::get($id, false) : StatusService::getMastodon($id, false);
  2730. if (! $res || ! isset($res['visibility'])) {
  2731. abort(404);
  2732. }
  2733. if ($res && isset($res['account'], $res['account']['acct'], $res['account']['url']) && strpos($res['account']['acct'], '@') != -1) {
  2734. $domain = parse_url($res['account']['url'], PHP_URL_HOST);
  2735. abort_if(in_array($domain, InstanceService::getBannedDomains()), 404);
  2736. }
  2737. $scope = $res['visibility'];
  2738. if (! in_array($scope, ['public', 'unlisted'])) {
  2739. if ($scope === 'private') {
  2740. if (intval($res['account']['id']) !== intval($pid)) {
  2741. abort_unless(FollowerService::follows($pid, $res['account']['id']), 403);
  2742. }
  2743. } else {
  2744. abort(400, 'Invalid request');
  2745. }
  2746. }
  2747. if (! empty($res['reblog']) && isset($res['reblog']['id'])) {
  2748. $res['reblog']['favourited'] = (bool) LikeService::liked($pid, $res['reblog']['id']);
  2749. $res['reblog']['reblogged'] = (bool) ReblogService::get($pid, $res['reblog']['id']);
  2750. $res['reblog']['bookmarked'] = BookmarkService::get($pid, $res['reblog']['id']);
  2751. }
  2752. $res['favourited'] = LikeService::liked($pid, $res['id']);
  2753. $res['reblogged'] = ReblogService::get($pid, $res['id']);
  2754. $res['bookmarked'] = BookmarkService::get($pid, $res['id']);
  2755. return $this->json($res);
  2756. }
  2757. /**
  2758. * GET /api/v1/statuses/{id}/context
  2759. *
  2760. * @param int $id
  2761. * @return StatusTransformer
  2762. */
  2763. public function statusContext(Request $request, $id)
  2764. {
  2765. abort_if(! $request->user() || ! $request->user()->token(), 403);
  2766. abort_unless($request->user()->tokenCan('read'), 403);
  2767. $user = $request->user();
  2768. $pid = $user->profile_id;
  2769. $status = StatusService::getMastodon($id, false);
  2770. $pe = $request->has(self::PF_API_ENTITY_KEY);
  2771. if (! $status || ! isset($status['account'])) {
  2772. return response('', 404);
  2773. }
  2774. if ($status && isset($status['account'], $status['account']['acct']) && strpos($status['account']['acct'], '@') != -1) {
  2775. $domain = parse_url($status['account']['url'], PHP_URL_HOST);
  2776. abort_if(in_array($domain, InstanceService::getBannedDomains()), 404);
  2777. }
  2778. if (intval($status['account']['id']) !== intval($user->profile_id)) {
  2779. if ($status['visibility'] == 'private') {
  2780. if (! FollowerService::follows($user->profile_id, $status['account']['id'])) {
  2781. return response('', 404);
  2782. }
  2783. } else {
  2784. if (! in_array($status['visibility'], ['public', 'unlisted'])) {
  2785. return response('', 404);
  2786. }
  2787. }
  2788. }
  2789. $ancestors = [];
  2790. $descendants = [];
  2791. if ($status['in_reply_to_id']) {
  2792. $ancestors[] = $pe ?
  2793. StatusService::get($status['in_reply_to_id'], false) :
  2794. StatusService::getMastodon($status['in_reply_to_id'], false);
  2795. }
  2796. if ($status['replies_count']) {
  2797. $filters = UserFilterService::filters($pid);
  2798. $descendants = DB::table('statuses')
  2799. ->where('in_reply_to_id', $id)
  2800. ->limit(20)
  2801. ->pluck('id')
  2802. ->map(function ($sid) use ($pe) {
  2803. return $pe ?
  2804. StatusService::get($sid, false) :
  2805. StatusService::getMastodon($sid, false);
  2806. })
  2807. ->filter(function ($post) use ($filters) {
  2808. return $post && isset($post['account'], $post['account']['id']) && ! in_array($post['account']['id'], $filters);
  2809. })
  2810. ->map(function ($status) use ($pid) {
  2811. $status['favourited'] = LikeService::liked($pid, $status['id']);
  2812. $status['reblogged'] = ReblogService::get($pid, $status['id']);
  2813. return $status;
  2814. })
  2815. ->values();
  2816. }
  2817. $res = [
  2818. 'ancestors' => $ancestors,
  2819. 'descendants' => $descendants,
  2820. ];
  2821. return $this->json($res);
  2822. }
  2823. /**
  2824. * GET /api/v1/statuses/{id}/card
  2825. *
  2826. * @param int $id
  2827. * @return StatusTransformer
  2828. */
  2829. public function statusCard(Request $request, $id)
  2830. {
  2831. abort_if(! $request->user() || ! $request->user()->token(), 403);
  2832. abort_unless($request->user()->tokenCan('read'), 403);
  2833. $res = [];
  2834. return response()->json($res);
  2835. }
  2836. /**
  2837. * GET /api/v1/statuses/{id}/reblogged_by
  2838. *
  2839. * @param int $id
  2840. * @return AccountTransformer
  2841. */
  2842. public function statusRebloggedBy(Request $request, $id)
  2843. {
  2844. abort_if(! $request->user() || ! $request->user()->token(), 403);
  2845. abort_unless($request->user()->tokenCan('read'), 403);
  2846. $this->validate($request, [
  2847. 'limit' => 'sometimes|integer|min:1|max:80',
  2848. ]);
  2849. $limit = $request->input('limit', 10);
  2850. $user = $request->user();
  2851. $pid = $user->profile_id;
  2852. $status = Status::findOrFail($id);
  2853. $account = AccountService::get($status->profile_id, true);
  2854. abort_if(! $account, 404);
  2855. abort_if(isset($account['moved'], $account['moved']['id']), 404, 'Account moved');
  2856. if ($account && strpos($account['acct'], '@') != -1) {
  2857. $domain = parse_url($account['url'], PHP_URL_HOST);
  2858. abort_if(in_array($domain, InstanceService::getBannedDomains()), 404);
  2859. }
  2860. $author = intval($status->profile_id) === intval($pid) || $user->is_admin;
  2861. $napi = $request->has(self::PF_API_ENTITY_KEY);
  2862. abort_if(
  2863. ! $status->type ||
  2864. ! in_array($status->type, ['photo', 'photo:album', 'photo:video:album', 'reply', 'text', 'video', 'video:album']),
  2865. 404,
  2866. );
  2867. if (! $author) {
  2868. if ($status->scope == 'private') {
  2869. abort_if(! FollowerService::follows($pid, $status->profile_id), 403);
  2870. } else {
  2871. abort_if(! in_array($status->scope, ['public', 'unlisted']), 403);
  2872. }
  2873. if ($request->has('cursor')) {
  2874. return $this->json([]);
  2875. }
  2876. }
  2877. $res = Status::where('reblog_of_id', $status->id)
  2878. ->orderByDesc('id')
  2879. ->cursorPaginate($limit)
  2880. ->withQueryString();
  2881. if (! $res) {
  2882. return $this->json([]);
  2883. }
  2884. $headers = [];
  2885. if ($author && $res->hasPages()) {
  2886. $links = '';
  2887. if ($res->onFirstPage()) {
  2888. if ($res->nextPageUrl()) {
  2889. $links = '<'.$res->nextPageUrl().'>; rel="prev"';
  2890. }
  2891. } else {
  2892. if ($res->previousPageUrl()) {
  2893. $links = '<'.$res->previousPageUrl().'>; rel="next"';
  2894. }
  2895. if ($res->nextPageUrl()) {
  2896. if (! empty($links)) {
  2897. $links .= ', ';
  2898. }
  2899. $links .= '<'.$res->nextPageUrl().'>; rel="prev"';
  2900. }
  2901. }
  2902. $headers = ['Link' => $links];
  2903. }
  2904. $res = $res->map(function ($status) use ($pid, $napi) {
  2905. $account = $napi ? AccountService::get($status->profile_id, true) : AccountService::getMastodon($status->profile_id, true);
  2906. if (! $account) {
  2907. return false;
  2908. }
  2909. if ($napi) {
  2910. $account['follows'] = $status->profile_id == $pid ? null : FollowerService::follows($pid, $status->profile_id);
  2911. }
  2912. return $account;
  2913. })
  2914. ->filter(function ($account) {
  2915. return $account && isset($account['id']);
  2916. })
  2917. ->values();
  2918. return $this->json($res, 200, $headers);
  2919. }
  2920. /**
  2921. * GET /api/v1/statuses/{id}/favourited_by
  2922. *
  2923. * @param int $id
  2924. * @return AccountTransformer
  2925. */
  2926. public function statusFavouritedBy(Request $request, $id)
  2927. {
  2928. abort_if(! $request->user() || ! $request->user()->token(), 403);
  2929. abort_unless($request->user()->tokenCan('read'), 403);
  2930. $this->validate($request, [
  2931. 'limit' => 'sometimes|integer|min:1',
  2932. ]);
  2933. $limit = $request->input('limit', 40);
  2934. if ($limit > 80) {
  2935. $limit = 80;
  2936. }
  2937. $user = $request->user();
  2938. $pid = $user->profile_id;
  2939. $status = Status::findOrFail($id);
  2940. $account = AccountService::get($status->profile_id, true);
  2941. abort_if(! $account, 404);
  2942. abort_if(isset($account['moved'], $account['moved']['id']), 404, 'Account moved');
  2943. if ($account && strpos($account['acct'], '@') != -1) {
  2944. $domain = parse_url($account['url'], PHP_URL_HOST);
  2945. abort_if(in_array($domain, InstanceService::getBannedDomains()), 404);
  2946. }
  2947. $author = intval($status->profile_id) === intval($pid) || $user->is_admin;
  2948. $napi = $request->has(self::PF_API_ENTITY_KEY);
  2949. abort_if(
  2950. ! $status->type ||
  2951. ! in_array($status->type, ['photo', 'photo:album', 'photo:video:album', 'reply', 'text', 'video', 'video:album']),
  2952. 404,
  2953. );
  2954. if (! $author) {
  2955. if ($status->scope == 'private') {
  2956. abort_if(! FollowerService::follows($pid, $status->profile_id), 403);
  2957. } else {
  2958. abort_if(! in_array($status->scope, ['public', 'unlisted']), 403);
  2959. }
  2960. if ($request->has('cursor')) {
  2961. return $this->json([]);
  2962. }
  2963. }
  2964. $res = Like::where('status_id', $status->id)
  2965. ->orderByDesc('id')
  2966. ->cursorPaginate($limit)
  2967. ->withQueryString();
  2968. if (! $res) {
  2969. return $this->json([]);
  2970. }
  2971. $headers = [];
  2972. if ($author && $res->hasPages()) {
  2973. $links = '';
  2974. if ($res->onFirstPage()) {
  2975. if ($res->nextPageUrl()) {
  2976. $links = '<'.$res->nextPageUrl().'>; rel="prev"';
  2977. }
  2978. } else {
  2979. if ($res->previousPageUrl()) {
  2980. $links = '<'.$res->previousPageUrl().'>; rel="next"';
  2981. }
  2982. if ($res->nextPageUrl()) {
  2983. if (! empty($links)) {
  2984. $links .= ', ';
  2985. }
  2986. $links .= '<'.$res->nextPageUrl().'>; rel="prev"';
  2987. }
  2988. }
  2989. $headers = ['Link' => $links];
  2990. }
  2991. $res = $res->map(function ($like) use ($pid, $napi) {
  2992. $account = $napi ? AccountService::get($like->profile_id, true) : AccountService::getMastodon($like->profile_id, true);
  2993. if (! $account) {
  2994. return false;
  2995. }
  2996. if ($napi) {
  2997. $account['follows'] = $like->profile_id == $pid ? null : FollowerService::follows($pid, $like->profile_id);
  2998. }
  2999. return $account;
  3000. })
  3001. ->filter(function ($account) {
  3002. return $account && isset($account['id']);
  3003. })
  3004. ->values();
  3005. return $this->json($res, 200, $headers);
  3006. }
  3007. /**
  3008. * POST /api/v1/statuses
  3009. *
  3010. *
  3011. * @return StatusTransformer
  3012. */
  3013. public function statusCreate(Request $request)
  3014. {
  3015. abort_if(! $request->user() || ! $request->user()->token(), 403);
  3016. abort_unless($request->user()->tokenCan('write'), 403);
  3017. $this->validate($request, [
  3018. 'status' => 'nullable|string|max:'.(int) config_cache('pixelfed.max_caption_length'),
  3019. 'in_reply_to_id' => 'nullable',
  3020. 'media_ids' => 'sometimes|array|max:'.(int) config_cache('pixelfed.max_album_length'),
  3021. 'sensitive' => 'nullable',
  3022. 'visibility' => 'string|in:private,unlisted,public,direct',
  3023. 'spoiler_text' => 'sometimes|max:140',
  3024. 'place_id' => 'sometimes|integer|min:1|max:128769',
  3025. 'collection_ids' => 'sometimes|array|max:3',
  3026. 'comments_disabled' => 'sometimes|boolean',
  3027. ]);
  3028. if ($request->filled('visibility') && $request->input('visibility') === 'direct') {
  3029. return $this->json([
  3030. 'error' => 'Direct visibility is not available.',
  3031. ], 400);
  3032. }
  3033. if ($request->hasHeader('idempotency-key')) {
  3034. $key = 'pf:api:v1:status:idempotency-key:'.$request->user()->id.':'.hash('sha1', $request->header('idempotency-key'));
  3035. $exists = Cache::has($key);
  3036. abort_if($exists, 400, 'Duplicate idempotency key.');
  3037. Cache::put($key, 1, 3600);
  3038. }
  3039. if (config('costar.enabled') == true) {
  3040. $blockedKeywords = config('costar.keyword.block');
  3041. if ($blockedKeywords !== null && $request->status) {
  3042. $keywords = config('costar.keyword.block');
  3043. foreach ($keywords as $kw) {
  3044. if (Str::contains($request->status, $kw) == true) {
  3045. abort(400, 'Invalid object. Contains banned keyword.');
  3046. }
  3047. }
  3048. }
  3049. }
  3050. if (! $request->filled('media_ids') && ! $request->filled('in_reply_to_id')) {
  3051. abort(403, 'Empty statuses are not allowed');
  3052. }
  3053. $ids = $request->input('media_ids');
  3054. $in_reply_to_id = $request->input('in_reply_to_id');
  3055. $user = $request->user();
  3056. if ($user->has_roles) {
  3057. if ($in_reply_to_id != null) {
  3058. abort_if(! UserRoleService::can('can-comment', $user->id), 403, 'Invalid permissions for this action');
  3059. } else {
  3060. abort_if(! UserRoleService::can('can-post', $user->id), 403, 'Invalid permissions for this action');
  3061. }
  3062. }
  3063. $profile = $user->profile;
  3064. $limitKey = 'compose:rate-limit:store:'.$user->id;
  3065. $limitTtl = now()->addMinutes(15);
  3066. $limitReached = Cache::remember($limitKey, $limitTtl, function () use ($user) {
  3067. $minId = SnowflakeService::byDate(now()->subDays(1));
  3068. $dailyLimit = Status::whereProfileId($user->profile_id)
  3069. ->where('id', '>', $minId)
  3070. ->count();
  3071. return $dailyLimit >= 1000;
  3072. });
  3073. abort_if($limitReached == true, 429);
  3074. $visibility = $profile->is_private ? 'private' : (
  3075. $profile->unlisted == true &&
  3076. $request->input('visibility', 'public') == 'public' ?
  3077. 'unlisted' :
  3078. $request->input('visibility', 'public'));
  3079. if ($user->last_active_at == null) {
  3080. return [];
  3081. }
  3082. $defaultCaption = '';
  3083. $content = $request->filled('status') ? strip_tags($request->input('status')) : $defaultCaption;
  3084. $cw = $user->profile->cw == true ? true : $request->boolean('sensitive', false);
  3085. $spoilerText = $cw && $request->filled('spoiler_text') ? $request->input('spoiler_text') : null;
  3086. if ($in_reply_to_id) {
  3087. $parent = Status::findOrFail($in_reply_to_id);
  3088. if ($parent->comments_disabled) {
  3089. return $this->json('Comments have been disabled on this post', 422);
  3090. }
  3091. $blocks = UserFilterService::blocks($parent->profile_id);
  3092. abort_if(in_array($profile->id, $blocks), 422, 'Cannot reply to this post at this time.');
  3093. $status = new Status;
  3094. $status->caption = $content;
  3095. $status->rendered = $defaultCaption;
  3096. $status->scope = $visibility;
  3097. $status->visibility = $visibility;
  3098. $status->profile_id = $user->profile_id;
  3099. $status->is_nsfw = $cw;
  3100. $status->cw_summary = $spoilerText;
  3101. $status->in_reply_to_id = $parent->id;
  3102. $status->in_reply_to_profile_id = $parent->profile_id;
  3103. $status->save();
  3104. StatusService::del($parent->id);
  3105. Cache::forget('status:replies:all:'.$parent->id);
  3106. }
  3107. if ($ids) {
  3108. if (Media::whereUserId($user->id)
  3109. ->whereNull('status_id')
  3110. ->find($ids)
  3111. ->count() == 0
  3112. ) {
  3113. abort(400, 'Invalid media_ids');
  3114. }
  3115. if (! $in_reply_to_id) {
  3116. $status = new Status;
  3117. $status->caption = $content;
  3118. $status->rendered = $defaultCaption;
  3119. $status->profile_id = $user->profile_id;
  3120. $status->is_nsfw = $cw;
  3121. $status->cw_summary = $spoilerText;
  3122. $status->scope = 'draft';
  3123. $status->visibility = 'draft';
  3124. if ($request->has('place_id')) {
  3125. $status->place_id = $request->input('place_id');
  3126. }
  3127. $status->save();
  3128. }
  3129. $mimes = [];
  3130. foreach ($ids as $k => $v) {
  3131. if ($k + 1 > (int) config_cache('pixelfed.max_album_length')) {
  3132. continue;
  3133. }
  3134. $m = Media::whereUserId($user->id)->whereNull('status_id')->findOrFail($v);
  3135. if ($m->profile_id !== $user->profile_id || $m->status_id) {
  3136. abort(403, 'Invalid media id');
  3137. }
  3138. $m->order = $k + 1;
  3139. $m->status_id = $status->id;
  3140. $m->save();
  3141. array_push($mimes, $m->mime);
  3142. }
  3143. if (empty($mimes)) {
  3144. $status->delete();
  3145. abort(400, 'Invalid media ids');
  3146. }
  3147. if ($request->has('comments_disabled') && $request->input('comments_disabled')) {
  3148. $status->comments_disabled = true;
  3149. }
  3150. $status->scope = $visibility;
  3151. $status->visibility = $visibility;
  3152. $status->type = StatusController::mimeTypeCheck($mimes);
  3153. $status->save();
  3154. }
  3155. if (! $status) {
  3156. abort(500, 'An error occured.');
  3157. }
  3158. NewStatusPipeline::dispatch($status);
  3159. if ($status->in_reply_to_id) {
  3160. CommentPipeline::dispatch($parent, $status);
  3161. }
  3162. Cache::forget('user:account:id:'.$user->id);
  3163. Cache::forget('_api:statuses:recent_9:'.$user->profile_id);
  3164. Cache::forget('profile:status_count:'.$user->profile_id);
  3165. Cache::forget($user->storageUsedKey());
  3166. Cache::forget('profile:embed:'.$status->profile_id);
  3167. Cache::forget($limitKey);
  3168. if ($request->has('collection_ids') && $ids) {
  3169. $collections = Collection::whereProfileId($user->profile_id)
  3170. ->find($request->input('collection_ids'))
  3171. ->each(function ($collection) use ($status) {
  3172. $count = $collection->items()->count();
  3173. $item = CollectionItem::firstOrCreate([
  3174. 'collection_id' => $collection->id,
  3175. 'object_type' => 'App\Status',
  3176. 'object_id' => $status->id,
  3177. ], [
  3178. 'order' => $count,
  3179. ]);
  3180. CollectionService::addItem(
  3181. $collection->id,
  3182. $status->id,
  3183. $count
  3184. );
  3185. $collection->updated_at = now();
  3186. $collection->save();
  3187. CollectionService::setCollection($collection->id, $collection);
  3188. });
  3189. }
  3190. $res = StatusService::getMastodon($status->id, false);
  3191. $res['favourited'] = false;
  3192. $res['language'] = 'en';
  3193. $res['bookmarked'] = false;
  3194. $res['card'] = null;
  3195. return $this->json($res);
  3196. }
  3197. /**
  3198. * DELETE /api/v1/statuses
  3199. *
  3200. * @param int $id
  3201. * @return null
  3202. */
  3203. public function statusDelete(Request $request, $id)
  3204. {
  3205. abort_if(! $request->user() || ! $request->user()->token(), 403);
  3206. abort_unless($request->user()->tokenCan('write'), 403);
  3207. AccountService::setLastActive($request->user()->id);
  3208. $status = Status::whereProfileId($request->user()->profile->id)
  3209. ->findOrFail($id);
  3210. $resource = new Fractal\Resource\Item($status, new StatusTransformer);
  3211. Cache::forget('profile:status_count:'.$status->profile_id);
  3212. StatusDelete::dispatch($status);
  3213. $res = $this->fractal->createData($resource)->toArray();
  3214. $res['text'] = $res['content'];
  3215. unset($res['content']);
  3216. return $this->json($res);
  3217. }
  3218. /**
  3219. * POST /api/v1/statuses/{id}/reblog
  3220. *
  3221. * @param int $id
  3222. * @return StatusTransformer
  3223. */
  3224. public function statusShare(Request $request, $id)
  3225. {
  3226. abort_if(! $request->user() || ! $request->user()->token(), 403);
  3227. abort_unless($request->user()->tokenCan('write'), 403);
  3228. $user = $request->user();
  3229. abort_if($user->has_roles && ! UserRoleService::can('can-share', $user->id), 403, 'Invalid permissions for this action');
  3230. AccountService::setLastActive($user->id);
  3231. $status = Status::whereScope('public')->findOrFail($id);
  3232. $account = AccountService::get($status->profile_id);
  3233. abort_if(isset($account['moved'], $account['moved']['id']), 422, 'Cannot share a post from an account that has migrated');
  3234. if ($status && ($status->uri || $status->url || $status->object_url)) {
  3235. $url = $status->uri ?? $status->url ?? $status->object_url;
  3236. $domain = parse_url($url, PHP_URL_HOST);
  3237. abort_if(in_array($domain, InstanceService::getBannedDomains()), 404);
  3238. }
  3239. if (intval($status->profile_id) !== intval($user->profile_id)) {
  3240. if ($status->scope == 'private') {
  3241. abort_if(! FollowerService::follows($user->profile_id, $status->profile_id), 403);
  3242. } else {
  3243. abort_if(! in_array($status->scope, ['public', 'unlisted']), 403);
  3244. }
  3245. $blocks = UserFilterService::blocks($status->profile_id);
  3246. if ($blocks && in_array($user->profile_id, $blocks)) {
  3247. abort(422);
  3248. }
  3249. }
  3250. $defaultCaption = config_cache('database.default') === 'mysql' ? null : '';
  3251. $share = Status::firstOrCreate([
  3252. 'caption' => $defaultCaption,
  3253. 'rendered' => $defaultCaption,
  3254. 'profile_id' => $user->profile_id,
  3255. 'reblog_of_id' => $status->id,
  3256. 'type' => 'share',
  3257. 'in_reply_to_profile_id' => $status->profile_id,
  3258. 'scope' => 'public',
  3259. 'visibility' => 'public',
  3260. ]);
  3261. SharePipeline::dispatch($share)->onQueue('low');
  3262. StatusService::del($status->id);
  3263. ReblogService::add($user->profile_id, $status->id);
  3264. $res = StatusService::getMastodon($status->id);
  3265. $res['reblogged'] = true;
  3266. $res['favourited'] = LikeService::liked($user->profile_id, $status->id);
  3267. $res['bookmarked'] = BookmarkService::get($user->profile_id, $status->id);
  3268. return $this->json($res);
  3269. }
  3270. /**
  3271. * POST /api/v1/statuses/{id}/unreblog
  3272. *
  3273. * @param int $id
  3274. * @return StatusTransformer
  3275. */
  3276. public function statusUnshare(Request $request, $id)
  3277. {
  3278. abort_if(! $request->user() || ! $request->user()->token(), 403);
  3279. abort_unless($request->user()->tokenCan('write'), 403);
  3280. $user = $request->user();
  3281. abort_if($user->has_roles && ! UserRoleService::can('can-share', $user->id), 403, 'Invalid permissions for this action');
  3282. AccountService::setLastActive($user->id);
  3283. $status = Status::whereScope('public')->findOrFail($id);
  3284. $account = AccountService::get($status->profile_id);
  3285. abort_if(isset($account['moved'], $account['moved']['id']), 422, 'Cannot unshare a post from an account that has migrated');
  3286. if (intval($status->profile_id) !== intval($user->profile_id)) {
  3287. if ($status->scope == 'private') {
  3288. abort_if(! FollowerService::follows($user->profile_id, $status->profile_id), 403);
  3289. } else {
  3290. abort_if(! in_array($status->scope, ['public', 'unlisted']), 403);
  3291. }
  3292. }
  3293. $reblog = Status::whereProfileId($user->profile_id)
  3294. ->whereReblogOfId($status->id)
  3295. ->first();
  3296. if (! $reblog) {
  3297. $res = StatusService::getMastodon($status->id);
  3298. $res['reblogged'] = false;
  3299. return $this->json($res);
  3300. }
  3301. UndoSharePipeline::dispatch($reblog)->onQueue('low');
  3302. ReblogService::del($user->profile_id, $status->id);
  3303. $res = StatusService::getMastodon($status->id);
  3304. $res['reblogged'] = false;
  3305. $res['favourited'] = LikeService::liked($user->profile_id, $status->id);
  3306. $res['bookmarked'] = BookmarkService::get($user->profile_id, $status->id);
  3307. return $this->json($res);
  3308. }
  3309. /**
  3310. * GET /api/v1/timelines/tag/{hashtag}
  3311. *
  3312. * @param string $hashtag
  3313. * @return StatusTransformer
  3314. */
  3315. public function timelineHashtag(Request $request, $hashtag)
  3316. {
  3317. abort_if(! $request->user() || ! $request->user()->token(), 403);
  3318. abort_unless($request->user()->tokenCan('read'), 403);
  3319. $this->validate($request, [
  3320. 'page' => 'nullable|integer|max:40',
  3321. 'min_id' => 'nullable|integer|min:0|max:'.PHP_INT_MAX,
  3322. 'max_id' => 'nullable|integer|min:0|max:'.PHP_INT_MAX,
  3323. 'limit' => 'sometimes|integer|min:1',
  3324. 'only_media' => 'sometimes',
  3325. '_pe' => 'sometimes',
  3326. ]);
  3327. $user = $request->user();
  3328. abort_if(
  3329. $user->has_roles && ! UserRoleService::can('can-view-hashtag-feed', $user->id),
  3330. 403,
  3331. 'Invalid permissions for this action'
  3332. );
  3333. if (config('database.default') === 'pgsql') {
  3334. $tag = Hashtag::where('name', 'ilike', $hashtag)
  3335. ->orWhere('slug', 'ilike', $hashtag)
  3336. ->first();
  3337. } else {
  3338. $tag = Hashtag::whereName($hashtag)
  3339. ->orWhere('slug', $hashtag)
  3340. ->first();
  3341. }
  3342. if (! $tag) {
  3343. return response()->json([]);
  3344. }
  3345. if ($tag->is_banned == true) {
  3346. return $this->json([]);
  3347. }
  3348. $min = $request->input('min_id');
  3349. $max = $request->input('max_id');
  3350. $limit = $request->input('limit', 20);
  3351. if ($limit > 40) {
  3352. $limit = 40;
  3353. }
  3354. $onlyMedia = $request->boolean('only_media', true);
  3355. $pe = $request->has(self::PF_API_ENTITY_KEY);
  3356. $pid = $request->user()->profile_id;
  3357. if ($min || $max) {
  3358. $minMax = SnowflakeService::byDate(now()->subMonths(6));
  3359. if ($min && intval($min) < $minMax) {
  3360. return [];
  3361. }
  3362. if ($max && intval($max) < $minMax) {
  3363. return [];
  3364. }
  3365. }
  3366. $filters = UserFilterService::filters($pid);
  3367. $domainBlocks = UserFilterService::domainBlocks($pid);
  3368. if (! $min && ! $max) {
  3369. $id = 1;
  3370. $dir = '>';
  3371. } else {
  3372. $dir = $min ? '>' : '<';
  3373. $id = $min ?? $max;
  3374. }
  3375. $res = StatusHashtag::whereHashtagId($tag->id)
  3376. ->where('status_id', $dir, $id)
  3377. ->orderBy('status_id', 'desc')
  3378. ->limit(100)
  3379. ->pluck('status_id')
  3380. ->map(function ($i) use ($pe) {
  3381. return $pe ? StatusService::get($i, false) : StatusService::getMastodon($i, false);
  3382. })
  3383. ->filter(function ($i) use ($onlyMedia, $pid) {
  3384. if (! $i || ! isset($i['account'], $i['account']['id'])) {
  3385. return false;
  3386. }
  3387. if ($i['visibility'] === 'unlisted') {
  3388. if ((int) $i['account']['id'] !== $pid) {
  3389. return false;
  3390. }
  3391. }
  3392. // if ($i['visibility'] === 'private') {
  3393. // if ((int) $i['account']['id'] !== $pid) {
  3394. // return FollowerService::follows($pid, $i['account']['id'], true);
  3395. // }
  3396. // }
  3397. if ($onlyMedia == true) {
  3398. if (! isset($i['media_attachments']) || ! count($i['media_attachments'])) {
  3399. return false;
  3400. }
  3401. }
  3402. return $i && isset($i['account'], $i['url']);
  3403. })
  3404. ->filter(function ($i) use ($filters, $domainBlocks) {
  3405. $domain = strtolower(parse_url($i['url'], PHP_URL_HOST));
  3406. return ! in_array($i['account']['id'], $filters) && ! in_array($domain, $domainBlocks);
  3407. })
  3408. ->take($limit)
  3409. ->values()
  3410. ->toArray();
  3411. return $this->json($res);
  3412. }
  3413. /**
  3414. * GET /api/v1/bookmarks
  3415. *
  3416. *
  3417. *
  3418. * @return StatusTransformer
  3419. */
  3420. public function bookmarks(Request $request)
  3421. {
  3422. abort_if(! $request->user() || ! $request->user()->token(), 403);
  3423. abort_unless($request->user()->tokenCan('read'), 403);
  3424. $this->validate($request, [
  3425. 'limit' => 'sometimes|integer|min:1',
  3426. 'max_id' => 'nullable|integer|min:0',
  3427. 'since_id' => 'nullable|integer|min:0',
  3428. 'min_id' => 'nullable|integer|min:0',
  3429. ]);
  3430. $pe = $request->has('_pe');
  3431. $pid = $request->user()->profile_id;
  3432. $limit = $request->input('limit') ?? 20;
  3433. if ($limit > 40) {
  3434. $limit = 40;
  3435. }
  3436. $max_id = $request->input('max_id');
  3437. $since_id = $request->input('since_id');
  3438. $min_id = $request->input('min_id');
  3439. $dir = $min_id ? '>' : '<';
  3440. $id = $min_id ?? $max_id;
  3441. $bookmarkQuery = Bookmark::whereProfileId($pid)
  3442. ->orderByDesc('id')
  3443. ->cursorPaginate($limit);
  3444. $bookmarks = $bookmarkQuery->map(function ($bookmark) use ($pid, $pe) {
  3445. $status = $pe ? StatusService::get($bookmark->status_id, false) : StatusService::getMastodon($bookmark->status_id, false);
  3446. if ($status) {
  3447. $status['bookmarked'] = true;
  3448. $status['favourited'] = LikeService::liked($pid, $status['id']);
  3449. $status['reblogged'] = ReblogService::get($pid, $status['id']);
  3450. }
  3451. return $status;
  3452. })
  3453. ->filter()
  3454. ->values()
  3455. ->toArray();
  3456. $links = null;
  3457. $headers = [];
  3458. if ($bookmarkQuery->nextCursor()) {
  3459. $links .= '<'.$bookmarkQuery->nextPageUrl().'&limit='.$limit.'>; rel="next"';
  3460. }
  3461. if ($bookmarkQuery->previousCursor()) {
  3462. if ($links != null) {
  3463. $links .= ', ';
  3464. }
  3465. $links .= '<'.$bookmarkQuery->previousPageUrl().'&limit='.$limit.'>; rel="prev"';
  3466. }
  3467. if ($links) {
  3468. $headers = ['Link' => $links];
  3469. }
  3470. return $this->json($bookmarks, 200, $headers);
  3471. }
  3472. /**
  3473. * POST /api/v1/statuses/{id}/bookmark
  3474. *
  3475. *
  3476. *
  3477. * @return StatusTransformer
  3478. */
  3479. public function bookmarkStatus(Request $request, $id)
  3480. {
  3481. abort_if(! $request->user() || ! $request->user()->token(), 403);
  3482. abort_unless($request->user()->tokenCan('write'), 403);
  3483. $status = Status::findOrFail($id);
  3484. $user = $request->user();
  3485. $pid = $request->user()->profile_id;
  3486. $account = AccountService::get($status->profile_id);
  3487. abort_if(isset($account['moved'], $account['moved']['id']), 422, 'Cannot bookmark a post from an account that has migrated');
  3488. abort_if($user->has_roles && ! UserRoleService::can('can-bookmark', $user->id), 403, 'Invalid permissions for this action');
  3489. abort_if($status->in_reply_to_id || $status->reblog_of_id, 404);
  3490. abort_if(! in_array($status->scope, ['public', 'unlisted', 'private']), 404);
  3491. abort_if(! in_array($status->type, ['photo', 'photo:album', 'video', 'video:album', 'photo:video:album']), 404);
  3492. if ($status->scope == 'private') {
  3493. abort_if(
  3494. $pid !== $status->profile_id && ! FollowerService::follows($pid, $status->profile_id),
  3495. 404,
  3496. 'Error: You cannot bookmark private posts from accounts you do not follow.'
  3497. );
  3498. }
  3499. Bookmark::firstOrCreate([
  3500. 'status_id' => $status->id,
  3501. 'profile_id' => $pid,
  3502. ]);
  3503. BookmarkService::add($pid, $status->id);
  3504. $res = StatusService::getMastodon($status->id, false);
  3505. $res['bookmarked'] = true;
  3506. return $this->json($res);
  3507. }
  3508. /**
  3509. * POST /api/v1/statuses/{id}/unbookmark
  3510. *
  3511. *
  3512. *
  3513. * @return StatusTransformer
  3514. */
  3515. public function unbookmarkStatus(Request $request, $id)
  3516. {
  3517. abort_if(! $request->user() || ! $request->user()->token(), 403);
  3518. abort_unless($request->user()->tokenCan('write'), 403);
  3519. $status = Status::findOrFail($id);
  3520. $pid = $request->user()->profile_id;
  3521. $user = $request->user();
  3522. abort_if($user->has_roles && ! UserRoleService::can('can-bookmark', $user->id), 403, 'Invalid permissions for this action');
  3523. abort_if($status->in_reply_to_id || $status->reblog_of_id, 404);
  3524. abort_if(! in_array($status->scope, ['public', 'unlisted', 'private']), 404);
  3525. abort_if(! in_array($status->type, ['photo', 'photo:album', 'video', 'video:album', 'photo:video:album']), 404);
  3526. $bookmark = Bookmark::whereStatusId($status->id)
  3527. ->whereProfileId($pid)
  3528. ->first();
  3529. if ($bookmark) {
  3530. BookmarkService::del($pid, $status->id);
  3531. $bookmark->delete();
  3532. }
  3533. $res = StatusService::getMastodon($status->id, false);
  3534. $res['bookmarked'] = false;
  3535. return $this->json($res);
  3536. }
  3537. /**
  3538. * GET /api/v1/discover/posts
  3539. *
  3540. *
  3541. * @return array
  3542. */
  3543. public function discoverPosts(Request $request)
  3544. {
  3545. abort_if(! $request->user() || ! $request->user()->token(), 403);
  3546. abort_unless($request->user()->tokenCan('read'), 403);
  3547. $this->validate($request, [
  3548. 'limit' => 'integer|min:1|max:40',
  3549. ]);
  3550. $limit = $request->input('limit', 40);
  3551. $pid = $request->user()->profile_id;
  3552. $filters = UserFilterService::filters($pid);
  3553. $forYou = DiscoverService::getForYou();
  3554. $posts = $forYou->take(50)->map(function ($post) {
  3555. return StatusService::getMastodon($post);
  3556. })
  3557. ->filter(function ($post) use ($filters) {
  3558. return $post &&
  3559. isset($post['account']) &&
  3560. isset($post['account']['id']) &&
  3561. ! in_array($post['account']['id'], $filters);
  3562. })
  3563. ->take(12)
  3564. ->values();
  3565. return $this->json(compact('posts'));
  3566. }
  3567. /**
  3568. * GET /api/v2/statuses/{id}/replies
  3569. *
  3570. *
  3571. * @return array
  3572. */
  3573. public function statusReplies(Request $request, $id)
  3574. {
  3575. abort_if(! $request->user(), 403);
  3576. $this->validate($request, [
  3577. 'limit' => 'sometimes|integer|min:1',
  3578. 'sort' => 'in:all,newest,popular',
  3579. ]);
  3580. $limit = $request->input('limit', 3);
  3581. if ($limit > 10) {
  3582. $limit = 10;
  3583. }
  3584. $pid = $request->user()->profile_id;
  3585. $status = StatusService::getMastodon($id, false);
  3586. abort_if(! $status, 404);
  3587. abort_if(isset($status['account'], $account['account']['moved']['id']), 404, 'Account moved');
  3588. if ($status['visibility'] == 'private') {
  3589. if ($pid != $status['account']['id']) {
  3590. abort_unless(FollowerService::follows($pid, $status['account']['id']), 404);
  3591. }
  3592. }
  3593. $sortBy = $request->input('sort', 'all');
  3594. if ($sortBy == 'all' && isset($status['replies_count']) && $status['replies_count'] && $request->has('refresh_cache')) {
  3595. if (! Cache::has('status:replies:all-rc:'.$id)) {
  3596. Cache::forget('status:replies:all:'.$id);
  3597. Cache::put('status:replies:all-rc:'.$id, true, 300);
  3598. }
  3599. }
  3600. if ($sortBy == 'all' && ! $request->has('cursor')) {
  3601. $ids = Cache::remember('status:replies:all:'.$id, 3600, function () use ($id) {
  3602. return DB::table('statuses')
  3603. ->where('in_reply_to_id', $id)
  3604. ->orderBy('id')
  3605. ->cursorPaginate(3);
  3606. });
  3607. } else {
  3608. $ids = DB::table('statuses')
  3609. ->where('in_reply_to_id', $id)
  3610. ->when($sortBy, function ($q, $sortBy) {
  3611. if ($sortBy === 'all') {
  3612. return $q->orderBy('id');
  3613. }
  3614. if ($sortBy === 'newest') {
  3615. return $q->orderByDesc('created_at');
  3616. }
  3617. if ($sortBy === 'popular') {
  3618. return $q->orderByDesc('likes_count');
  3619. }
  3620. })
  3621. ->cursorPaginate($limit);
  3622. }
  3623. $filters = UserFilterService::filters($pid);
  3624. $data = $ids->filter(function ($post) use ($filters) {
  3625. return ! in_array($post->profile_id, $filters);
  3626. })
  3627. ->map(function ($post) use ($pid) {
  3628. $status = StatusService::get($post->id, false);
  3629. if (! $status || ! isset($status['id'])) {
  3630. return false;
  3631. }
  3632. $status['favourited'] = LikeService::liked($pid, $post->id);
  3633. return $status;
  3634. })
  3635. ->map(function ($post) {
  3636. if (isset($post['account']) && isset($post['account']['id'])) {
  3637. $account = AccountService::get($post['account']['id'], true);
  3638. $post['account'] = $account;
  3639. }
  3640. return $post;
  3641. })
  3642. ->filter(function ($post) {
  3643. return $post && isset($post['id']) && isset($post['account']) && isset($post['account']['id']);
  3644. })
  3645. ->values();
  3646. $res = [
  3647. 'data' => $data,
  3648. 'next' => $ids->nextPageUrl(),
  3649. ];
  3650. return $this->json($res);
  3651. }
  3652. /**
  3653. * GET /api/v2/statuses/{id}/state
  3654. *
  3655. *
  3656. * @return array
  3657. */
  3658. public function statusState(Request $request, $id)
  3659. {
  3660. abort_if(! $request->user(), 403);
  3661. $status = StatusService::get($id, false, true);
  3662. abort_if(! $status, 404);
  3663. abort_if(! in_array($status['visibility'], ['public', 'unlisted', 'private']), 404);
  3664. return $this->json(StatusService::getState($status['id'], $request->user()->profile_id));
  3665. }
  3666. /**
  3667. * GET /api/v1.1/discover/accounts/popular
  3668. *
  3669. *
  3670. * @return array
  3671. */
  3672. public function discoverAccountsPopular(Request $request)
  3673. {
  3674. abort_if(! $request->user() || ! $request->user()->token(), 403);
  3675. abort_unless($request->user()->tokenCan('read'), 403);
  3676. $pid = $request->user()->profile_id;
  3677. $ids = Cache::remember('api:v1.1:discover:accounts:popular', 14400, function () {
  3678. return DB::table('profiles')
  3679. ->where('is_private', false)
  3680. ->whereNull('status')
  3681. ->orderByDesc('profiles.followers_count')
  3682. ->limit(30)
  3683. ->get();
  3684. });
  3685. $filters = UserFilterService::filters($pid);
  3686. $asf = AdminShadowFilterService::getHideFromPublicFeedsList();
  3687. $ids = $ids->map(function ($profile) {
  3688. return AccountService::get($profile->id, true);
  3689. })
  3690. ->filter(function ($profile) {
  3691. return $profile && isset($profile['id'], $profile['locked']) && ! $profile['locked'];
  3692. })
  3693. ->filter(function ($profile) use ($pid) {
  3694. return $profile['id'] != $pid;
  3695. })
  3696. ->filter(function ($profile) use ($pid) {
  3697. return ! FollowerService::follows($pid, $profile['id'], true);
  3698. })
  3699. ->filter(function ($profile) use ($asf) {
  3700. return ! in_array($profile['id'], $asf);
  3701. })
  3702. ->filter(function ($profile) use ($filters) {
  3703. return ! in_array($profile['id'], $filters);
  3704. })
  3705. ->take(16)
  3706. ->values();
  3707. return $this->json($ids);
  3708. }
  3709. /**
  3710. * GET /api/v1/preferences
  3711. *
  3712. *
  3713. * @return array
  3714. */
  3715. public function getPreferences(Request $request)
  3716. {
  3717. abort_if(! $request->user() || ! $request->user()->token(), 403);
  3718. abort_unless($request->user()->tokenCan('read'), 403);
  3719. $pid = $request->user()->profile_id;
  3720. $account = AccountService::get($pid);
  3721. return $this->json([
  3722. 'posting:default:visibility' => $account['locked'] ? 'private' : 'public',
  3723. 'posting:default:sensitive' => false,
  3724. 'posting:default:language' => null,
  3725. 'reading:expand:media' => 'default',
  3726. 'reading:expand:spoilers' => false,
  3727. ]);
  3728. }
  3729. /**
  3730. * GET /api/v1/trends
  3731. *
  3732. *
  3733. * @return array
  3734. */
  3735. public function getTrends(Request $request)
  3736. {
  3737. abort_if(! $request->user() || ! $request->user()->token(), 403);
  3738. abort_unless($request->user()->tokenCan('read'), 403);
  3739. return $this->json([]);
  3740. }
  3741. /**
  3742. * GET /api/v1/announcements
  3743. *
  3744. *
  3745. * @return array
  3746. */
  3747. public function getAnnouncements(Request $request)
  3748. {
  3749. abort_if(! $request->user() || ! $request->user()->token(), 403);
  3750. abort_unless($request->user()->tokenCan('read'), 403);
  3751. return $this->json([]);
  3752. }
  3753. /**
  3754. * GET /api/v1/markers
  3755. *
  3756. *
  3757. * @return array
  3758. */
  3759. public function getMarkers(Request $request)
  3760. {
  3761. abort_if(! $request->user() || ! $request->user()->token(), 403);
  3762. abort_unless($request->user()->tokenCan('read'), 403);
  3763. $type = $request->input('timeline');
  3764. if (is_array($type)) {
  3765. $type = $type[0];
  3766. }
  3767. if (! $type || ! in_array($type, ['home', 'notifications'])) {
  3768. return $this->json([]);
  3769. }
  3770. $pid = $request->user()->profile_id;
  3771. return $this->json(MarkerService::get($pid, $type));
  3772. }
  3773. /**
  3774. * POST /api/v1/markers
  3775. *
  3776. *
  3777. * @return array
  3778. */
  3779. public function setMarkers(Request $request)
  3780. {
  3781. abort_if(! $request->user() || ! $request->user()->token(), 403);
  3782. abort_unless($request->user()->tokenCan('write'), 403);
  3783. $pid = $request->user()->profile_id;
  3784. $home = $request->input('home[last_read_id]');
  3785. $notifications = $request->input('notifications[last_read_id]');
  3786. if ($home) {
  3787. return $this->json(MarkerService::set($pid, 'home', $home));
  3788. }
  3789. if ($notifications) {
  3790. return $this->json(MarkerService::set($pid, 'notifications', $notifications));
  3791. }
  3792. return $this->json([]);
  3793. }
  3794. /**
  3795. * GET /api/v1/instance/peers
  3796. *
  3797. *
  3798. * @return array
  3799. */
  3800. public function instancePeers(Request $request)
  3801. {
  3802. if ((bool) config('instance.show_peers') == false) {
  3803. return $this->json([]);
  3804. }
  3805. return $this->json(
  3806. Cache::remember(InstanceService::CACHE_KEY_API_PEERS_LIST, now()->addHours(24), function () {
  3807. return Instance::whereNotNull('nodeinfo_last_fetched')
  3808. ->whereBanned(false)
  3809. ->where('nodeinfo_last_fetched', '>', now()->subDays(8))
  3810. ->pluck('domain');
  3811. })
  3812. );
  3813. }
  3814. /**
  3815. * GET /api/v1/statuses/{id}/pin
  3816. */
  3817. public function statusPin(Request $request, $id)
  3818. {
  3819. abort_if(! $request->user(), 403);
  3820. abort_unless($request->user()->tokenCan('write'), 403);
  3821. $user = $request->user();
  3822. $status = Status::whereScope('public')->find($id);
  3823. if (! $status) {
  3824. return $this->json(['error' => 'Record not found'], 404);
  3825. }
  3826. if ($status->profile_id != $user->profile_id) {
  3827. return $this->json(['error' => "Validation failed: Someone else's post cannot be pinned"], 422);
  3828. }
  3829. $res = StatusService::markPin($status->id);
  3830. if (! $res['success']) {
  3831. return $this->json([
  3832. 'error' => $res['error'],
  3833. ], 422);
  3834. }
  3835. $statusRes = StatusService::get($status->id, true, true);
  3836. $status['pinned'] = true;
  3837. return $this->json($statusRes);
  3838. }
  3839. /**
  3840. * GET /api/v1/statuses/{id}/unpin
  3841. */
  3842. public function statusUnpin(Request $request, $id)
  3843. {
  3844. abort_if(! $request->user(), 403);
  3845. abort_unless($request->user()->tokenCan('write'), 403);
  3846. $status = Status::whereScope('public')->findOrFail($id);
  3847. $user = $request->user();
  3848. if ($status->profile_id != $user->profile_id) {
  3849. return $this->json(['error' => 'Record not found'], 404);
  3850. }
  3851. $res = StatusService::unmarkPin($status->id);
  3852. if (! $res) {
  3853. return $this->json($res, 422);
  3854. }
  3855. $status = StatusService::get($status->id, true, true);
  3856. $status['pinned'] = false;
  3857. return $this->json($status);
  3858. }
  3859. }