ApiV1Controller.php 154 KB

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