ApiV1Controller.php 162 KB

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