ApiV1Controller.php 143 KB

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