ApiV1Controller.php 156 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497
  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' => 16777216,
  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' => 2304000,
  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. ->filter(function ($n) use ($types) {
  2067. if (! $types) {
  2068. return true;
  2069. }
  2070. return in_array($n['type'], $types);
  2071. })
  2072. ->take($ogLimit)
  2073. ->values();
  2074. if ($maxId) {
  2075. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next"';
  2076. }
  2077. if ($minId) {
  2078. $link = '<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  2079. }
  2080. if ($maxId && $minId) {
  2081. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next",<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  2082. }
  2083. $headers = isset($link) ? ['Link' => $link] : [];
  2084. return $this->json($res, 200, $headers);
  2085. }
  2086. /**
  2087. * GET /api/v1/timelines/home
  2088. *
  2089. *
  2090. * @return StatusTransformer
  2091. */
  2092. public function timelineHome(Request $request)
  2093. {
  2094. abort_if(! $request->user() || ! $request->user()->token(), 403);
  2095. abort_unless($request->user()->tokenCan('read'), 403);
  2096. $this->validate($request, [
  2097. 'page' => 'sometimes|integer|max:40',
  2098. 'min_id' => 'sometimes|integer|min:0|max:'.PHP_INT_MAX,
  2099. 'max_id' => 'sometimes|integer|min:0|max:'.PHP_INT_MAX,
  2100. 'limit' => 'sometimes|integer|min:1',
  2101. 'include_reblogs' => 'sometimes',
  2102. ]);
  2103. $napi = $request->has(self::PF_API_ENTITY_KEY);
  2104. $page = $request->input('page');
  2105. $min = $request->input('min_id');
  2106. $max = $request->input('max_id');
  2107. $limit = $request->input('limit') ?? 20;
  2108. if ($limit > 40) {
  2109. $limit = 40;
  2110. }
  2111. $pid = $request->user()->profile_id;
  2112. $includeReblogs = $request->filled('include_reblogs') ? $request->boolean('include_reblogs') : false;
  2113. $nullFields = $includeReblogs ?
  2114. ['in_reply_to_id'] :
  2115. ['in_reply_to_id', 'reblog_of_id'];
  2116. $inTypes = $includeReblogs ?
  2117. ['photo', 'photo:album', 'video', 'video:album', 'photo:video:album', 'share'] :
  2118. ['photo', 'photo:album', 'video', 'video:album', 'photo:video:album'];
  2119. AccountService::setLastActive($request->user()->id);
  2120. if (config('exp.cached_home_timeline')) {
  2121. $paddedLimit = $includeReblogs ? $limit + 10 : $limit + 50;
  2122. if ($min || $max) {
  2123. if ($request->has('min_id')) {
  2124. $res = HomeTimelineService::getRankedMinId($pid, $min ?? 0, $paddedLimit);
  2125. } else {
  2126. $res = HomeTimelineService::getRankedMaxId($pid, $max ?? 0, $paddedLimit);
  2127. }
  2128. } else {
  2129. $res = HomeTimelineService::get($pid, 0, $paddedLimit);
  2130. }
  2131. if (! $res) {
  2132. $res = Cache::has('pf:services:apiv1:home:cached:coldbootcheck:'.$pid);
  2133. if (! $res) {
  2134. Cache::set('pf:services:apiv1:home:cached:coldbootcheck:'.$pid, 1, 86400);
  2135. FeedWarmCachePipeline::dispatchSync($pid);
  2136. return response()->json([], 206);
  2137. } else {
  2138. Cache::set('pf:services:apiv1:home:cached:coldbootcheck:'.$pid, 1, 86400);
  2139. return response()->json([], 206);
  2140. }
  2141. }
  2142. $res = collect($res)
  2143. ->map(function ($id) use ($napi) {
  2144. return $napi ? StatusService::get($id, false) : StatusService::getMastodon($id, false);
  2145. })
  2146. ->filter(function ($res) {
  2147. return $res && isset($res['account']);
  2148. })
  2149. ->filter(function ($s) use ($includeReblogs) {
  2150. return $includeReblogs ? true : $s['reblog'] == null;
  2151. })
  2152. ->take($limit)
  2153. ->map(function ($status) use ($pid) {
  2154. if ($pid) {
  2155. $status['favourited'] = (bool) LikeService::liked($pid, $status['id']);
  2156. $status['reblogged'] = (bool) ReblogService::get($pid, $status['id']);
  2157. $status['bookmarked'] = (bool) BookmarkService::get($pid, $status['id']);
  2158. }
  2159. return $status;
  2160. })
  2161. ->values();
  2162. $baseUrl = config('app.url').'/api/v1/timelines/home?limit='.$limit.'&';
  2163. $minId = $res->map(function ($s) {
  2164. return ['id' => $s['id']];
  2165. })->min('id');
  2166. $maxId = $res->map(function ($s) {
  2167. return ['id' => $s['id']];
  2168. })->max('id');
  2169. if ($minId == $maxId) {
  2170. $minId = null;
  2171. }
  2172. if ($maxId && $res->count() >= $limit) {
  2173. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next"';
  2174. }
  2175. if ($minId) {
  2176. $link = '<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  2177. }
  2178. if ($maxId && $minId) {
  2179. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next",<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  2180. }
  2181. $headers = isset($link) ? ['Link' => $link] : [];
  2182. return $this->json($res->toArray(), 200, $headers);
  2183. }
  2184. $following = Cache::remember('profile:following:'.$pid, 1209600, function () use ($pid) {
  2185. $following = Follower::whereProfileId($pid)->pluck('following_id');
  2186. return $following->push($pid)->toArray();
  2187. });
  2188. $muted = UserFilterService::mutes($pid);
  2189. if ($muted && count($muted)) {
  2190. $following = array_diff($following, $muted);
  2191. }
  2192. if ($min || $max) {
  2193. $dir = $min ? '>' : '<';
  2194. $id = $min ?? $max;
  2195. $res = Status::select(
  2196. 'id',
  2197. 'profile_id',
  2198. 'type',
  2199. 'visibility',
  2200. 'in_reply_to_id',
  2201. 'reblog_of_id'
  2202. )
  2203. ->where('id', $dir, $id)
  2204. ->whereNull($nullFields)
  2205. ->whereIntegerInRaw('profile_id', $following)
  2206. ->whereIn('type', $inTypes)
  2207. ->whereIn('visibility', ['public', 'unlisted', 'private'])
  2208. ->orderByDesc('id')
  2209. ->take(($limit * 2))
  2210. ->get()
  2211. ->map(function ($s) use ($pid, $napi) {
  2212. try {
  2213. $account = $napi ? AccountService::get($s['profile_id'], true) : AccountService::getMastodon($s['profile_id'], true);
  2214. if (! $account) {
  2215. return false;
  2216. }
  2217. $status = $napi ? StatusService::get($s['id'], false) : StatusService::getMastodon($s['id'], false);
  2218. if (! $status || ! isset($status['account']) || ! isset($status['account']['id'])) {
  2219. return false;
  2220. }
  2221. } catch (\Exception $e) {
  2222. return false;
  2223. }
  2224. $status['account'] = $account;
  2225. if ($pid) {
  2226. $status['favourited'] = (bool) LikeService::liked($pid, $s['id']);
  2227. $status['reblogged'] = (bool) ReblogService::get($pid, $status['id']);
  2228. $status['bookmarked'] = (bool) BookmarkService::get($pid, $status['id']);
  2229. }
  2230. return $status;
  2231. })
  2232. ->filter(function ($status) {
  2233. return $status && isset($status['account']);
  2234. })
  2235. ->map(function ($status) use ($pid) {
  2236. if (! empty($status['reblog'])) {
  2237. $status['reblog']['favourited'] = (bool) LikeService::liked($pid, $status['reblog']['id']);
  2238. $status['reblog']['reblogged'] = (bool) ReblogService::get($pid, $status['reblog']['id']);
  2239. $status['bookmarked'] = (bool) BookmarkService::get($pid, $status['id']);
  2240. }
  2241. return $status;
  2242. })
  2243. ->take($limit)
  2244. ->values();
  2245. } else {
  2246. $res = Status::select(
  2247. 'id',
  2248. 'profile_id',
  2249. 'type',
  2250. 'visibility',
  2251. 'in_reply_to_id',
  2252. 'reblog_of_id',
  2253. )
  2254. ->whereNull($nullFields)
  2255. ->whereIntegerInRaw('profile_id', $following)
  2256. ->whereIn('type', $inTypes)
  2257. ->whereIn('visibility', ['public', 'unlisted', 'private'])
  2258. ->orderByDesc('id')
  2259. ->take(($limit * 2))
  2260. ->get()
  2261. ->map(function ($s) use ($pid, $napi) {
  2262. try {
  2263. $account = $napi ? AccountService::get($s['profile_id'], true) : AccountService::getMastodon($s['profile_id'], true);
  2264. if (! $account) {
  2265. return false;
  2266. }
  2267. $status = $napi ? StatusService::get($s['id'], false) : StatusService::getMastodon($s['id'], false);
  2268. if (! $status || ! isset($status['account']) || ! isset($status['account']['id'])) {
  2269. return false;
  2270. }
  2271. } catch (\Exception $e) {
  2272. return false;
  2273. }
  2274. $status['account'] = $account;
  2275. if ($pid) {
  2276. $status['favourited'] = (bool) LikeService::liked($pid, $s['id']);
  2277. $status['reblogged'] = (bool) ReblogService::get($pid, $status['id']);
  2278. $status['bookmarked'] = (bool) BookmarkService::get($pid, $status['id']);
  2279. }
  2280. return $status;
  2281. })
  2282. ->filter(function ($status) {
  2283. return $status && isset($status['account']);
  2284. })
  2285. ->map(function ($status) use ($pid) {
  2286. if (! empty($status['reblog'])) {
  2287. $status['reblog']['favourited'] = (bool) LikeService::liked($pid, $status['reblog']['id']);
  2288. $status['reblog']['reblogged'] = (bool) ReblogService::get($pid, $status['reblog']['id']);
  2289. $status['bookmarked'] = (bool) BookmarkService::get($pid, $status['id']);
  2290. }
  2291. return $status;
  2292. })
  2293. ->take($limit)
  2294. ->values();
  2295. }
  2296. $baseUrl = config('app.url').'/api/v1/timelines/home?limit='.$limit.'&';
  2297. $minId = $res->map(function ($s) {
  2298. return ['id' => $s['id']];
  2299. })->min('id');
  2300. $maxId = $res->map(function ($s) {
  2301. return ['id' => $s['id']];
  2302. })->max('id');
  2303. if ($minId == $maxId) {
  2304. $minId = null;
  2305. }
  2306. if ($maxId) {
  2307. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next"';
  2308. }
  2309. if ($minId) {
  2310. $link = '<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  2311. }
  2312. if ($maxId && $minId) {
  2313. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next",<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  2314. }
  2315. $headers = isset($link) ? ['Link' => $link] : [];
  2316. return $this->json($res->toArray(), 200, $headers);
  2317. }
  2318. /**
  2319. * GET /api/v1/timelines/public
  2320. *
  2321. *
  2322. * @return StatusTransformer
  2323. */
  2324. public function timelinePublic(Request $request)
  2325. {
  2326. $this->validate($request, [
  2327. 'min_id' => 'nullable|integer|min:0|max:'.PHP_INT_MAX,
  2328. 'max_id' => 'nullable|integer|min:0|max:'.PHP_INT_MAX,
  2329. 'limit' => 'sometimes|integer|min:1',
  2330. 'remote' => 'sometimes',
  2331. 'local' => 'sometimes',
  2332. ]);
  2333. $napi = $request->has(self::PF_API_ENTITY_KEY);
  2334. $min = $request->input('min_id');
  2335. $max = $request->input('max_id');
  2336. if ($max == 0) {
  2337. $min = 1;
  2338. }
  2339. $minOrMax = $request->anyFilled(['max_id', 'min_id']);
  2340. $limit = $request->input('limit') ?? 20;
  2341. if ($limit > 40) {
  2342. $limit = 40;
  2343. }
  2344. $user = $request->user();
  2345. $remote = $request->has('remote') && $request->boolean('remote');
  2346. $local = $request->boolean('local');
  2347. $userRoleKey = $remote ? 'can-view-network-feed' : 'can-view-public-feed';
  2348. if ($user->has_roles && ! UserRoleService::can($userRoleKey, $user->id)) {
  2349. return [];
  2350. }
  2351. $filtered = $user ? UserFilterService::filters($user->profile_id) : [];
  2352. AccountService::setLastActive($user->id);
  2353. $domainBlocks = UserFilterService::domainBlocks($user->profile_id);
  2354. $hideNsfw = config('instance.hide_nsfw_on_public_feeds');
  2355. $amin = SnowflakeService::byDate(now()->subDays(config('federation.network_timeline_days_falloff')));
  2356. $asf = AdminShadowFilterService::getHideFromPublicFeedsList();
  2357. if ($local && $remote) {
  2358. $feed = Status::select(
  2359. 'id',
  2360. 'uri',
  2361. 'type',
  2362. 'scope',
  2363. 'created_at',
  2364. 'profile_id',
  2365. 'in_reply_to_id',
  2366. 'reblog_of_id'
  2367. )
  2368. ->when($minOrMax, function ($q, $minOrMax) use ($min, $max) {
  2369. $dir = $min ? '>' : '<';
  2370. $id = $min ?? $max;
  2371. return $q->where('id', $dir, $id);
  2372. })
  2373. ->whereNull(['in_reply_to_id', 'reblog_of_id'])
  2374. ->when($hideNsfw, function ($q, $hideNsfw) {
  2375. return $q->where('is_nsfw', false);
  2376. })
  2377. ->whereIn('type', ['photo', 'photo:album', 'video', 'video:album', 'photo:video:album'])
  2378. ->whereScope('public')
  2379. ->where('id', '>', $amin)
  2380. ->orderByDesc('id')
  2381. ->limit(($limit * 2))
  2382. ->pluck('id')
  2383. ->values()
  2384. ->toArray();
  2385. } elseif ($remote && ! $local) {
  2386. if (config('instance.timeline.network.cached')) {
  2387. Cache::remember('api:v1:timelines:network:cache_check', 10368000, function () {
  2388. if (NetworkTimelineService::count() == 0) {
  2389. NetworkTimelineService::warmCache(true, config('instance.timeline.network.cache_dropoff'));
  2390. }
  2391. });
  2392. if ($max) {
  2393. $feed = NetworkTimelineService::getRankedMaxId($max, $limit + 5);
  2394. } elseif ($min) {
  2395. $feed = NetworkTimelineService::getRankedMinId($min, $limit + 5);
  2396. } else {
  2397. $feed = NetworkTimelineService::get(0, $limit + 5);
  2398. }
  2399. } else {
  2400. $feed = Status::select(
  2401. 'id',
  2402. 'uri',
  2403. 'type',
  2404. 'scope',
  2405. 'local',
  2406. 'created_at',
  2407. 'profile_id',
  2408. 'in_reply_to_id',
  2409. 'reblog_of_id'
  2410. )
  2411. ->when($minOrMax, function ($q, $minOrMax) use ($min, $max) {
  2412. $dir = $min ? '>' : '<';
  2413. $id = $min ?? $max;
  2414. return $q->where('id', $dir, $id);
  2415. })
  2416. ->whereNull(['in_reply_to_id', 'reblog_of_id'])
  2417. ->when($hideNsfw, function ($q, $hideNsfw) {
  2418. return $q->where('is_nsfw', false);
  2419. })
  2420. ->whereIn('type', ['photo', 'photo:album', 'video', 'video:album', 'photo:video:album'])
  2421. ->whereLocal(false)
  2422. ->whereScope('public')
  2423. ->where('id', '>', $amin)
  2424. ->orderByDesc('id')
  2425. ->limit(($limit * 2))
  2426. ->pluck('id')
  2427. ->values()
  2428. ->toArray();
  2429. }
  2430. } else {
  2431. if (config('instance.timeline.local.cached')) {
  2432. Cache::remember('api:v1:timelines:public:cache_check', 10368000, function () {
  2433. if (PublicTimelineService::count() == 0) {
  2434. PublicTimelineService::warmCache(true, 400);
  2435. }
  2436. });
  2437. if ($max) {
  2438. $feed = PublicTimelineService::getRankedMaxId($max, $limit + 5);
  2439. } elseif ($min) {
  2440. $feed = PublicTimelineService::getRankedMinId($min, $limit + 5);
  2441. } else {
  2442. $feed = PublicTimelineService::get(0, $limit + 5);
  2443. }
  2444. } else {
  2445. $feed = Status::select(
  2446. 'id',
  2447. 'uri',
  2448. 'type',
  2449. 'scope',
  2450. 'local',
  2451. 'created_at',
  2452. 'profile_id',
  2453. 'in_reply_to_id',
  2454. 'reblog_of_id'
  2455. )
  2456. ->when($minOrMax, function ($q, $minOrMax) use ($min, $max) {
  2457. $dir = $min ? '>' : '<';
  2458. $id = $min ?? $max;
  2459. return $q->where('id', $dir, $id);
  2460. })
  2461. ->whereNull(['in_reply_to_id', 'reblog_of_id'])
  2462. ->when($hideNsfw, function ($q, $hideNsfw) {
  2463. return $q->where('is_nsfw', false);
  2464. })
  2465. ->whereIn('type', ['photo', 'photo:album', 'video', 'video:album', 'photo:video:album'])
  2466. ->whereLocal(true)
  2467. ->whereScope('public')
  2468. ->where('id', '>', $amin)
  2469. ->orderByDesc('id')
  2470. ->limit(($limit * 2))
  2471. ->pluck('id')
  2472. ->values()
  2473. ->toArray();
  2474. }
  2475. }
  2476. $res = collect($feed)
  2477. ->filter(function ($k) use ($min, $max) {
  2478. if (! $min && ! $max) {
  2479. return true;
  2480. }
  2481. if ($min) {
  2482. return $min != $k;
  2483. }
  2484. if ($max) {
  2485. return $max != $k;
  2486. }
  2487. })
  2488. ->map(function ($k) use ($user, $napi) {
  2489. try {
  2490. $status = $napi ? StatusService::get($k) : StatusService::getMastodon($k);
  2491. if (! $status || ! isset($status['account']) || ! isset($status['account']['id'])) {
  2492. return false;
  2493. }
  2494. } catch (\Exception $e) {
  2495. return false;
  2496. }
  2497. $account = $napi ? AccountService::get($status['account']['id'], true) : AccountService::getMastodon($status['account']['id'], true);
  2498. if (! $account) {
  2499. return false;
  2500. }
  2501. $status['account'] = $account;
  2502. if ($user) {
  2503. $status['favourited'] = (bool) LikeService::liked($user->profile_id, $k);
  2504. $status['reblogged'] = (bool) ReblogService::get($user->profile_id, $status['id']);
  2505. $status['bookmarked'] = (bool) BookmarkService::get($user->profile_id, $status['id']);
  2506. }
  2507. return $status;
  2508. })
  2509. ->filter(function ($s) use ($filtered) {
  2510. return $s && isset($s['account']) && in_array($s['account']['id'], $filtered) == false;
  2511. })
  2512. ->filter(function ($s) use ($domainBlocks) {
  2513. if (! $domainBlocks || ! count($domainBlocks)) {
  2514. return $s;
  2515. }
  2516. $domain = strtolower(parse_url($s['url'], PHP_URL_HOST));
  2517. return ! in_array($domain, $domainBlocks);
  2518. })
  2519. ->filter(function ($s) use ($asf, $user) {
  2520. if (! $asf || count($asf) === 0) {
  2521. return true;
  2522. }
  2523. if (in_array($s['account']['id'], $asf)) {
  2524. if ($user->profile_id == $s['account']['id']) {
  2525. return true;
  2526. }
  2527. return false;
  2528. }
  2529. return true;
  2530. })
  2531. ->take($limit)
  2532. ->values();
  2533. $baseUrl = config('app.url').'/api/v1/timelines/public?limit='.$limit.'&';
  2534. if ($remote) {
  2535. $baseUrl .= 'remote=1&';
  2536. }
  2537. if ($local) {
  2538. $baseUrl .= 'local=1&';
  2539. }
  2540. $minId = $res->map(function ($s) {
  2541. return ['id' => $s['id']];
  2542. })->min('id');
  2543. $maxId = $res->map(function ($s) {
  2544. return ['id' => $s['id']];
  2545. })->max('id');
  2546. if ($minId == $maxId) {
  2547. $minId = null;
  2548. }
  2549. if ($maxId && $res->count() >= $limit) {
  2550. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next"';
  2551. }
  2552. if ($minId) {
  2553. $link = '<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  2554. }
  2555. if ($maxId && $minId) {
  2556. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next",<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  2557. }
  2558. $headers = isset($link) ? ['Link' => $link] : [];
  2559. return $this->json($res->toArray(), 200, $headers);
  2560. }
  2561. /**
  2562. * GET /api/v1/conversations
  2563. *
  2564. * Not implemented
  2565. *
  2566. * @return array
  2567. */
  2568. public function conversations(Request $request)
  2569. {
  2570. abort_if(! $request->user() || ! $request->user()->token(), 403);
  2571. abort_unless($request->user()->tokenCan('read'), 403);
  2572. $this->validate($request, [
  2573. 'limit' => 'sometimes|integer|min:1|max:40',
  2574. 'scope' => 'nullable|in:inbox,sent,requests',
  2575. 'min_id' => 'nullable|integer',
  2576. 'max_id' => 'nullable|integer',
  2577. 'since_id' => 'nullable|integer',
  2578. ]);
  2579. $limit = $request->input('limit', 20);
  2580. if ($limit > 20) {
  2581. $limit = 20;
  2582. }
  2583. $scope = $request->input('scope', 'inbox');
  2584. $user = $request->user();
  2585. $min_id = $request->input('min_id');
  2586. $max_id = $request->input('max_id');
  2587. $since_id = $request->input('since_id');
  2588. if ($user->has_roles && ! UserRoleService::can('can-direct-message', $user->id)) {
  2589. return [];
  2590. }
  2591. $pid = $user->profile_id;
  2592. $isPgsql = config('database.default') == 'pgsql';
  2593. if ($isPgsql) {
  2594. $dms = DirectMessage::when($scope === 'inbox', function ($q) use ($pid) {
  2595. return $q->whereIsHidden(false)
  2596. ->where(function ($query) use ($pid) {
  2597. $query->where('to_id', $pid)
  2598. ->orWhere('from_id', $pid);
  2599. });
  2600. })
  2601. ->when($scope === 'sent', function ($q) use ($pid) {
  2602. return $q->whereFromId($pid)
  2603. ->groupBy(['to_id', 'id']);
  2604. })
  2605. ->when($scope === 'requests', function ($q) use ($pid) {
  2606. return $q->whereToId($pid)
  2607. ->whereIsHidden(true);
  2608. });
  2609. } else {
  2610. $dms = Conversation::when($scope === 'inbox', function ($q) use ($pid) {
  2611. return $q->whereIsHidden(false)
  2612. ->where(function ($query) use ($pid) {
  2613. $query->where('to_id', $pid)
  2614. ->orWhere('from_id', $pid);
  2615. })
  2616. ->orderByDesc('status_id')
  2617. ->groupBy(['to_id', 'from_id']);
  2618. })
  2619. ->when($scope === 'sent', function ($q) use ($pid) {
  2620. return $q->whereFromId($pid)
  2621. ->groupBy('to_id');
  2622. })
  2623. ->when($scope === 'requests', function ($q) use ($pid) {
  2624. return $q->whereToId($pid)
  2625. ->whereIsHidden(true);
  2626. });
  2627. }
  2628. if ($min_id) {
  2629. $dms = $dms->where('id', '>', $min_id);
  2630. }
  2631. if ($max_id) {
  2632. $dms = $dms->where('id', '<', $max_id);
  2633. }
  2634. if ($since_id) {
  2635. $dms = $dms->where('id', '>', $since_id);
  2636. }
  2637. $dms = $dms->orderByDesc('status_id')->orderBy('id');
  2638. $dmResults = $dms->limit($limit + 1)->get();
  2639. $hasNextPage = $dmResults->count() > $limit;
  2640. if ($hasNextPage) {
  2641. $dmResults = $dmResults->take($limit);
  2642. }
  2643. $transformedDms = $dmResults->map(function ($dm) use ($pid) {
  2644. $from = $pid == $dm->to_id ? $dm->from_id : $dm->to_id;
  2645. return [
  2646. 'id' => $dm->id,
  2647. 'unread' => false,
  2648. 'accounts' => [
  2649. AccountService::getMastodon($from, true),
  2650. ],
  2651. 'last_status' => StatusService::getDirectMessage($dm->status_id),
  2652. ];
  2653. })
  2654. ->filter(function ($dm) {
  2655. return $dm
  2656. && ! empty($dm['last_status'])
  2657. && isset($dm['accounts'])
  2658. && count($dm['accounts'])
  2659. && isset($dm['accounts'][0])
  2660. && isset($dm['accounts'][0]['id']);
  2661. })
  2662. ->unique(function ($item) {
  2663. return $item['accounts'][0]['id'];
  2664. })
  2665. ->values();
  2666. $links = [];
  2667. if (! $transformedDms->isEmpty()) {
  2668. $baseUrl = url()->current().'?'.http_build_query(array_merge(
  2669. $request->except(['min_id', 'max_id', 'since_id']),
  2670. ['limit' => $limit]
  2671. ));
  2672. $firstId = $transformedDms->first()['id'];
  2673. $lastId = $transformedDms->last()['id'];
  2674. $firstLink = $baseUrl;
  2675. $links[] = '<'.$firstLink.'>; rel="first"';
  2676. if ($hasNextPage) {
  2677. $nextLink = $baseUrl.'&max_id='.$lastId;
  2678. $links[] = '<'.$nextLink.'>; rel="next"';
  2679. }
  2680. if ($max_id || $since_id) {
  2681. $prevLink = $baseUrl.'&min_id='.$firstId;
  2682. $links[] = '<'.$prevLink.'>; rel="prev"';
  2683. }
  2684. }
  2685. if (! empty($links)) {
  2686. return response()->json($transformedDms->toArray())
  2687. ->header('Link', implode(', ', $links));
  2688. }
  2689. return $this->json($transformedDms);
  2690. }
  2691. /**
  2692. * GET /api/v1/statuses/{id}
  2693. *
  2694. * @param int $id
  2695. * @return StatusTransformer
  2696. */
  2697. public function statusById(Request $request, $id)
  2698. {
  2699. abort_if(! $request->user() || ! $request->user()->token(), 403);
  2700. abort_unless($request->user()->tokenCan('read'), 403);
  2701. AccountService::setLastActive($request->user()->id);
  2702. $pid = $request->user()->profile_id;
  2703. $res = $request->has(self::PF_API_ENTITY_KEY) ? StatusService::get($id, false) : StatusService::getMastodon($id, false);
  2704. if (! $res || ! isset($res['visibility'])) {
  2705. abort(404);
  2706. }
  2707. if ($res && isset($res['account'], $res['account']['acct'], $res['account']['url']) && strpos($res['account']['acct'], '@') != -1) {
  2708. $domain = parse_url($res['account']['url'], PHP_URL_HOST);
  2709. abort_if(in_array($domain, InstanceService::getBannedDomains()), 404);
  2710. }
  2711. $scope = $res['visibility'];
  2712. if (! in_array($scope, ['public', 'unlisted'])) {
  2713. if ($scope === 'private') {
  2714. if (intval($res['account']['id']) !== intval($pid)) {
  2715. abort_unless(FollowerService::follows($pid, $res['account']['id']), 403);
  2716. }
  2717. } else {
  2718. abort(400, 'Invalid request');
  2719. }
  2720. }
  2721. if (! empty($res['reblog']) && isset($res['reblog']['id'])) {
  2722. $res['reblog']['favourited'] = (bool) LikeService::liked($pid, $res['reblog']['id']);
  2723. $res['reblog']['reblogged'] = (bool) ReblogService::get($pid, $res['reblog']['id']);
  2724. $res['reblog']['bookmarked'] = BookmarkService::get($pid, $res['reblog']['id']);
  2725. }
  2726. $res['favourited'] = LikeService::liked($pid, $res['id']);
  2727. $res['reblogged'] = ReblogService::get($pid, $res['id']);
  2728. $res['bookmarked'] = BookmarkService::get($pid, $res['id']);
  2729. return $this->json($res);
  2730. }
  2731. /**
  2732. * GET /api/v1/statuses/{id}/context
  2733. *
  2734. * @param int $id
  2735. * @return StatusTransformer
  2736. */
  2737. public function statusContext(Request $request, $id)
  2738. {
  2739. abort_if(! $request->user() || ! $request->user()->token(), 403);
  2740. abort_unless($request->user()->tokenCan('read'), 403);
  2741. $user = $request->user();
  2742. $pid = $user->profile_id;
  2743. $status = StatusService::getMastodon($id, false);
  2744. $pe = $request->has(self::PF_API_ENTITY_KEY);
  2745. if (! $status || ! isset($status['account'])) {
  2746. return response('', 404);
  2747. }
  2748. if ($status && isset($status['account'], $status['account']['acct']) && strpos($status['account']['acct'], '@') != -1) {
  2749. $domain = parse_url($status['account']['url'], PHP_URL_HOST);
  2750. abort_if(in_array($domain, InstanceService::getBannedDomains()), 404);
  2751. }
  2752. if (intval($status['account']['id']) !== intval($user->profile_id)) {
  2753. if ($status['visibility'] == 'private') {
  2754. if (! FollowerService::follows($user->profile_id, $status['account']['id'])) {
  2755. return response('', 404);
  2756. }
  2757. } else {
  2758. if (! in_array($status['visibility'], ['public', 'unlisted'])) {
  2759. return response('', 404);
  2760. }
  2761. }
  2762. }
  2763. $ancestors = [];
  2764. $descendants = [];
  2765. if ($status['in_reply_to_id']) {
  2766. $ancestors[] = $pe ?
  2767. StatusService::get($status['in_reply_to_id'], false) :
  2768. StatusService::getMastodon($status['in_reply_to_id'], false);
  2769. }
  2770. if ($status['replies_count']) {
  2771. $filters = UserFilterService::filters($pid);
  2772. $descendants = DB::table('statuses')
  2773. ->where('in_reply_to_id', $id)
  2774. ->limit(20)
  2775. ->pluck('id')
  2776. ->map(function ($sid) use ($pe) {
  2777. return $pe ?
  2778. StatusService::get($sid, false) :
  2779. StatusService::getMastodon($sid, false);
  2780. })
  2781. ->filter(function ($post) use ($filters) {
  2782. return $post && isset($post['account'], $post['account']['id']) && ! in_array($post['account']['id'], $filters);
  2783. })
  2784. ->map(function ($status) use ($pid) {
  2785. $status['favourited'] = LikeService::liked($pid, $status['id']);
  2786. $status['reblogged'] = ReblogService::get($pid, $status['id']);
  2787. return $status;
  2788. })
  2789. ->values();
  2790. }
  2791. $res = [
  2792. 'ancestors' => $ancestors,
  2793. 'descendants' => $descendants,
  2794. ];
  2795. return $this->json($res);
  2796. }
  2797. /**
  2798. * GET /api/v1/statuses/{id}/card
  2799. *
  2800. * @param int $id
  2801. * @return StatusTransformer
  2802. */
  2803. public function statusCard(Request $request, $id)
  2804. {
  2805. abort_if(! $request->user() || ! $request->user()->token(), 403);
  2806. abort_unless($request->user()->tokenCan('read'), 403);
  2807. $res = [];
  2808. return response()->json($res);
  2809. }
  2810. /**
  2811. * GET /api/v1/statuses/{id}/reblogged_by
  2812. *
  2813. * @param int $id
  2814. * @return AccountTransformer
  2815. */
  2816. public function statusRebloggedBy(Request $request, $id)
  2817. {
  2818. abort_if(! $request->user() || ! $request->user()->token(), 403);
  2819. abort_unless($request->user()->tokenCan('read'), 403);
  2820. $this->validate($request, [
  2821. 'limit' => 'sometimes|integer|min:1|max:80',
  2822. ]);
  2823. $limit = $request->input('limit', 10);
  2824. $user = $request->user();
  2825. $pid = $user->profile_id;
  2826. $status = Status::findOrFail($id);
  2827. $account = AccountService::get($status->profile_id, true);
  2828. abort_if(! $account, 404);
  2829. abort_if(isset($account['moved'], $account['moved']['id']), 404, 'Account moved');
  2830. if ($account && strpos($account['acct'], '@') != -1) {
  2831. $domain = parse_url($account['url'], PHP_URL_HOST);
  2832. abort_if(in_array($domain, InstanceService::getBannedDomains()), 404);
  2833. }
  2834. $author = intval($status->profile_id) === intval($pid) || $user->is_admin;
  2835. $napi = $request->has(self::PF_API_ENTITY_KEY);
  2836. abort_if(
  2837. ! $status->type ||
  2838. ! in_array($status->type, ['photo', 'photo:album', 'photo:video:album', 'reply', 'text', 'video', 'video:album']),
  2839. 404,
  2840. );
  2841. if (! $author) {
  2842. if ($status->scope == 'private') {
  2843. abort_if(! FollowerService::follows($pid, $status->profile_id), 403);
  2844. } else {
  2845. abort_if(! in_array($status->scope, ['public', 'unlisted']), 403);
  2846. }
  2847. if ($request->has('cursor')) {
  2848. return $this->json([]);
  2849. }
  2850. }
  2851. $res = Status::where('reblog_of_id', $status->id)
  2852. ->orderByDesc('id')
  2853. ->cursorPaginate($limit)
  2854. ->withQueryString();
  2855. if (! $res) {
  2856. return $this->json([]);
  2857. }
  2858. $headers = [];
  2859. if ($author && $res->hasPages()) {
  2860. $links = '';
  2861. if ($res->onFirstPage()) {
  2862. if ($res->nextPageUrl()) {
  2863. $links = '<'.$res->nextPageUrl().'>; rel="prev"';
  2864. }
  2865. } else {
  2866. if ($res->previousPageUrl()) {
  2867. $links = '<'.$res->previousPageUrl().'>; rel="next"';
  2868. }
  2869. if ($res->nextPageUrl()) {
  2870. if (! empty($links)) {
  2871. $links .= ', ';
  2872. }
  2873. $links .= '<'.$res->nextPageUrl().'>; rel="prev"';
  2874. }
  2875. }
  2876. $headers = ['Link' => $links];
  2877. }
  2878. $res = $res->map(function ($status) use ($pid, $napi) {
  2879. $account = $napi ? AccountService::get($status->profile_id, true) : AccountService::getMastodon($status->profile_id, true);
  2880. if (! $account) {
  2881. return false;
  2882. }
  2883. if ($napi) {
  2884. $account['follows'] = $status->profile_id == $pid ? null : FollowerService::follows($pid, $status->profile_id);
  2885. }
  2886. return $account;
  2887. })
  2888. ->filter(function ($account) {
  2889. return $account && isset($account['id']);
  2890. })
  2891. ->values();
  2892. return $this->json($res, 200, $headers);
  2893. }
  2894. /**
  2895. * GET /api/v1/statuses/{id}/favourited_by
  2896. *
  2897. * @param int $id
  2898. * @return AccountTransformer
  2899. */
  2900. public function statusFavouritedBy(Request $request, $id)
  2901. {
  2902. abort_if(! $request->user() || ! $request->user()->token(), 403);
  2903. abort_unless($request->user()->tokenCan('read'), 403);
  2904. $this->validate($request, [
  2905. 'limit' => 'sometimes|integer|min:1',
  2906. ]);
  2907. $limit = $request->input('limit', 40);
  2908. if ($limit > 80) {
  2909. $limit = 80;
  2910. }
  2911. $user = $request->user();
  2912. $pid = $user->profile_id;
  2913. $status = Status::findOrFail($id);
  2914. $account = AccountService::get($status->profile_id, true);
  2915. abort_if(! $account, 404);
  2916. abort_if(isset($account['moved'], $account['moved']['id']), 404, 'Account moved');
  2917. if ($account && strpos($account['acct'], '@') != -1) {
  2918. $domain = parse_url($account['url'], PHP_URL_HOST);
  2919. abort_if(in_array($domain, InstanceService::getBannedDomains()), 404);
  2920. }
  2921. $author = intval($status->profile_id) === intval($pid) || $user->is_admin;
  2922. $napi = $request->has(self::PF_API_ENTITY_KEY);
  2923. abort_if(
  2924. ! $status->type ||
  2925. ! in_array($status->type, ['photo', 'photo:album', 'photo:video:album', 'reply', 'text', 'video', 'video:album']),
  2926. 404,
  2927. );
  2928. if (! $author) {
  2929. if ($status->scope == 'private') {
  2930. abort_if(! FollowerService::follows($pid, $status->profile_id), 403);
  2931. } else {
  2932. abort_if(! in_array($status->scope, ['public', 'unlisted']), 403);
  2933. }
  2934. if ($request->has('cursor')) {
  2935. return $this->json([]);
  2936. }
  2937. }
  2938. $res = Like::where('status_id', $status->id)
  2939. ->orderByDesc('id')
  2940. ->cursorPaginate($limit)
  2941. ->withQueryString();
  2942. if (! $res) {
  2943. return $this->json([]);
  2944. }
  2945. $headers = [];
  2946. if ($author && $res->hasPages()) {
  2947. $links = '';
  2948. if ($res->onFirstPage()) {
  2949. if ($res->nextPageUrl()) {
  2950. $links = '<'.$res->nextPageUrl().'>; rel="prev"';
  2951. }
  2952. } else {
  2953. if ($res->previousPageUrl()) {
  2954. $links = '<'.$res->previousPageUrl().'>; rel="next"';
  2955. }
  2956. if ($res->nextPageUrl()) {
  2957. if (! empty($links)) {
  2958. $links .= ', ';
  2959. }
  2960. $links .= '<'.$res->nextPageUrl().'>; rel="prev"';
  2961. }
  2962. }
  2963. $headers = ['Link' => $links];
  2964. }
  2965. $res = $res->map(function ($like) use ($pid, $napi) {
  2966. $account = $napi ? AccountService::get($like->profile_id, true) : AccountService::getMastodon($like->profile_id, true);
  2967. if (! $account) {
  2968. return false;
  2969. }
  2970. if ($napi) {
  2971. $account['follows'] = $like->profile_id == $pid ? null : FollowerService::follows($pid, $like->profile_id);
  2972. }
  2973. return $account;
  2974. })
  2975. ->filter(function ($account) {
  2976. return $account && isset($account['id']);
  2977. })
  2978. ->values();
  2979. return $this->json($res, 200, $headers);
  2980. }
  2981. /**
  2982. * POST /api/v1/statuses
  2983. *
  2984. *
  2985. * @return StatusTransformer
  2986. */
  2987. public function statusCreate(Request $request)
  2988. {
  2989. abort_if(! $request->user() || ! $request->user()->token(), 403);
  2990. abort_unless($request->user()->tokenCan('write'), 403);
  2991. $this->validate($request, [
  2992. 'status' => 'nullable|string|max:'.(int) config_cache('pixelfed.max_caption_length'),
  2993. 'in_reply_to_id' => 'nullable',
  2994. 'media_ids' => 'sometimes|array|max:'.(int) config_cache('pixelfed.max_album_length'),
  2995. 'sensitive' => 'nullable',
  2996. 'visibility' => 'string|in:private,unlisted,public',
  2997. 'spoiler_text' => 'sometimes|max:140',
  2998. 'place_id' => 'sometimes|integer|min:1|max:128769',
  2999. 'collection_ids' => 'sometimes|array|max:3',
  3000. 'comments_disabled' => 'sometimes|boolean',
  3001. ]);
  3002. if ($request->hasHeader('idempotency-key')) {
  3003. $key = 'pf:api:v1:status:idempotency-key:'.$request->user()->id.':'.hash('sha1', $request->header('idempotency-key'));
  3004. $exists = Cache::has($key);
  3005. abort_if($exists, 400, 'Duplicate idempotency key.');
  3006. Cache::put($key, 1, 3600);
  3007. }
  3008. if (config('costar.enabled') == true) {
  3009. $blockedKeywords = config('costar.keyword.block');
  3010. if ($blockedKeywords !== null && $request->status) {
  3011. $keywords = config('costar.keyword.block');
  3012. foreach ($keywords as $kw) {
  3013. if (Str::contains($request->status, $kw) == true) {
  3014. abort(400, 'Invalid object. Contains banned keyword.');
  3015. }
  3016. }
  3017. }
  3018. }
  3019. if (! $request->filled('media_ids') && ! $request->filled('in_reply_to_id')) {
  3020. abort(403, 'Empty statuses are not allowed');
  3021. }
  3022. $ids = $request->input('media_ids');
  3023. $in_reply_to_id = $request->input('in_reply_to_id');
  3024. $user = $request->user();
  3025. if ($user->has_roles) {
  3026. if ($in_reply_to_id != null) {
  3027. abort_if(! UserRoleService::can('can-comment', $user->id), 403, 'Invalid permissions for this action');
  3028. } else {
  3029. abort_if(! UserRoleService::can('can-post', $user->id), 403, 'Invalid permissions for this action');
  3030. }
  3031. }
  3032. $profile = $user->profile;
  3033. $limitKey = 'compose:rate-limit:store:'.$user->id;
  3034. $limitTtl = now()->addMinutes(15);
  3035. $limitReached = Cache::remember($limitKey, $limitTtl, function () use ($user) {
  3036. $minId = SnowflakeService::byDate(now()->subDays(1));
  3037. $dailyLimit = Status::whereProfileId($user->profile_id)
  3038. ->where('id', '>', $minId)
  3039. ->count();
  3040. return $dailyLimit >= 1000;
  3041. });
  3042. abort_if($limitReached == true, 429);
  3043. $visibility = $profile->is_private ? 'private' : (
  3044. $profile->unlisted == true &&
  3045. $request->input('visibility', 'public') == 'public' ?
  3046. 'unlisted' :
  3047. $request->input('visibility', 'public'));
  3048. if ($user->last_active_at == null) {
  3049. return [];
  3050. }
  3051. $defaultCaption = '';
  3052. $content = $request->filled('status') ? strip_tags($request->input('status')) : $defaultCaption;
  3053. $cw = $user->profile->cw == true ? true : $request->boolean('sensitive', false);
  3054. $spoilerText = $cw && $request->filled('spoiler_text') ? $request->input('spoiler_text') : null;
  3055. if ($in_reply_to_id) {
  3056. $parent = Status::findOrFail($in_reply_to_id);
  3057. if ($parent->comments_disabled) {
  3058. return $this->json('Comments have been disabled on this post', 422);
  3059. }
  3060. $blocks = UserFilterService::blocks($parent->profile_id);
  3061. abort_if(in_array($profile->id, $blocks), 422, 'Cannot reply to this post at this time.');
  3062. $status = new Status;
  3063. $status->caption = $content;
  3064. $status->rendered = $defaultCaption;
  3065. $status->scope = $visibility;
  3066. $status->visibility = $visibility;
  3067. $status->profile_id = $user->profile_id;
  3068. $status->is_nsfw = $cw;
  3069. $status->cw_summary = $spoilerText;
  3070. $status->in_reply_to_id = $parent->id;
  3071. $status->in_reply_to_profile_id = $parent->profile_id;
  3072. $status->save();
  3073. StatusService::del($parent->id);
  3074. Cache::forget('status:replies:all:'.$parent->id);
  3075. }
  3076. if ($ids) {
  3077. if (Media::whereUserId($user->id)
  3078. ->whereNull('status_id')
  3079. ->find($ids)
  3080. ->count() == 0
  3081. ) {
  3082. abort(400, 'Invalid media_ids');
  3083. }
  3084. if (! $in_reply_to_id) {
  3085. $status = new Status;
  3086. $status->caption = $content;
  3087. $status->rendered = $defaultCaption;
  3088. $status->profile_id = $user->profile_id;
  3089. $status->is_nsfw = $cw;
  3090. $status->cw_summary = $spoilerText;
  3091. $status->scope = 'draft';
  3092. $status->visibility = 'draft';
  3093. if ($request->has('place_id')) {
  3094. $status->place_id = $request->input('place_id');
  3095. }
  3096. $status->save();
  3097. }
  3098. $mimes = [];
  3099. foreach ($ids as $k => $v) {
  3100. if ($k + 1 > (int) config_cache('pixelfed.max_album_length')) {
  3101. continue;
  3102. }
  3103. $m = Media::whereUserId($user->id)->whereNull('status_id')->findOrFail($v);
  3104. if ($m->profile_id !== $user->profile_id || $m->status_id) {
  3105. abort(403, 'Invalid media id');
  3106. }
  3107. $m->order = $k + 1;
  3108. $m->status_id = $status->id;
  3109. $m->save();
  3110. array_push($mimes, $m->mime);
  3111. }
  3112. if (empty($mimes)) {
  3113. $status->delete();
  3114. abort(400, 'Invalid media ids');
  3115. }
  3116. if ($request->has('comments_disabled') && $request->input('comments_disabled')) {
  3117. $status->comments_disabled = true;
  3118. }
  3119. $status->scope = $visibility;
  3120. $status->visibility = $visibility;
  3121. $status->type = StatusController::mimeTypeCheck($mimes);
  3122. $status->save();
  3123. }
  3124. if (! $status) {
  3125. abort(500, 'An error occured.');
  3126. }
  3127. NewStatusPipeline::dispatch($status);
  3128. if ($status->in_reply_to_id) {
  3129. CommentPipeline::dispatch($parent, $status);
  3130. }
  3131. Cache::forget('user:account:id:'.$user->id);
  3132. Cache::forget('_api:statuses:recent_9:'.$user->profile_id);
  3133. Cache::forget('profile:status_count:'.$user->profile_id);
  3134. Cache::forget($user->storageUsedKey());
  3135. Cache::forget('profile:embed:'.$status->profile_id);
  3136. Cache::forget($limitKey);
  3137. if ($request->has('collection_ids') && $ids) {
  3138. $collections = Collection::whereProfileId($user->profile_id)
  3139. ->find($request->input('collection_ids'))
  3140. ->each(function ($collection) use ($status) {
  3141. $count = $collection->items()->count();
  3142. $item = CollectionItem::firstOrCreate([
  3143. 'collection_id' => $collection->id,
  3144. 'object_type' => 'App\Status',
  3145. 'object_id' => $status->id,
  3146. ], [
  3147. 'order' => $count,
  3148. ]);
  3149. CollectionService::addItem(
  3150. $collection->id,
  3151. $status->id,
  3152. $count
  3153. );
  3154. $collection->updated_at = now();
  3155. $collection->save();
  3156. CollectionService::setCollection($collection->id, $collection);
  3157. });
  3158. }
  3159. $res = StatusService::getMastodon($status->id, false);
  3160. $res['favourited'] = false;
  3161. $res['language'] = 'en';
  3162. $res['bookmarked'] = false;
  3163. $res['card'] = null;
  3164. return $this->json($res);
  3165. }
  3166. /**
  3167. * DELETE /api/v1/statuses
  3168. *
  3169. * @param int $id
  3170. * @return null
  3171. */
  3172. public function statusDelete(Request $request, $id)
  3173. {
  3174. abort_if(! $request->user() || ! $request->user()->token(), 403);
  3175. abort_unless($request->user()->tokenCan('write'), 403);
  3176. AccountService::setLastActive($request->user()->id);
  3177. $status = Status::whereProfileId($request->user()->profile->id)
  3178. ->findOrFail($id);
  3179. $resource = new Fractal\Resource\Item($status, new StatusTransformer);
  3180. Cache::forget('profile:status_count:'.$status->profile_id);
  3181. StatusDelete::dispatch($status);
  3182. $res = $this->fractal->createData($resource)->toArray();
  3183. $res['text'] = $res['content'];
  3184. unset($res['content']);
  3185. return $this->json($res);
  3186. }
  3187. /**
  3188. * POST /api/v1/statuses/{id}/reblog
  3189. *
  3190. * @param int $id
  3191. * @return StatusTransformer
  3192. */
  3193. public function statusShare(Request $request, $id)
  3194. {
  3195. abort_if(! $request->user() || ! $request->user()->token(), 403);
  3196. abort_unless($request->user()->tokenCan('write'), 403);
  3197. $user = $request->user();
  3198. abort_if($user->has_roles && ! UserRoleService::can('can-share', $user->id), 403, 'Invalid permissions for this action');
  3199. AccountService::setLastActive($user->id);
  3200. $status = Status::whereScope('public')->findOrFail($id);
  3201. $account = AccountService::get($status->profile_id);
  3202. abort_if(isset($account['moved'], $account['moved']['id']), 422, 'Cannot share a post from an account that has migrated');
  3203. if ($status && ($status->uri || $status->url || $status->object_url)) {
  3204. $url = $status->uri ?? $status->url ?? $status->object_url;
  3205. $domain = parse_url($url, PHP_URL_HOST);
  3206. abort_if(in_array($domain, InstanceService::getBannedDomains()), 404);
  3207. }
  3208. if (intval($status->profile_id) !== intval($user->profile_id)) {
  3209. if ($status->scope == 'private') {
  3210. abort_if(! FollowerService::follows($user->profile_id, $status->profile_id), 403);
  3211. } else {
  3212. abort_if(! in_array($status->scope, ['public', 'unlisted']), 403);
  3213. }
  3214. $blocks = UserFilterService::blocks($status->profile_id);
  3215. if ($blocks && in_array($user->profile_id, $blocks)) {
  3216. abort(422);
  3217. }
  3218. }
  3219. $defaultCaption = config_cache('database.default') === 'mysql' ? null : '';
  3220. $share = Status::firstOrCreate([
  3221. 'caption' => $defaultCaption,
  3222. 'rendered' => $defaultCaption,
  3223. 'profile_id' => $user->profile_id,
  3224. 'reblog_of_id' => $status->id,
  3225. 'type' => 'share',
  3226. 'in_reply_to_profile_id' => $status->profile_id,
  3227. 'scope' => 'public',
  3228. 'visibility' => 'public',
  3229. ]);
  3230. SharePipeline::dispatch($share)->onQueue('low');
  3231. StatusService::del($status->id);
  3232. ReblogService::add($user->profile_id, $status->id);
  3233. $res = StatusService::getMastodon($status->id);
  3234. $res['reblogged'] = true;
  3235. $res['favourited'] = LikeService::liked($user->profile_id, $status->id);
  3236. $res['bookmarked'] = BookmarkService::get($user->profile_id, $status->id);
  3237. return $this->json($res);
  3238. }
  3239. /**
  3240. * POST /api/v1/statuses/{id}/unreblog
  3241. *
  3242. * @param int $id
  3243. * @return StatusTransformer
  3244. */
  3245. public function statusUnshare(Request $request, $id)
  3246. {
  3247. abort_if(! $request->user() || ! $request->user()->token(), 403);
  3248. abort_unless($request->user()->tokenCan('write'), 403);
  3249. $user = $request->user();
  3250. abort_if($user->has_roles && ! UserRoleService::can('can-share', $user->id), 403, 'Invalid permissions for this action');
  3251. AccountService::setLastActive($user->id);
  3252. $status = Status::whereScope('public')->findOrFail($id);
  3253. $account = AccountService::get($status->profile_id);
  3254. abort_if(isset($account['moved'], $account['moved']['id']), 422, 'Cannot unshare a post from an account that has migrated');
  3255. if (intval($status->profile_id) !== intval($user->profile_id)) {
  3256. if ($status->scope == 'private') {
  3257. abort_if(! FollowerService::follows($user->profile_id, $status->profile_id), 403);
  3258. } else {
  3259. abort_if(! in_array($status->scope, ['public', 'unlisted']), 403);
  3260. }
  3261. }
  3262. $reblog = Status::whereProfileId($user->profile_id)
  3263. ->whereReblogOfId($status->id)
  3264. ->first();
  3265. if (! $reblog) {
  3266. $res = StatusService::getMastodon($status->id);
  3267. $res['reblogged'] = false;
  3268. return $this->json($res);
  3269. }
  3270. UndoSharePipeline::dispatch($reblog)->onQueue('low');
  3271. ReblogService::del($user->profile_id, $status->id);
  3272. $res = StatusService::getMastodon($status->id);
  3273. $res['reblogged'] = false;
  3274. $res['favourited'] = LikeService::liked($user->profile_id, $status->id);
  3275. $res['bookmarked'] = BookmarkService::get($user->profile_id, $status->id);
  3276. return $this->json($res);
  3277. }
  3278. /**
  3279. * GET /api/v1/timelines/tag/{hashtag}
  3280. *
  3281. * @param string $hashtag
  3282. * @return StatusTransformer
  3283. */
  3284. public function timelineHashtag(Request $request, $hashtag)
  3285. {
  3286. abort_if(! $request->user() || ! $request->user()->token(), 403);
  3287. abort_unless($request->user()->tokenCan('read'), 403);
  3288. $this->validate($request, [
  3289. 'page' => 'nullable|integer|max:40',
  3290. 'min_id' => 'nullable|integer|min:0|max:'.PHP_INT_MAX,
  3291. 'max_id' => 'nullable|integer|min:0|max:'.PHP_INT_MAX,
  3292. 'limit' => 'sometimes|integer|min:1',
  3293. 'only_media' => 'sometimes',
  3294. '_pe' => 'sometimes',
  3295. ]);
  3296. $user = $request->user();
  3297. abort_if(
  3298. $user->has_roles && ! UserRoleService::can('can-view-hashtag-feed', $user->id),
  3299. 403,
  3300. 'Invalid permissions for this action'
  3301. );
  3302. if (config('database.default') === 'pgsql') {
  3303. $tag = Hashtag::where('name', 'ilike', $hashtag)
  3304. ->orWhere('slug', 'ilike', $hashtag)
  3305. ->first();
  3306. } else {
  3307. $tag = Hashtag::whereName($hashtag)
  3308. ->orWhere('slug', $hashtag)
  3309. ->first();
  3310. }
  3311. if (! $tag) {
  3312. return response()->json([]);
  3313. }
  3314. if ($tag->is_banned == true) {
  3315. return $this->json([]);
  3316. }
  3317. $min = $request->input('min_id');
  3318. $max = $request->input('max_id');
  3319. $limit = $request->input('limit', 20);
  3320. if ($limit > 40) {
  3321. $limit = 40;
  3322. }
  3323. $onlyMedia = $request->boolean('only_media', true);
  3324. $pe = $request->has(self::PF_API_ENTITY_KEY);
  3325. $pid = $request->user()->profile_id;
  3326. if ($min || $max) {
  3327. $minMax = SnowflakeService::byDate(now()->subMonths(6));
  3328. if ($min && intval($min) < $minMax) {
  3329. return [];
  3330. }
  3331. if ($max && intval($max) < $minMax) {
  3332. return [];
  3333. }
  3334. }
  3335. $filters = UserFilterService::filters($pid);
  3336. $domainBlocks = UserFilterService::domainBlocks($pid);
  3337. if (! $min && ! $max) {
  3338. $id = 1;
  3339. $dir = '>';
  3340. } else {
  3341. $dir = $min ? '>' : '<';
  3342. $id = $min ?? $max;
  3343. }
  3344. $res = StatusHashtag::whereHashtagId($tag->id)
  3345. ->where('status_id', $dir, $id)
  3346. ->orderBy('status_id', 'desc')
  3347. ->limit(100)
  3348. ->pluck('status_id')
  3349. ->map(function ($i) use ($pe) {
  3350. return $pe ? StatusService::get($i, false) : StatusService::getMastodon($i, false);
  3351. })
  3352. ->filter(function ($i) use ($onlyMedia, $pid) {
  3353. if (! $i || ! isset($i['account'], $i['account']['id'])) {
  3354. return false;
  3355. }
  3356. if ($i['visibility'] === 'unlisted') {
  3357. if ((int) $i['account']['id'] !== $pid) {
  3358. return false;
  3359. }
  3360. }
  3361. // if ($i['visibility'] === 'private') {
  3362. // if ((int) $i['account']['id'] !== $pid) {
  3363. // return FollowerService::follows($pid, $i['account']['id'], true);
  3364. // }
  3365. // }
  3366. if ($onlyMedia == true) {
  3367. if (! isset($i['media_attachments']) || ! count($i['media_attachments'])) {
  3368. return false;
  3369. }
  3370. }
  3371. return $i && isset($i['account'], $i['url']);
  3372. })
  3373. ->filter(function ($i) use ($filters, $domainBlocks) {
  3374. $domain = strtolower(parse_url($i['url'], PHP_URL_HOST));
  3375. return ! in_array($i['account']['id'], $filters) && ! in_array($domain, $domainBlocks);
  3376. })
  3377. ->take($limit)
  3378. ->values()
  3379. ->toArray();
  3380. return $this->json($res);
  3381. }
  3382. /**
  3383. * GET /api/v1/bookmarks
  3384. *
  3385. *
  3386. *
  3387. * @return StatusTransformer
  3388. */
  3389. public function bookmarks(Request $request)
  3390. {
  3391. abort_if(! $request->user() || ! $request->user()->token(), 403);
  3392. abort_unless($request->user()->tokenCan('read'), 403);
  3393. $this->validate($request, [
  3394. 'limit' => 'sometimes|integer|min:1',
  3395. 'max_id' => 'nullable|integer|min:0',
  3396. 'since_id' => 'nullable|integer|min:0',
  3397. 'min_id' => 'nullable|integer|min:0',
  3398. ]);
  3399. $pe = $request->has('_pe');
  3400. $pid = $request->user()->profile_id;
  3401. $limit = $request->input('limit') ?? 20;
  3402. if ($limit > 40) {
  3403. $limit = 40;
  3404. }
  3405. $max_id = $request->input('max_id');
  3406. $since_id = $request->input('since_id');
  3407. $min_id = $request->input('min_id');
  3408. $dir = $min_id ? '>' : '<';
  3409. $id = $min_id ?? $max_id;
  3410. $bookmarkQuery = Bookmark::whereProfileId($pid)
  3411. ->orderByDesc('id')
  3412. ->cursorPaginate($limit);
  3413. $bookmarks = $bookmarkQuery->map(function ($bookmark) use ($pid, $pe) {
  3414. $status = $pe ? StatusService::get($bookmark->status_id, false) : StatusService::getMastodon($bookmark->status_id, false);
  3415. if ($status) {
  3416. $status['bookmarked'] = true;
  3417. $status['favourited'] = LikeService::liked($pid, $status['id']);
  3418. $status['reblogged'] = ReblogService::get($pid, $status['id']);
  3419. }
  3420. return $status;
  3421. })
  3422. ->filter()
  3423. ->values()
  3424. ->toArray();
  3425. $links = null;
  3426. $headers = [];
  3427. if ($bookmarkQuery->nextCursor()) {
  3428. $links .= '<'.$bookmarkQuery->nextPageUrl().'&limit='.$limit.'>; rel="next"';
  3429. }
  3430. if ($bookmarkQuery->previousCursor()) {
  3431. if ($links != null) {
  3432. $links .= ', ';
  3433. }
  3434. $links .= '<'.$bookmarkQuery->previousPageUrl().'&limit='.$limit.'>; rel="prev"';
  3435. }
  3436. if ($links) {
  3437. $headers = ['Link' => $links];
  3438. }
  3439. return $this->json($bookmarks, 200, $headers);
  3440. }
  3441. /**
  3442. * POST /api/v1/statuses/{id}/bookmark
  3443. *
  3444. *
  3445. *
  3446. * @return StatusTransformer
  3447. */
  3448. public function bookmarkStatus(Request $request, $id)
  3449. {
  3450. abort_if(! $request->user() || ! $request->user()->token(), 403);
  3451. abort_unless($request->user()->tokenCan('write'), 403);
  3452. $status = Status::findOrFail($id);
  3453. $user = $request->user();
  3454. $pid = $request->user()->profile_id;
  3455. $account = AccountService::get($status->profile_id);
  3456. abort_if(isset($account['moved'], $account['moved']['id']), 422, 'Cannot bookmark a post from an account that has migrated');
  3457. abort_if($user->has_roles && ! UserRoleService::can('can-bookmark', $user->id), 403, 'Invalid permissions for this action');
  3458. abort_if($status->in_reply_to_id || $status->reblog_of_id, 404);
  3459. abort_if(! in_array($status->scope, ['public', 'unlisted', 'private']), 404);
  3460. abort_if(! in_array($status->type, ['photo', 'photo:album', 'video', 'video:album', 'photo:video:album']), 404);
  3461. if ($status->scope == 'private') {
  3462. abort_if(
  3463. $pid !== $status->profile_id && ! FollowerService::follows($pid, $status->profile_id),
  3464. 404,
  3465. 'Error: You cannot bookmark private posts from accounts you do not follow.'
  3466. );
  3467. }
  3468. Bookmark::firstOrCreate([
  3469. 'status_id' => $status->id,
  3470. 'profile_id' => $pid,
  3471. ]);
  3472. BookmarkService::add($pid, $status->id);
  3473. $res = StatusService::getMastodon($status->id, false);
  3474. $res['bookmarked'] = true;
  3475. return $this->json($res);
  3476. }
  3477. /**
  3478. * POST /api/v1/statuses/{id}/unbookmark
  3479. *
  3480. *
  3481. *
  3482. * @return StatusTransformer
  3483. */
  3484. public function unbookmarkStatus(Request $request, $id)
  3485. {
  3486. abort_if(! $request->user() || ! $request->user()->token(), 403);
  3487. abort_unless($request->user()->tokenCan('write'), 403);
  3488. $status = Status::findOrFail($id);
  3489. $pid = $request->user()->profile_id;
  3490. $user = $request->user();
  3491. abort_if($user->has_roles && ! UserRoleService::can('can-bookmark', $user->id), 403, 'Invalid permissions for this action');
  3492. abort_if($status->in_reply_to_id || $status->reblog_of_id, 404);
  3493. abort_if(! in_array($status->scope, ['public', 'unlisted', 'private']), 404);
  3494. abort_if(! in_array($status->type, ['photo', 'photo:album', 'video', 'video:album', 'photo:video:album']), 404);
  3495. $bookmark = Bookmark::whereStatusId($status->id)
  3496. ->whereProfileId($pid)
  3497. ->first();
  3498. if ($bookmark) {
  3499. BookmarkService::del($pid, $status->id);
  3500. $bookmark->delete();
  3501. }
  3502. $res = StatusService::getMastodon($status->id, false);
  3503. $res['bookmarked'] = false;
  3504. return $this->json($res);
  3505. }
  3506. /**
  3507. * GET /api/v1/discover/posts
  3508. *
  3509. *
  3510. * @return array
  3511. */
  3512. public function discoverPosts(Request $request)
  3513. {
  3514. abort_if(! $request->user() || ! $request->user()->token(), 403);
  3515. abort_unless($request->user()->tokenCan('read'), 403);
  3516. $this->validate($request, [
  3517. 'limit' => 'integer|min:1|max:40',
  3518. ]);
  3519. $limit = $request->input('limit', 40);
  3520. $pid = $request->user()->profile_id;
  3521. $filters = UserFilterService::filters($pid);
  3522. $forYou = DiscoverService::getForYou();
  3523. $posts = $forYou->take(50)->map(function ($post) {
  3524. return StatusService::getMastodon($post);
  3525. })
  3526. ->filter(function ($post) use ($filters) {
  3527. return $post &&
  3528. isset($post['account']) &&
  3529. isset($post['account']['id']) &&
  3530. ! in_array($post['account']['id'], $filters);
  3531. })
  3532. ->take(12)
  3533. ->values();
  3534. return $this->json(compact('posts'));
  3535. }
  3536. /**
  3537. * GET /api/v2/statuses/{id}/replies
  3538. *
  3539. *
  3540. * @return array
  3541. */
  3542. public function statusReplies(Request $request, $id)
  3543. {
  3544. abort_if(! $request->user(), 403);
  3545. $this->validate($request, [
  3546. 'limit' => 'sometimes|integer|min:1',
  3547. 'sort' => 'in:all,newest,popular',
  3548. ]);
  3549. $limit = $request->input('limit', 3);
  3550. if ($limit > 10) {
  3551. $limit = 10;
  3552. }
  3553. $pid = $request->user()->profile_id;
  3554. $status = StatusService::getMastodon($id, false);
  3555. abort_if(! $status, 404);
  3556. abort_if(isset($status['account'], $account['account']['moved']['id']), 404, 'Account moved');
  3557. if ($status['visibility'] == 'private') {
  3558. if ($pid != $status['account']['id']) {
  3559. abort_unless(FollowerService::follows($pid, $status['account']['id']), 404);
  3560. }
  3561. }
  3562. $sortBy = $request->input('sort', 'all');
  3563. if ($sortBy == 'all' && isset($status['replies_count']) && $status['replies_count'] && $request->has('refresh_cache')) {
  3564. if (! Cache::has('status:replies:all-rc:'.$id)) {
  3565. Cache::forget('status:replies:all:'.$id);
  3566. Cache::put('status:replies:all-rc:'.$id, true, 300);
  3567. }
  3568. }
  3569. if ($sortBy == 'all' && ! $request->has('cursor')) {
  3570. $ids = Cache::remember('status:replies:all:'.$id, 3600, function () use ($id) {
  3571. return DB::table('statuses')
  3572. ->where('in_reply_to_id', $id)
  3573. ->orderBy('id')
  3574. ->cursorPaginate(3);
  3575. });
  3576. } else {
  3577. $ids = DB::table('statuses')
  3578. ->where('in_reply_to_id', $id)
  3579. ->when($sortBy, function ($q, $sortBy) {
  3580. if ($sortBy === 'all') {
  3581. return $q->orderBy('id');
  3582. }
  3583. if ($sortBy === 'newest') {
  3584. return $q->orderByDesc('created_at');
  3585. }
  3586. if ($sortBy === 'popular') {
  3587. return $q->orderByDesc('likes_count');
  3588. }
  3589. })
  3590. ->cursorPaginate($limit);
  3591. }
  3592. $filters = UserFilterService::filters($pid);
  3593. $data = $ids->filter(function ($post) use ($filters) {
  3594. return ! in_array($post->profile_id, $filters);
  3595. })
  3596. ->map(function ($post) use ($pid) {
  3597. $status = StatusService::get($post->id, false);
  3598. if (! $status || ! isset($status['id'])) {
  3599. return false;
  3600. }
  3601. $status['favourited'] = LikeService::liked($pid, $post->id);
  3602. return $status;
  3603. })
  3604. ->map(function ($post) {
  3605. if (isset($post['account']) && isset($post['account']['id'])) {
  3606. $account = AccountService::get($post['account']['id'], true);
  3607. $post['account'] = $account;
  3608. }
  3609. return $post;
  3610. })
  3611. ->filter(function ($post) {
  3612. return $post && isset($post['id']) && isset($post['account']) && isset($post['account']['id']);
  3613. })
  3614. ->values();
  3615. $res = [
  3616. 'data' => $data,
  3617. 'next' => $ids->nextPageUrl(),
  3618. ];
  3619. return $this->json($res);
  3620. }
  3621. /**
  3622. * GET /api/v2/statuses/{id}/state
  3623. *
  3624. *
  3625. * @return array
  3626. */
  3627. public function statusState(Request $request, $id)
  3628. {
  3629. abort_if(! $request->user(), 403);
  3630. $status = StatusService::get($id, false, true);
  3631. abort_if(! $status, 404);
  3632. abort_if(! in_array($status['visibility'], ['public', 'unlisted', 'private']), 404);
  3633. return $this->json(StatusService::getState($status['id'], $request->user()->profile_id));
  3634. }
  3635. /**
  3636. * GET /api/v1.1/discover/accounts/popular
  3637. *
  3638. *
  3639. * @return array
  3640. */
  3641. public function discoverAccountsPopular(Request $request)
  3642. {
  3643. abort_if(! $request->user() || ! $request->user()->token(), 403);
  3644. abort_unless($request->user()->tokenCan('read'), 403);
  3645. $pid = $request->user()->profile_id;
  3646. $ids = Cache::remember('api:v1.1:discover:accounts:popular', 14400, function () {
  3647. return DB::table('profiles')
  3648. ->where('is_private', false)
  3649. ->whereNull('status')
  3650. ->orderByDesc('profiles.followers_count')
  3651. ->limit(30)
  3652. ->get();
  3653. });
  3654. $filters = UserFilterService::filters($pid);
  3655. $asf = AdminShadowFilterService::getHideFromPublicFeedsList();
  3656. $ids = $ids->map(function ($profile) {
  3657. return AccountService::get($profile->id, true);
  3658. })
  3659. ->filter(function ($profile) {
  3660. return $profile && isset($profile['id'], $profile['locked']) && ! $profile['locked'];
  3661. })
  3662. ->filter(function ($profile) use ($pid) {
  3663. return $profile['id'] != $pid;
  3664. })
  3665. ->filter(function ($profile) use ($pid) {
  3666. return ! FollowerService::follows($pid, $profile['id'], true);
  3667. })
  3668. ->filter(function ($profile) use ($asf) {
  3669. return ! in_array($profile['id'], $asf);
  3670. })
  3671. ->filter(function ($profile) use ($filters) {
  3672. return ! in_array($profile['id'], $filters);
  3673. })
  3674. ->take(16)
  3675. ->values();
  3676. return $this->json($ids);
  3677. }
  3678. /**
  3679. * GET /api/v1/preferences
  3680. *
  3681. *
  3682. * @return array
  3683. */
  3684. public function getPreferences(Request $request)
  3685. {
  3686. abort_if(! $request->user() || ! $request->user()->token(), 403);
  3687. abort_unless($request->user()->tokenCan('read'), 403);
  3688. $pid = $request->user()->profile_id;
  3689. $account = AccountService::get($pid);
  3690. return $this->json([
  3691. 'posting:default:visibility' => $account['locked'] ? 'private' : 'public',
  3692. 'posting:default:sensitive' => false,
  3693. 'posting:default:language' => null,
  3694. 'reading:expand:media' => 'default',
  3695. 'reading:expand:spoilers' => false,
  3696. ]);
  3697. }
  3698. /**
  3699. * GET /api/v1/trends
  3700. *
  3701. *
  3702. * @return array
  3703. */
  3704. public function getTrends(Request $request)
  3705. {
  3706. abort_if(! $request->user() || ! $request->user()->token(), 403);
  3707. abort_unless($request->user()->tokenCan('read'), 403);
  3708. return $this->json([]);
  3709. }
  3710. /**
  3711. * GET /api/v1/announcements
  3712. *
  3713. *
  3714. * @return array
  3715. */
  3716. public function getAnnouncements(Request $request)
  3717. {
  3718. abort_if(! $request->user() || ! $request->user()->token(), 403);
  3719. abort_unless($request->user()->tokenCan('read'), 403);
  3720. return $this->json([]);
  3721. }
  3722. /**
  3723. * GET /api/v1/markers
  3724. *
  3725. *
  3726. * @return array
  3727. */
  3728. public function getMarkers(Request $request)
  3729. {
  3730. abort_if(! $request->user() || ! $request->user()->token(), 403);
  3731. abort_unless($request->user()->tokenCan('read'), 403);
  3732. $type = $request->input('timeline');
  3733. if (is_array($type)) {
  3734. $type = $type[0];
  3735. }
  3736. if (! $type || ! in_array($type, ['home', 'notifications'])) {
  3737. return $this->json([]);
  3738. }
  3739. $pid = $request->user()->profile_id;
  3740. return $this->json(MarkerService::get($pid, $type));
  3741. }
  3742. /**
  3743. * POST /api/v1/markers
  3744. *
  3745. *
  3746. * @return array
  3747. */
  3748. public function setMarkers(Request $request)
  3749. {
  3750. abort_if(! $request->user() || ! $request->user()->token(), 403);
  3751. abort_unless($request->user()->tokenCan('write'), 403);
  3752. $pid = $request->user()->profile_id;
  3753. $home = $request->input('home[last_read_id]');
  3754. $notifications = $request->input('notifications[last_read_id]');
  3755. if ($home) {
  3756. return $this->json(MarkerService::set($pid, 'home', $home));
  3757. }
  3758. if ($notifications) {
  3759. return $this->json(MarkerService::set($pid, 'notifications', $notifications));
  3760. }
  3761. return $this->json([]);
  3762. }
  3763. /**
  3764. * GET /api/v1/instance/peers
  3765. *
  3766. *
  3767. * @return array
  3768. */
  3769. public function instancePeers(Request $request)
  3770. {
  3771. if ((bool) config('instance.show_peers') == false) {
  3772. return $this->json([]);
  3773. }
  3774. return $this->json(
  3775. Cache::remember(InstanceService::CACHE_KEY_API_PEERS_LIST, now()->addHours(24), function () {
  3776. return Instance::whereNotNull('nodeinfo_last_fetched')
  3777. ->whereBanned(false)
  3778. ->where('nodeinfo_last_fetched', '>', now()->subDays(8))
  3779. ->pluck('domain');
  3780. })
  3781. );
  3782. }
  3783. /**
  3784. * GET /api/v1/statuses/{id}/pin
  3785. */
  3786. public function statusPin(Request $request, $id)
  3787. {
  3788. abort_if(! $request->user(), 403);
  3789. abort_unless($request->user()->tokenCan('write'), 403);
  3790. $user = $request->user();
  3791. $status = Status::whereScope('public')->find($id);
  3792. if (! $status) {
  3793. return $this->json(['error' => 'Record not found'], 404);
  3794. }
  3795. if ($status->profile_id != $user->profile_id) {
  3796. return $this->json(['error' => "Validation failed: Someone else's post cannot be pinned"], 422);
  3797. }
  3798. $res = StatusService::markPin($status->id);
  3799. if (! $res['success']) {
  3800. return $this->json([
  3801. 'error' => $res['error'],
  3802. ], 422);
  3803. }
  3804. $statusRes = StatusService::get($status->id, true, true);
  3805. $status['pinned'] = true;
  3806. return $this->json($statusRes);
  3807. }
  3808. /**
  3809. * GET /api/v1/statuses/{id}/unpin
  3810. */
  3811. public function statusUnpin(Request $request, $id)
  3812. {
  3813. abort_if(! $request->user(), 403);
  3814. abort_unless($request->user()->tokenCan('write'), 403);
  3815. $status = Status::whereScope('public')->findOrFail($id);
  3816. $user = $request->user();
  3817. if ($status->profile_id != $user->profile_id) {
  3818. return $this->json(['error' => 'Record not found'], 404);
  3819. }
  3820. $res = StatusService::unmarkPin($status->id);
  3821. if (! $res) {
  3822. return $this->json($res, 422);
  3823. }
  3824. $status = StatusService::get($status->id, true, true);
  3825. $status['pinned'] = false;
  3826. return $this->json($status);
  3827. }
  3828. }