ApiV1Controller.php 152 KB

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