ApiV1Controller.php 146 KB

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