ApiV1Controller.php 157 KB

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