ApiV1Controller.php 148 KB

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