ApiV1Controller.php 145 KB

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