ApiV1Controller.php 151 KB

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