ApiV1Controller.php 162 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664
  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/jpg,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/jpg':
  1629. case 'image/jpeg':
  1630. case 'image/png':
  1631. case 'image/webp':
  1632. case 'image/avif':
  1633. ImageOptimize::dispatch($media)->onQueue('mmo');
  1634. break;
  1635. case 'video/mp4':
  1636. VideoThumbnail::dispatch($media)->onQueue('mmo');
  1637. $preview_url = '/storage/no-preview.png';
  1638. $url = '/storage/no-preview.png';
  1639. break;
  1640. }
  1641. $user->storage_used = (int) $updatedAccountSize;
  1642. $user->storage_used_updated_at = now();
  1643. $user->save();
  1644. Cache::forget($limitKey);
  1645. $resource = new Fractal\Resource\Item($media, new MediaTransformer);
  1646. $res = $this->fractal->createData($resource)->toArray();
  1647. $res['preview_url'] = $media->url().'?v='.time();
  1648. $res['url'] = $media->url().'?v='.time();
  1649. return $this->json($res);
  1650. }
  1651. /**
  1652. * PUT /api/v1/media/{id}
  1653. *
  1654. * @param int $id
  1655. * @return MediaTransformer
  1656. */
  1657. public function mediaUpdate(Request $request, $id)
  1658. {
  1659. abort_if(! $request->user() || ! $request->user()->token(), 403);
  1660. abort_unless($request->user()->tokenCan('write'), 403);
  1661. $this->validate($request, [
  1662. 'description' => 'nullable|string|max:'.config_cache('pixelfed.max_altext_length'),
  1663. ]);
  1664. $user = $request->user();
  1665. abort_if($user->has_roles && ! UserRoleService::can('can-post', $user->id), 403, 'Invalid permissions for this action');
  1666. AccountService::setLastActive($user->id);
  1667. $media = Media::whereUserId($user->id)
  1668. ->whereProfileId($user->profile_id)
  1669. ->findOrFail($id);
  1670. $executed = RateLimiter::attempt(
  1671. 'media:update:'.$user->id,
  1672. 10,
  1673. function () use ($media, $request) {
  1674. $caption = Purify::clean($request->input('description'));
  1675. if ($caption != $media->caption) {
  1676. $media->caption = $caption;
  1677. $media->save();
  1678. if ($media->status_id) {
  1679. MediaService::del($media->status_id);
  1680. StatusService::del($media->status_id);
  1681. }
  1682. }
  1683. });
  1684. if (! $executed) {
  1685. return response()->json([
  1686. 'error' => 'Too many attempts. Try again in a few minutes.',
  1687. ], 429);
  1688. }
  1689. $fractal = new Fractal\Manager;
  1690. $fractal->setSerializer(new ArraySerializer);
  1691. $resource = new Fractal\Resource\Item($media, new MediaTransformer);
  1692. return $this->json($fractal->createData($resource)->toArray());
  1693. }
  1694. /**
  1695. * GET /api/v1/media/{id}
  1696. *
  1697. * @param int $id
  1698. * @return MediaTransformer
  1699. */
  1700. public function mediaGet(Request $request, $id)
  1701. {
  1702. abort_if(! $request->user() || ! $request->user()->token(), 403);
  1703. abort_unless($request->user()->tokenCan('read'), 403);
  1704. $user = $request->user();
  1705. abort_if($user->has_roles && ! UserRoleService::can('can-post', $user->id), 403, 'Invalid permissions for this action');
  1706. AccountService::setLastActive($user->id);
  1707. $media = Media::whereUserId($user->id)
  1708. ->whereNull('status_id')
  1709. ->findOrFail($id);
  1710. $resource = new Fractal\Resource\Item($media, new MediaTransformer);
  1711. $res = $this->fractal->createData($resource)->toArray();
  1712. return $this->json($res);
  1713. }
  1714. /**
  1715. * POST /api/v2/media
  1716. *
  1717. *
  1718. * @return MediaTransformer
  1719. */
  1720. public function mediaUploadV2(Request $request)
  1721. {
  1722. abort_if(! $request->user() || ! $request->user()->token(), 403);
  1723. abort_unless($request->user()->tokenCan('write'), 403);
  1724. $this->validate($request, [
  1725. 'file.*' => [
  1726. 'required_without:file',
  1727. 'mimetypes:'.config_cache('pixelfed.media_types'),
  1728. 'max:'.config_cache('pixelfed.max_photo_size'),
  1729. ],
  1730. 'file' => [
  1731. 'required_without:file.*',
  1732. 'mimetypes:'.config_cache('pixelfed.media_types'),
  1733. 'max:'.config_cache('pixelfed.max_photo_size'),
  1734. ],
  1735. 'filter_name' => 'nullable|string|max:24',
  1736. 'filter_class' => 'nullable|alpha_dash|max:24',
  1737. 'description' => 'nullable|string|max:'.config_cache('pixelfed.max_altext_length'),
  1738. 'replace_id' => 'sometimes',
  1739. ]);
  1740. $user = $request->user();
  1741. abort_if($user->has_roles && ! UserRoleService::can('can-post', $user->id), 403, 'Invalid permissions for this action');
  1742. if ($user->last_active_at == null) {
  1743. return [];
  1744. }
  1745. AccountService::setLastActive($user->id);
  1746. if (empty($request->file('file'))) {
  1747. return response('', 422);
  1748. }
  1749. $limitKey = 'compose:rate-limit:media-upload:'.$user->id;
  1750. $limitTtl = now()->addMinutes(15);
  1751. $limitReached = Cache::remember($limitKey, $limitTtl, function () use ($user) {
  1752. $dailyLimit = Media::whereUserId($user->id)->where('created_at', '>', now()->subDays(1))->count();
  1753. return $dailyLimit >= 1250;
  1754. });
  1755. abort_if($limitReached == true, 429);
  1756. $profile = $user->profile;
  1757. $accountSize = UserStorageService::get($user->id);
  1758. abort_if($accountSize === -1, 403, 'Invalid request.');
  1759. $photo = $request->file('file');
  1760. $fileSize = $photo->getSize();
  1761. $sizeInKbs = (int) ceil($fileSize / 1000);
  1762. $updatedAccountSize = (int) $accountSize + (int) $sizeInKbs;
  1763. if ((bool) config_cache('pixelfed.enforce_account_limit') == true) {
  1764. $limit = (int) config_cache('pixelfed.max_account_size');
  1765. if ($updatedAccountSize >= $limit) {
  1766. abort(403, 'Account size limit reached.');
  1767. }
  1768. }
  1769. $filterClass = in_array($request->input('filter_class'), Filter::classes()) ? $request->input('filter_class') : null;
  1770. $filterName = in_array($request->input('filter_name'), Filter::names()) ? $request->input('filter_name') : null;
  1771. $mimes = explode(',', config_cache('pixelfed.media_types'));
  1772. if (in_array($photo->getMimeType(), $mimes) == false) {
  1773. abort(403, 'Invalid or unsupported mime type.');
  1774. }
  1775. $storagePath = MediaPathService::get($user, 2);
  1776. $path = $photo->storePublicly($storagePath);
  1777. $hash = \hash_file('sha256', $photo);
  1778. $license = null;
  1779. $mime = $photo->getMimeType();
  1780. $settings = UserSetting::whereUserId($user->id)->first();
  1781. if ($settings && ! empty($settings->compose_settings)) {
  1782. $compose = $settings->compose_settings;
  1783. if (isset($compose['default_license']) && $compose['default_license'] != 1) {
  1784. $license = $compose['default_license'];
  1785. }
  1786. }
  1787. abort_if(MediaBlocklistService::exists($hash) == true, 451);
  1788. if ($request->has('replace_id')) {
  1789. $rpid = $request->input('replace_id');
  1790. $removeMedia = Media::whereNull('status_id')
  1791. ->whereUserId($user->id)
  1792. ->whereProfileId($profile->id)
  1793. ->where('created_at', '>', now()->subHours(2))
  1794. ->find($rpid);
  1795. if ($removeMedia) {
  1796. $dateTime = Carbon::now();
  1797. MediaDeletePipeline::dispatch($removeMedia)
  1798. ->onQueue('mmo')
  1799. ->delay($dateTime->addMinutes(15));
  1800. }
  1801. }
  1802. $media = new Media;
  1803. $media->status_id = null;
  1804. $media->profile_id = $profile->id;
  1805. $media->user_id = $user->id;
  1806. $media->media_path = $path;
  1807. $media->original_sha256 = $hash;
  1808. $media->size = $photo->getSize();
  1809. $media->mime = $mime;
  1810. $media->caption = $request->input('description') ?? '';
  1811. $media->filter_class = $filterClass;
  1812. $media->filter_name = $filterName;
  1813. if ($license) {
  1814. $media->license = $license;
  1815. }
  1816. $media->save();
  1817. switch ($media->mime) {
  1818. case 'image/jpg':
  1819. case 'image/jpeg':
  1820. case 'image/png':
  1821. case 'image/webp':
  1822. case 'image/avif':
  1823. ImageOptimize::dispatch($media)->onQueue('mmo');
  1824. break;
  1825. case 'video/mp4':
  1826. VideoThumbnail::dispatch($media)->onQueue('mmo');
  1827. $preview_url = '/storage/no-preview.png';
  1828. $url = '/storage/no-preview.png';
  1829. break;
  1830. }
  1831. $user->storage_used = (int) $updatedAccountSize;
  1832. $user->storage_used_updated_at = now();
  1833. $user->save();
  1834. Cache::forget($limitKey);
  1835. $resource = new Fractal\Resource\Item($media, new MediaTransformer);
  1836. $res = $this->fractal->createData($resource)->toArray();
  1837. $res['preview_url'] = $media->url().'?v='.time();
  1838. $res['url'] = null;
  1839. return $this->json($res, 202);
  1840. }
  1841. /**
  1842. * GET /api/v1/mutes
  1843. *
  1844. *
  1845. * @return AccountTransformer
  1846. */
  1847. public function accountMutes(Request $request)
  1848. {
  1849. abort_if(! $request->user() || ! $request->user()->token(), 403);
  1850. abort_unless($request->user()->tokenCan('read'), 403);
  1851. $this->validate($request, [
  1852. 'limit' => 'sometimes|integer|min:1',
  1853. ]);
  1854. $user = $request->user();
  1855. $limit = $request->input('limit', 40);
  1856. if ($limit > 80) {
  1857. $limit = 80;
  1858. }
  1859. $mutes = UserFilter::whereUserId($user->profile_id)
  1860. ->whereFilterableType('App\Profile')
  1861. ->whereFilterType('mute')
  1862. ->orderByDesc('id')
  1863. ->simplePaginate($limit)
  1864. ->withQueryString();
  1865. $res = $mutes->pluck('filterable_id')
  1866. ->map(function ($id) {
  1867. return AccountService::get($id, true);
  1868. })
  1869. ->filter(function ($account) {
  1870. return $account && isset($account['id']);
  1871. })
  1872. ->values();
  1873. $baseUrl = config('app.url').'/api/v1/mutes?limit='.$limit.'&';
  1874. $next = $mutes->nextPageUrl();
  1875. $prev = $mutes->previousPageUrl();
  1876. if ($next && ! $prev) {
  1877. $link = '<'.$next.'>; rel="next"';
  1878. }
  1879. if (! $next && $prev) {
  1880. $link = '<'.$prev.'>; rel="prev"';
  1881. }
  1882. if ($next && $prev) {
  1883. $link = '<'.$next.'>; rel="next",<'.$prev.'>; rel="prev"';
  1884. }
  1885. $headers = isset($link) ? ['Link' => $link] : [];
  1886. return $this->json($res, 200, $headers);
  1887. }
  1888. /**
  1889. * POST /api/v1/accounts/{id}/mute
  1890. *
  1891. * @param int $id
  1892. * @return RelationshipTransformer
  1893. */
  1894. public function accountMuteById(Request $request, $id)
  1895. {
  1896. abort_if(! $request->user() || ! $request->user()->token(), 403);
  1897. abort_unless($request->user()->tokenCan('write'), 403);
  1898. $user = $request->user();
  1899. $pid = $user->profile_id;
  1900. if (intval($pid) === intval($id)) {
  1901. return $this->json(['error' => 'You cannot mute yourself'], 500);
  1902. }
  1903. $account = Profile::findOrFail($id);
  1904. abort_if($account->moved_to_profile_id, 422, 'Cannot mute an account that has migrated!');
  1905. if ($account && $account->domain) {
  1906. $domain = $account->domain;
  1907. abort_if(in_array($domain, InstanceService::getBannedDomains()), 404);
  1908. }
  1909. $count = UserFilterService::muteCount($pid);
  1910. $maxLimit = (int) config_cache('instance.user_filters.max_user_mutes');
  1911. if ($count == 0) {
  1912. $filterCount = UserFilter::whereUserId($pid)
  1913. ->whereFilterType('mute')
  1914. ->get()
  1915. ->map(function ($rec) {
  1916. return AccountService::get($rec->filterable_id, true);
  1917. })
  1918. ->filter(function ($account) {
  1919. return $account && isset($account['id']);
  1920. })
  1921. ->values()
  1922. ->count();
  1923. abort_if($filterCount >= $maxLimit, 422, AccountController::FILTER_LIMIT_MUTE_TEXT.$maxLimit.' accounts');
  1924. } else {
  1925. abort_if($count >= $maxLimit, 422, AccountController::FILTER_LIMIT_MUTE_TEXT.$maxLimit.' accounts');
  1926. }
  1927. $filter = UserFilter::firstOrCreate([
  1928. 'user_id' => $pid,
  1929. 'filterable_id' => $account->id,
  1930. 'filterable_type' => 'App\Profile',
  1931. 'filter_type' => 'mute',
  1932. ]);
  1933. RelationshipService::refresh($pid, $id);
  1934. $resource = new Fractal\Resource\Item($account, new RelationshipTransformer);
  1935. $res = $this->fractal->createData($resource)->toArray();
  1936. return $this->json($res);
  1937. }
  1938. /**
  1939. * POST /api/v1/accounts/{id}/unmute
  1940. *
  1941. * @param int $id
  1942. * @return RelationshipTransformer
  1943. */
  1944. public function accountUnmuteById(Request $request, $id)
  1945. {
  1946. abort_if(! $request->user() || ! $request->user()->token(), 403);
  1947. abort_unless($request->user()->tokenCan('write'), 403);
  1948. $user = $request->user();
  1949. $pid = $user->profile_id;
  1950. if (intval($pid) === intval($id)) {
  1951. return $this->json(['error' => 'You cannot unmute yourself'], 500);
  1952. }
  1953. $profile = Profile::findOrFail($id);
  1954. abort_if($profile->moved_to_profile_id, 422, 'Cannot unmute an account that has migrated!');
  1955. $filter = UserFilter::whereUserId($pid)
  1956. ->whereFilterableId($profile->id)
  1957. ->whereFilterableType('App\Profile')
  1958. ->whereFilterType('mute')
  1959. ->first();
  1960. if ($filter) {
  1961. $filter->delete();
  1962. UserFilterService::unmute($pid, $profile->id);
  1963. }
  1964. RelationshipService::refresh($pid, $id);
  1965. $resource = new Fractal\Resource\Item($profile, new RelationshipTransformer);
  1966. $res = $this->fractal->createData($resource)->toArray();
  1967. return $this->json($res);
  1968. }
  1969. /**
  1970. * GET /api/v1/notifications
  1971. *
  1972. *
  1973. * @return NotificationTransformer
  1974. */
  1975. public function accountNotifications(Request $request)
  1976. {
  1977. abort_if(! $request->user() || ! $request->user()->token(), 403);
  1978. abort_unless($request->user()->tokenCan('read'), 403);
  1979. $this->validate($request, [
  1980. 'limit' => 'sometimes|integer|min:1',
  1981. 'min_id' => 'nullable|integer|min:1|max:'.PHP_INT_MAX,
  1982. 'max_id' => 'nullable|integer|min:1|max:'.PHP_INT_MAX,
  1983. 'since_id' => 'nullable|integer|min:1|max:'.PHP_INT_MAX,
  1984. 'types[]' => 'sometimes|array',
  1985. 'types[].*' => 'string|in:mention,reblog,follow,favourite',
  1986. 'type' => 'sometimes|string|in:mention,reblog,follow,favourite',
  1987. '_pe' => 'sometimes',
  1988. ]);
  1989. $pid = $request->user()->profile_id;
  1990. $limit = $request->input('limit', 20);
  1991. $ogLimit = $request->input('limit', 20);
  1992. if ($limit > 40) {
  1993. $limit = 40;
  1994. $ogLimit = 40;
  1995. }
  1996. $since = $request->input('since_id');
  1997. $min = $request->input('min_id');
  1998. $max = $request->input('max_id');
  1999. $pe = $request->filled('_pe');
  2000. if (! $since && ! $min && ! $max) {
  2001. $min = 1;
  2002. }
  2003. if ($since) {
  2004. $min = $since + 1;
  2005. }
  2006. $types = $request->input('types');
  2007. if ($request->has('types')) {
  2008. $limit = 150;
  2009. }
  2010. $maxId = null;
  2011. $minId = null;
  2012. AccountService::setLastActive($request->user()->id);
  2013. $res = $max ?
  2014. NotificationService::getMaxMastodon($pid, $max, $limit) :
  2015. NotificationService::getMinMastodon($pid, $min ?? $since, $limit);
  2016. $ids = $max ?
  2017. NotificationService::getRankedMaxId($pid, $max, $limit) :
  2018. NotificationService::getRankedMinId($pid, $min ?? $since, $limit);
  2019. if (! empty($ids)) {
  2020. $maxId = max($ids);
  2021. $minId = min($ids);
  2022. }
  2023. if (empty($res)) {
  2024. if (! Cache::has('pf:services:notifications:hasSynced:'.$pid)) {
  2025. Cache::put('pf:services:notifications:hasSynced:'.$pid, 1, 1209600);
  2026. NotificationWarmUserCache::dispatch($pid);
  2027. }
  2028. }
  2029. if ($request->has('types')) {
  2030. $typesParams = collect($types)->implode('&types[]=');
  2031. $baseUrl = config('app.url').'/api/v1/notifications?types[]='.$typesParams.'&limit='.$ogLimit.'&';
  2032. } else {
  2033. $baseUrl = config('app.url').'/api/v1/notifications?limit='.$ogLimit.'&';
  2034. }
  2035. if ($minId == $maxId) {
  2036. $minId = null;
  2037. }
  2038. $res = collect($res)
  2039. ->map(function ($n) use ($pe) {
  2040. if (! $pe) {
  2041. if ($n['type'] == 'comment') {
  2042. $n['type'] = 'mention';
  2043. return $n;
  2044. }
  2045. return $n;
  2046. }
  2047. return $n;
  2048. })
  2049. ->filter(function ($n) use ($pe) {
  2050. if (in_array($n['type'], ['mention', 'reblog', 'favourite'])) {
  2051. return isset($n['status'], $n['status']['id']);
  2052. }
  2053. if (! $pe) {
  2054. if (in_array($n['type'], [
  2055. 'tagged',
  2056. 'modlog',
  2057. 'story:react',
  2058. 'story:comment',
  2059. 'group:comment',
  2060. 'group:join:approved',
  2061. 'group:join:rejected',
  2062. ])) {
  2063. return false;
  2064. }
  2065. return isset($n['account'], $n['account']['id']);
  2066. }
  2067. return true;
  2068. })
  2069. ->map(function ($n) use ($pid) {
  2070. if (isset($n['status'])) {
  2071. $n['status']['favourited'] = (bool) LikeService::liked($pid, $n['status']['id']);
  2072. $n['status']['reblogged'] = (bool) ReblogService::get($pid, $n['status']['id']);
  2073. $n['status']['bookmarked'] = (bool) BookmarkService::get($pid, $n['status']['id']);
  2074. }
  2075. return $n;
  2076. })
  2077. ->filter(function ($n) use ($types) {
  2078. if (! $types) {
  2079. return true;
  2080. }
  2081. return in_array($n['type'], $types);
  2082. })
  2083. ->take($ogLimit)
  2084. ->values();
  2085. if ($maxId) {
  2086. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next"';
  2087. }
  2088. if ($minId) {
  2089. $link = '<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  2090. }
  2091. if ($maxId && $minId) {
  2092. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next",<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  2093. }
  2094. $headers = isset($link) ? ['Link' => $link] : [];
  2095. return $this->json($res, 200, $headers);
  2096. }
  2097. /**
  2098. * GET /api/v1/timelines/home
  2099. *
  2100. *
  2101. * @return StatusTransformer
  2102. */
  2103. public function timelineHome(Request $request)
  2104. {
  2105. abort_if(! $request->user() || ! $request->user()->token(), 403);
  2106. abort_unless($request->user()->tokenCan('read'), 403);
  2107. $this->validate($request, [
  2108. 'page' => 'sometimes|integer|max:40',
  2109. 'min_id' => 'sometimes|integer|min:0|max:'.PHP_INT_MAX,
  2110. 'max_id' => 'sometimes|integer|min:0|max:'.PHP_INT_MAX,
  2111. 'limit' => 'sometimes|integer|min:1',
  2112. 'include_reblogs' => 'sometimes',
  2113. ]);
  2114. $napi = $request->has(self::PF_API_ENTITY_KEY);
  2115. $page = $request->input('page');
  2116. $min = $request->input('min_id');
  2117. $max = $request->input('max_id');
  2118. $limit = $request->input('limit') ?? 20;
  2119. if ($limit > 40) {
  2120. $limit = 40;
  2121. }
  2122. $pid = $request->user()->profile_id;
  2123. $includeReblogs = $request->filled('include_reblogs') ? $request->boolean('include_reblogs') : false;
  2124. $nullFields = $includeReblogs ?
  2125. ['in_reply_to_id'] :
  2126. ['in_reply_to_id', 'reblog_of_id'];
  2127. $inTypes = $includeReblogs ?
  2128. ['photo', 'photo:album', 'video', 'video:album', 'photo:video:album', 'share'] :
  2129. ['photo', 'photo:album', 'video', 'video:album', 'photo:video:album'];
  2130. AccountService::setLastActive($request->user()->id);
  2131. $cachedFilters = CustomFilter::getCachedFiltersForAccount($pid);
  2132. $homeFilters = array_filter($cachedFilters, function ($item) {
  2133. [$filter, $rules] = $item;
  2134. return in_array('home', $filter->context);
  2135. });
  2136. if (config('exp.cached_home_timeline')) {
  2137. $paddedLimit = $includeReblogs ? $limit + 10 : $limit + 50;
  2138. if ($min || $max) {
  2139. if ($request->has('min_id')) {
  2140. $res = HomeTimelineService::getRankedMinId($pid, $min ?? 0, $paddedLimit);
  2141. } else {
  2142. $res = HomeTimelineService::getRankedMaxId($pid, $max ?? 0, $paddedLimit);
  2143. }
  2144. } else {
  2145. $res = HomeTimelineService::get($pid, 0, $paddedLimit);
  2146. }
  2147. if (! $res) {
  2148. $res = Cache::has('pf:services:apiv1:home:cached:coldbootcheck:'.$pid);
  2149. if (! $res) {
  2150. Cache::set('pf:services:apiv1:home:cached:coldbootcheck:'.$pid, 1, 86400);
  2151. FeedWarmCachePipeline::dispatchSync($pid);
  2152. return response()->json([], 206);
  2153. } else {
  2154. Cache::set('pf:services:apiv1:home:cached:coldbootcheck:'.$pid, 1, 86400);
  2155. return response()->json([], 206);
  2156. }
  2157. }
  2158. $res = collect($res)
  2159. ->map(function ($id) use ($napi) {
  2160. return $napi ? StatusService::get($id, false) : StatusService::getMastodon($id, false);
  2161. })
  2162. ->filter(function ($res) {
  2163. return $res && isset($res['account']);
  2164. })
  2165. ->filter(function ($s) use ($includeReblogs) {
  2166. return $includeReblogs ? true : $s['reblog'] == null;
  2167. })
  2168. ->map(function ($status) use ($homeFilters) {
  2169. $filterResults = CustomFilter::applyCachedFilters($homeFilters, $status);
  2170. if (! empty($filterResults)) {
  2171. $status['filtered'] = $filterResults;
  2172. $shouldHide = collect($filterResults)->contains(function ($result) {
  2173. return $result['filter']['filter_action'] === 'hide';
  2174. });
  2175. if ($shouldHide) {
  2176. return null;
  2177. }
  2178. }
  2179. return $status;
  2180. })
  2181. ->filter()
  2182. ->take($limit)
  2183. ->map(function ($status) use ($pid) {
  2184. if ($pid) {
  2185. $status['favourited'] = (bool) LikeService::liked($pid, $status['id']);
  2186. $status['reblogged'] = (bool) ReblogService::get($pid, $status['id']);
  2187. $status['bookmarked'] = (bool) BookmarkService::get($pid, $status['id']);
  2188. }
  2189. return $status;
  2190. })
  2191. ->values();
  2192. $baseUrl = config('app.url').'/api/v1/timelines/home?limit='.$limit.'&';
  2193. $minId = $res->map(function ($s) {
  2194. return ['id' => $s['id']];
  2195. })->min('id');
  2196. $maxId = $res->map(function ($s) {
  2197. return ['id' => $s['id']];
  2198. })->max('id');
  2199. if ($minId == $maxId) {
  2200. $minId = null;
  2201. }
  2202. if ($maxId && $res->count() >= $limit) {
  2203. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next"';
  2204. }
  2205. if ($minId) {
  2206. $link = '<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  2207. }
  2208. if ($maxId && $minId) {
  2209. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next",<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  2210. }
  2211. $headers = isset($link) ? ['Link' => $link] : [];
  2212. return $this->json($res->toArray(), 200, $headers);
  2213. }
  2214. $following = Cache::remember('profile:following:'.$pid, 1209600, function () use ($pid) {
  2215. $following = Follower::whereProfileId($pid)->pluck('following_id');
  2216. return $following->push($pid)->toArray();
  2217. });
  2218. $muted = UserFilterService::mutes($pid);
  2219. if ($muted && count($muted)) {
  2220. $following = array_diff($following, $muted);
  2221. }
  2222. if ($min || $max) {
  2223. $dir = $min ? '>' : '<';
  2224. $id = $min ?? $max;
  2225. $res = Status::select(
  2226. 'id',
  2227. 'profile_id',
  2228. 'type',
  2229. 'visibility',
  2230. 'in_reply_to_id',
  2231. 'reblog_of_id'
  2232. )
  2233. ->where('id', $dir, $id)
  2234. ->whereNull($nullFields)
  2235. ->whereIntegerInRaw('profile_id', $following)
  2236. ->whereIn('type', $inTypes)
  2237. ->whereIn('visibility', ['public', 'unlisted', 'private'])
  2238. ->orderByDesc('id')
  2239. ->take(($limit * 2))
  2240. ->get()
  2241. ->map(function ($s) use ($pid, $napi) {
  2242. try {
  2243. $account = $napi ? AccountService::get($s['profile_id'], true) : AccountService::getMastodon($s['profile_id'], true);
  2244. if (! $account) {
  2245. return false;
  2246. }
  2247. $status = $napi ? StatusService::get($s['id'], false) : StatusService::getMastodon($s['id'], false);
  2248. if (! $status || ! isset($status['account']) || ! isset($status['account']['id'])) {
  2249. return false;
  2250. }
  2251. } catch (\Exception $e) {
  2252. return false;
  2253. }
  2254. $status['account'] = $account;
  2255. if ($pid) {
  2256. $status['favourited'] = (bool) LikeService::liked($pid, $s['id']);
  2257. $status['reblogged'] = (bool) ReblogService::get($pid, $status['id']);
  2258. $status['bookmarked'] = (bool) BookmarkService::get($pid, $status['id']);
  2259. }
  2260. return $status;
  2261. })
  2262. ->filter(function ($status) {
  2263. return $status && isset($status['account']);
  2264. })
  2265. ->map(function ($status) use ($pid) {
  2266. if (! empty($status['reblog'])) {
  2267. $status['reblog']['favourited'] = (bool) LikeService::liked($pid, $status['reblog']['id']);
  2268. $status['reblog']['reblogged'] = (bool) ReblogService::get($pid, $status['reblog']['id']);
  2269. $status['bookmarked'] = (bool) BookmarkService::get($pid, $status['id']);
  2270. }
  2271. return $status;
  2272. })
  2273. ->map(function ($status) use ($homeFilters) {
  2274. $filterResults = CustomFilter::applyCachedFilters($homeFilters, $status);
  2275. if (! empty($filterResults)) {
  2276. $status['filtered'] = $filterResults;
  2277. $shouldHide = collect($filterResults)->contains(function ($result) {
  2278. return $result['filter']['filter_action'] === 'hide';
  2279. });
  2280. if ($shouldHide) {
  2281. return null;
  2282. }
  2283. }
  2284. return $status;
  2285. })
  2286. ->filter()
  2287. ->take($limit)
  2288. ->values();
  2289. } else {
  2290. $res = Status::select(
  2291. 'id',
  2292. 'profile_id',
  2293. 'type',
  2294. 'visibility',
  2295. 'in_reply_to_id',
  2296. 'reblog_of_id',
  2297. )
  2298. ->whereNull($nullFields)
  2299. ->whereIntegerInRaw('profile_id', $following)
  2300. ->whereIn('type', $inTypes)
  2301. ->whereIn('visibility', ['public', 'unlisted', 'private'])
  2302. ->orderByDesc('id')
  2303. ->take(($limit * 2))
  2304. ->get()
  2305. ->map(function ($s) use ($pid, $napi) {
  2306. try {
  2307. $account = $napi ? AccountService::get($s['profile_id'], true) : AccountService::getMastodon($s['profile_id'], true);
  2308. if (! $account) {
  2309. return false;
  2310. }
  2311. $status = $napi ? StatusService::get($s['id'], false) : StatusService::getMastodon($s['id'], false);
  2312. if (! $status || ! isset($status['account']) || ! isset($status['account']['id'])) {
  2313. return false;
  2314. }
  2315. } catch (\Exception $e) {
  2316. return false;
  2317. }
  2318. $status['account'] = $account;
  2319. if ($pid) {
  2320. $status['favourited'] = (bool) LikeService::liked($pid, $s['id']);
  2321. $status['reblogged'] = (bool) ReblogService::get($pid, $status['id']);
  2322. $status['bookmarked'] = (bool) BookmarkService::get($pid, $status['id']);
  2323. }
  2324. return $status;
  2325. })
  2326. ->filter(function ($status) {
  2327. return $status && isset($status['account']);
  2328. })
  2329. ->map(function ($status) use ($pid) {
  2330. if (! empty($status['reblog'])) {
  2331. $status['reblog']['favourited'] = (bool) LikeService::liked($pid, $status['reblog']['id']);
  2332. $status['reblog']['reblogged'] = (bool) ReblogService::get($pid, $status['reblog']['id']);
  2333. $status['bookmarked'] = (bool) BookmarkService::get($pid, $status['id']);
  2334. }
  2335. return $status;
  2336. })
  2337. ->map(function ($status) use ($homeFilters) {
  2338. $filterResults = CustomFilter::applyCachedFilters($homeFilters, $status);
  2339. if (! empty($filterResults)) {
  2340. $status['filtered'] = $filterResults;
  2341. $shouldHide = collect($filterResults)->contains(function ($result) {
  2342. return $result['filter']['filter_action'] === 'hide';
  2343. });
  2344. if ($shouldHide) {
  2345. return null;
  2346. }
  2347. }
  2348. return $status;
  2349. })
  2350. ->filter()
  2351. ->take($limit)
  2352. ->values();
  2353. }
  2354. $baseUrl = config('app.url').'/api/v1/timelines/home?limit='.$limit.'&';
  2355. $minId = $res->map(function ($s) {
  2356. return ['id' => $s['id']];
  2357. })->min('id');
  2358. $maxId = $res->map(function ($s) {
  2359. return ['id' => $s['id']];
  2360. })->max('id');
  2361. if ($minId == $maxId) {
  2362. $minId = null;
  2363. }
  2364. if ($maxId) {
  2365. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next"';
  2366. }
  2367. if ($minId) {
  2368. $link = '<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  2369. }
  2370. if ($maxId && $minId) {
  2371. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next",<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  2372. }
  2373. $headers = isset($link) ? ['Link' => $link] : [];
  2374. return $this->json($res->toArray(), 200, $headers);
  2375. }
  2376. /**
  2377. * GET /api/v1/timelines/public
  2378. *
  2379. *
  2380. * @return StatusTransformer
  2381. */
  2382. public function timelinePublic(Request $request)
  2383. {
  2384. $this->validate($request, [
  2385. 'min_id' => 'nullable|integer|min:0|max:'.PHP_INT_MAX,
  2386. 'max_id' => 'nullable|integer|min:0|max:'.PHP_INT_MAX,
  2387. 'limit' => 'sometimes|integer|min:1',
  2388. 'remote' => 'sometimes',
  2389. 'local' => 'sometimes',
  2390. ]);
  2391. $napi = $request->has(self::PF_API_ENTITY_KEY);
  2392. $min = $request->input('min_id');
  2393. $max = $request->input('max_id');
  2394. if ($max == 0) {
  2395. $min = 1;
  2396. }
  2397. $minOrMax = $request->anyFilled(['max_id', 'min_id']);
  2398. $limit = $request->input('limit') ?? 20;
  2399. if ($limit > 40) {
  2400. $limit = 40;
  2401. }
  2402. $user = $request->user();
  2403. $pid = $user->profile_id;
  2404. $remote = $request->has('remote') && $request->boolean('remote');
  2405. $local = $request->boolean('local');
  2406. $userRoleKey = $remote ? 'can-view-network-feed' : 'can-view-public-feed';
  2407. if ($user->has_roles && ! UserRoleService::can($userRoleKey, $user->id)) {
  2408. return [];
  2409. }
  2410. $filtered = $user ? UserFilterService::filters($user->profile_id) : [];
  2411. AccountService::setLastActive($user->id);
  2412. $domainBlocks = UserFilterService::domainBlocks($user->profile_id);
  2413. $hideNsfw = config('instance.hide_nsfw_on_public_feeds');
  2414. $amin = SnowflakeService::byDate(now()->subDays(config('federation.network_timeline_days_falloff')));
  2415. $asf = AdminShadowFilterService::getHideFromPublicFeedsList();
  2416. $cachedFilters = CustomFilter::getCachedFiltersForAccount($pid);
  2417. $homeFilters = array_filter($cachedFilters, function ($item) {
  2418. [$filter, $rules] = $item;
  2419. return in_array('public', $filter->context);
  2420. });
  2421. if ($local && $remote) {
  2422. $feed = Status::select(
  2423. 'id',
  2424. 'uri',
  2425. 'type',
  2426. 'scope',
  2427. 'created_at',
  2428. 'profile_id',
  2429. 'in_reply_to_id',
  2430. 'reblog_of_id'
  2431. )
  2432. ->when($minOrMax, function ($q, $minOrMax) use ($min, $max) {
  2433. $dir = $min ? '>' : '<';
  2434. $id = $min ?? $max;
  2435. return $q->where('id', $dir, $id);
  2436. })
  2437. ->whereNull(['in_reply_to_id', 'reblog_of_id'])
  2438. ->when($hideNsfw, function ($q, $hideNsfw) {
  2439. return $q->where('is_nsfw', false);
  2440. })
  2441. ->whereIn('type', ['photo', 'photo:album', 'video', 'video:album', 'photo:video:album'])
  2442. ->whereScope('public')
  2443. ->where('id', '>', $amin)
  2444. ->orderByDesc('id')
  2445. ->limit(($limit * 2))
  2446. ->pluck('id')
  2447. ->values()
  2448. ->toArray();
  2449. } elseif ($remote && ! $local) {
  2450. if (config('instance.timeline.network.cached')) {
  2451. Cache::remember('api:v1:timelines:network:cache_check', 10368000, function () {
  2452. if (NetworkTimelineService::count() == 0) {
  2453. NetworkTimelineService::warmCache(true, config('instance.timeline.network.cache_dropoff'));
  2454. }
  2455. });
  2456. if ($max) {
  2457. $feed = NetworkTimelineService::getRankedMaxId($max, $limit + 5);
  2458. } elseif ($min) {
  2459. $feed = NetworkTimelineService::getRankedMinId($min, $limit + 5);
  2460. } else {
  2461. $feed = NetworkTimelineService::get(0, $limit + 5);
  2462. }
  2463. } else {
  2464. $feed = Status::select(
  2465. 'id',
  2466. 'uri',
  2467. 'type',
  2468. 'scope',
  2469. 'local',
  2470. 'created_at',
  2471. 'profile_id',
  2472. 'in_reply_to_id',
  2473. 'reblog_of_id'
  2474. )
  2475. ->when($minOrMax, function ($q, $minOrMax) use ($min, $max) {
  2476. $dir = $min ? '>' : '<';
  2477. $id = $min ?? $max;
  2478. return $q->where('id', $dir, $id);
  2479. })
  2480. ->whereNull(['in_reply_to_id', 'reblog_of_id'])
  2481. ->when($hideNsfw, function ($q, $hideNsfw) {
  2482. return $q->where('is_nsfw', false);
  2483. })
  2484. ->whereIn('type', ['photo', 'photo:album', 'video', 'video:album', 'photo:video:album'])
  2485. ->whereLocal(false)
  2486. ->whereScope('public')
  2487. ->where('id', '>', $amin)
  2488. ->orderByDesc('id')
  2489. ->limit(($limit * 2))
  2490. ->pluck('id')
  2491. ->values()
  2492. ->toArray();
  2493. }
  2494. } else {
  2495. if (config('instance.timeline.local.cached')) {
  2496. Cache::remember('api:v1:timelines:public:cache_check', 10368000, function () {
  2497. if (PublicTimelineService::count() == 0) {
  2498. PublicTimelineService::warmCache(true, 400);
  2499. }
  2500. });
  2501. if ($max) {
  2502. $feed = PublicTimelineService::getRankedMaxId($max, $limit + 5);
  2503. } elseif ($min) {
  2504. $feed = PublicTimelineService::getRankedMinId($min, $limit + 5);
  2505. } else {
  2506. $feed = PublicTimelineService::get(0, $limit + 5);
  2507. }
  2508. } else {
  2509. $feed = Status::select(
  2510. 'id',
  2511. 'uri',
  2512. 'type',
  2513. 'scope',
  2514. 'local',
  2515. 'created_at',
  2516. 'profile_id',
  2517. 'in_reply_to_id',
  2518. 'reblog_of_id'
  2519. )
  2520. ->when($minOrMax, function ($q, $minOrMax) use ($min, $max) {
  2521. $dir = $min ? '>' : '<';
  2522. $id = $min ?? $max;
  2523. return $q->where('id', $dir, $id);
  2524. })
  2525. ->whereNull(['in_reply_to_id', 'reblog_of_id'])
  2526. ->when($hideNsfw, function ($q, $hideNsfw) {
  2527. return $q->where('is_nsfw', false);
  2528. })
  2529. ->whereIn('type', ['photo', 'photo:album', 'video', 'video:album', 'photo:video:album'])
  2530. ->whereLocal(true)
  2531. ->whereScope('public')
  2532. ->where('id', '>', $amin)
  2533. ->orderByDesc('id')
  2534. ->limit(($limit * 2))
  2535. ->pluck('id')
  2536. ->values()
  2537. ->toArray();
  2538. }
  2539. }
  2540. $res = collect($feed)
  2541. ->filter(function ($k) use ($min, $max) {
  2542. if (! $min && ! $max) {
  2543. return true;
  2544. }
  2545. if ($min) {
  2546. return $min != $k;
  2547. }
  2548. if ($max) {
  2549. return $max != $k;
  2550. }
  2551. })
  2552. ->map(function ($k) use ($user, $napi) {
  2553. try {
  2554. $status = $napi ? StatusService::get($k) : StatusService::getMastodon($k);
  2555. if (! $status || ! isset($status['account']) || ! isset($status['account']['id'])) {
  2556. return false;
  2557. }
  2558. } catch (\Exception $e) {
  2559. return false;
  2560. }
  2561. $account = $napi ? AccountService::get($status['account']['id'], true) : AccountService::getMastodon($status['account']['id'], true);
  2562. if (! $account) {
  2563. return false;
  2564. }
  2565. $status['account'] = $account;
  2566. if ($user) {
  2567. $status['favourited'] = (bool) LikeService::liked($user->profile_id, $k);
  2568. $status['reblogged'] = (bool) ReblogService::get($user->profile_id, $status['id']);
  2569. $status['bookmarked'] = (bool) BookmarkService::get($user->profile_id, $status['id']);
  2570. }
  2571. return $status;
  2572. })
  2573. ->filter(function ($s) use ($filtered) {
  2574. return $s && isset($s['account']) && in_array($s['account']['id'], $filtered) == false;
  2575. })
  2576. ->filter(function ($s) use ($domainBlocks) {
  2577. if (! $domainBlocks || ! count($domainBlocks)) {
  2578. return $s;
  2579. }
  2580. $domain = strtolower(parse_url($s['url'], PHP_URL_HOST));
  2581. return ! in_array($domain, $domainBlocks);
  2582. })
  2583. ->filter(function ($s) use ($asf, $user) {
  2584. if (! $asf || count($asf) === 0) {
  2585. return true;
  2586. }
  2587. if (in_array($s['account']['id'], $asf)) {
  2588. if ($user->profile_id == $s['account']['id']) {
  2589. return true;
  2590. }
  2591. return false;
  2592. }
  2593. return true;
  2594. })
  2595. ->map(function ($status) use ($homeFilters) {
  2596. $filterResults = CustomFilter::applyCachedFilters($homeFilters, $status);
  2597. if (! empty($filterResults)) {
  2598. $status['filtered'] = $filterResults;
  2599. $shouldHide = collect($filterResults)->contains(function ($result) {
  2600. return $result['filter']['filter_action'] === 'hide';
  2601. });
  2602. if ($shouldHide) {
  2603. return null;
  2604. }
  2605. }
  2606. return $status;
  2607. })
  2608. ->filter()
  2609. ->take($limit)
  2610. ->values();
  2611. $baseUrl = config('app.url').'/api/v1/timelines/public?limit='.$limit.'&';
  2612. if ($remote) {
  2613. $baseUrl .= 'remote=1&';
  2614. }
  2615. if ($local) {
  2616. $baseUrl .= 'local=1&';
  2617. }
  2618. $minId = $res->map(function ($s) {
  2619. return ['id' => $s['id']];
  2620. })->min('id');
  2621. $maxId = $res->map(function ($s) {
  2622. return ['id' => $s['id']];
  2623. })->max('id');
  2624. if ($minId == $maxId) {
  2625. $minId = null;
  2626. }
  2627. if ($maxId && $res->count() >= $limit) {
  2628. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next"';
  2629. }
  2630. if ($minId) {
  2631. $link = '<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  2632. }
  2633. if ($maxId && $minId) {
  2634. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next",<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  2635. }
  2636. $headers = isset($link) ? ['Link' => $link] : [];
  2637. return $this->json($res->toArray(), 200, $headers);
  2638. }
  2639. /**
  2640. * GET /api/v1/conversations
  2641. *
  2642. * Not implemented
  2643. *
  2644. * @return array
  2645. */
  2646. public function conversations(Request $request)
  2647. {
  2648. abort_if(! $request->user() || ! $request->user()->token(), 403);
  2649. abort_unless($request->user()->tokenCan('read'), 403);
  2650. $this->validate($request, [
  2651. 'limit' => 'sometimes|integer|min:1|max:40',
  2652. 'scope' => 'nullable|in:inbox,sent,requests',
  2653. 'min_id' => 'nullable|integer',
  2654. 'max_id' => 'nullable|integer',
  2655. 'since_id' => 'nullable|integer',
  2656. ]);
  2657. $limit = $request->input('limit', 20);
  2658. if ($limit > 20) {
  2659. $limit = 20;
  2660. }
  2661. $scope = $request->input('scope', 'inbox');
  2662. $user = $request->user();
  2663. $min_id = $request->input('min_id');
  2664. $max_id = $request->input('max_id');
  2665. $since_id = $request->input('since_id');
  2666. if ($user->has_roles && ! UserRoleService::can('can-direct-message', $user->id)) {
  2667. return [];
  2668. }
  2669. $pid = $user->profile_id;
  2670. $isPgsql = config('database.default') == 'pgsql';
  2671. if ($isPgsql) {
  2672. $dms = DirectMessage::when($scope === 'inbox', function ($q) use ($pid) {
  2673. return $q->whereIsHidden(false)
  2674. ->where(function ($query) use ($pid) {
  2675. $query->where('to_id', $pid)
  2676. ->orWhere('from_id', $pid);
  2677. });
  2678. })
  2679. ->when($scope === 'sent', function ($q) use ($pid) {
  2680. return $q->whereFromId($pid)
  2681. ->groupBy(['to_id', 'id']);
  2682. })
  2683. ->when($scope === 'requests', function ($q) use ($pid) {
  2684. return $q->whereToId($pid)
  2685. ->whereIsHidden(true);
  2686. });
  2687. } else {
  2688. $dms = Conversation::when($scope === 'inbox', function ($q) use ($pid) {
  2689. return $q->whereIsHidden(false)
  2690. ->where(function ($query) use ($pid) {
  2691. $query->where('to_id', $pid)
  2692. ->orWhere('from_id', $pid);
  2693. })
  2694. ->orderByDesc('status_id')
  2695. ->groupBy(['to_id', 'from_id']);
  2696. })
  2697. ->when($scope === 'sent', function ($q) use ($pid) {
  2698. return $q->whereFromId($pid)
  2699. ->groupBy('to_id');
  2700. })
  2701. ->when($scope === 'requests', function ($q) use ($pid) {
  2702. return $q->whereToId($pid)
  2703. ->whereIsHidden(true);
  2704. });
  2705. }
  2706. if ($min_id) {
  2707. $dms = $dms->where('id', '>', $min_id);
  2708. }
  2709. if ($max_id) {
  2710. $dms = $dms->where('id', '<', $max_id);
  2711. }
  2712. if ($since_id) {
  2713. $dms = $dms->where('id', '>', $since_id);
  2714. }
  2715. $dms = $dms->orderByDesc('status_id')->orderBy('id');
  2716. $dmResults = $dms->limit($limit + 1)->get();
  2717. $hasNextPage = $dmResults->count() > $limit;
  2718. if ($hasNextPage) {
  2719. $dmResults = $dmResults->take($limit);
  2720. }
  2721. $transformedDms = $dmResults->map(function ($dm) use ($pid) {
  2722. $from = $pid == $dm->to_id ? $dm->from_id : $dm->to_id;
  2723. return [
  2724. 'id' => $dm->id,
  2725. 'unread' => false,
  2726. 'accounts' => [
  2727. AccountService::getMastodon($from, true),
  2728. ],
  2729. 'last_status' => StatusService::getDirectMessage($dm->status_id),
  2730. ];
  2731. })
  2732. ->filter(function ($dm) {
  2733. return $dm
  2734. && ! empty($dm['last_status'])
  2735. && isset($dm['accounts'])
  2736. && count($dm['accounts'])
  2737. && isset($dm['accounts'][0])
  2738. && isset($dm['accounts'][0]['id']);
  2739. })
  2740. ->unique(function ($item) {
  2741. return $item['accounts'][0]['id'];
  2742. })
  2743. ->values();
  2744. $links = [];
  2745. if (! $transformedDms->isEmpty()) {
  2746. $baseUrl = url()->current().'?'.http_build_query(array_merge(
  2747. $request->except(['min_id', 'max_id', 'since_id']),
  2748. ['limit' => $limit]
  2749. ));
  2750. $firstId = $transformedDms->first()['id'];
  2751. $lastId = $transformedDms->last()['id'];
  2752. $firstLink = $baseUrl;
  2753. $links[] = '<'.$firstLink.'>; rel="first"';
  2754. if ($hasNextPage) {
  2755. $nextLink = $baseUrl.'&max_id='.$lastId;
  2756. $links[] = '<'.$nextLink.'>; rel="next"';
  2757. }
  2758. if ($max_id || $since_id) {
  2759. $prevLink = $baseUrl.'&min_id='.$firstId;
  2760. $links[] = '<'.$prevLink.'>; rel="prev"';
  2761. }
  2762. }
  2763. if (! empty($links)) {
  2764. return response()->json($transformedDms->toArray())
  2765. ->header('Link', implode(', ', $links));
  2766. }
  2767. return $this->json($transformedDms);
  2768. }
  2769. /**
  2770. * GET /api/v1/statuses/{id}
  2771. *
  2772. * @param int $id
  2773. * @return StatusTransformer
  2774. */
  2775. public function statusById(Request $request, $id)
  2776. {
  2777. abort_if(! $request->user() || ! $request->user()->token(), 403);
  2778. abort_unless($request->user()->tokenCan('read'), 403);
  2779. AccountService::setLastActive($request->user()->id);
  2780. $pid = $request->user()->profile_id;
  2781. $res = $request->has(self::PF_API_ENTITY_KEY) ? StatusService::get($id, false) : StatusService::getMastodon($id, false);
  2782. if (! $res || ! isset($res['visibility'])) {
  2783. abort(404);
  2784. }
  2785. if ($res && isset($res['account'], $res['account']['acct'], $res['account']['url']) && strpos($res['account']['acct'], '@') != -1) {
  2786. $domain = parse_url($res['account']['url'], PHP_URL_HOST);
  2787. abort_if(in_array($domain, InstanceService::getBannedDomains()), 404);
  2788. }
  2789. $scope = $res['visibility'];
  2790. if (! in_array($scope, ['public', 'unlisted'])) {
  2791. if ($scope === 'private') {
  2792. if (intval($res['account']['id']) !== intval($pid)) {
  2793. abort_unless(FollowerService::follows($pid, $res['account']['id']), 403);
  2794. }
  2795. } else {
  2796. abort(400, 'Invalid request');
  2797. }
  2798. }
  2799. if (! empty($res['reblog']) && isset($res['reblog']['id'])) {
  2800. $res['reblog']['favourited'] = (bool) LikeService::liked($pid, $res['reblog']['id']);
  2801. $res['reblog']['reblogged'] = (bool) ReblogService::get($pid, $res['reblog']['id']);
  2802. $res['reblog']['bookmarked'] = BookmarkService::get($pid, $res['reblog']['id']);
  2803. }
  2804. $res['favourited'] = LikeService::liked($pid, $res['id']);
  2805. $res['reblogged'] = ReblogService::get($pid, $res['id']);
  2806. $res['bookmarked'] = BookmarkService::get($pid, $res['id']);
  2807. return $this->json($res);
  2808. }
  2809. /**
  2810. * GET /api/v1/statuses/{id}/context
  2811. *
  2812. * @param int $id
  2813. * @return StatusTransformer
  2814. */
  2815. public function statusContext(Request $request, $id)
  2816. {
  2817. abort_if(! $request->user() || ! $request->user()->token(), 403);
  2818. abort_unless($request->user()->tokenCan('read'), 403);
  2819. $user = $request->user();
  2820. $pid = $user->profile_id;
  2821. $status = StatusService::getMastodon($id, false);
  2822. $pe = $request->has(self::PF_API_ENTITY_KEY);
  2823. if (! $status || ! isset($status['account'])) {
  2824. return response('', 404);
  2825. }
  2826. if ($status && isset($status['account'], $status['account']['acct']) && strpos($status['account']['acct'], '@') != -1) {
  2827. $domain = parse_url($status['account']['url'], PHP_URL_HOST);
  2828. abort_if(in_array($domain, InstanceService::getBannedDomains()), 404);
  2829. }
  2830. if (intval($status['account']['id']) !== intval($user->profile_id)) {
  2831. if ($status['visibility'] == 'private') {
  2832. if (! FollowerService::follows($user->profile_id, $status['account']['id'])) {
  2833. return response('', 404);
  2834. }
  2835. } else {
  2836. if (! in_array($status['visibility'], ['public', 'unlisted'])) {
  2837. return response('', 404);
  2838. }
  2839. }
  2840. }
  2841. $ancestors = [];
  2842. $descendants = [];
  2843. if ($status['in_reply_to_id']) {
  2844. $ancestors[] = $pe ?
  2845. StatusService::get($status['in_reply_to_id'], false) :
  2846. StatusService::getMastodon($status['in_reply_to_id'], false);
  2847. }
  2848. if ($status['replies_count']) {
  2849. $filters = UserFilterService::filters($pid);
  2850. $descendants = DB::table('statuses')
  2851. ->where('in_reply_to_id', $id)
  2852. ->limit(20)
  2853. ->pluck('id')
  2854. ->map(function ($sid) use ($pe) {
  2855. return $pe ?
  2856. StatusService::get($sid, false) :
  2857. StatusService::getMastodon($sid, false);
  2858. })
  2859. ->filter(function ($post) use ($filters) {
  2860. return $post && isset($post['account'], $post['account']['id']) && ! in_array($post['account']['id'], $filters);
  2861. })
  2862. ->map(function ($status) use ($pid) {
  2863. $status['favourited'] = LikeService::liked($pid, $status['id']);
  2864. $status['reblogged'] = ReblogService::get($pid, $status['id']);
  2865. return $status;
  2866. })
  2867. ->values();
  2868. }
  2869. $res = [
  2870. 'ancestors' => $ancestors,
  2871. 'descendants' => $descendants,
  2872. ];
  2873. return $this->json($res);
  2874. }
  2875. /**
  2876. * GET /api/v1/statuses/{id}/card
  2877. *
  2878. * @param int $id
  2879. * @return StatusTransformer
  2880. */
  2881. public function statusCard(Request $request, $id)
  2882. {
  2883. abort_if(! $request->user() || ! $request->user()->token(), 403);
  2884. abort_unless($request->user()->tokenCan('read'), 403);
  2885. $res = [];
  2886. return response()->json($res);
  2887. }
  2888. /**
  2889. * GET /api/v1/statuses/{id}/reblogged_by
  2890. *
  2891. * @param int $id
  2892. * @return AccountTransformer
  2893. */
  2894. public function statusRebloggedBy(Request $request, $id)
  2895. {
  2896. abort_if(! $request->user() || ! $request->user()->token(), 403);
  2897. abort_unless($request->user()->tokenCan('read'), 403);
  2898. $this->validate($request, [
  2899. 'limit' => 'sometimes|integer|min:1|max:80',
  2900. ]);
  2901. $limit = $request->input('limit', 10);
  2902. $user = $request->user();
  2903. $pid = $user->profile_id;
  2904. $status = Status::findOrFail($id);
  2905. $account = AccountService::get($status->profile_id, true);
  2906. abort_if(! $account, 404);
  2907. abort_if(isset($account['moved'], $account['moved']['id']), 404, 'Account moved');
  2908. if ($account && strpos($account['acct'], '@') != -1) {
  2909. $domain = parse_url($account['url'], PHP_URL_HOST);
  2910. abort_if(in_array($domain, InstanceService::getBannedDomains()), 404);
  2911. }
  2912. $author = intval($status->profile_id) === intval($pid) || $user->is_admin;
  2913. $napi = $request->has(self::PF_API_ENTITY_KEY);
  2914. abort_if(
  2915. ! $status->type ||
  2916. ! in_array($status->type, ['photo', 'photo:album', 'photo:video:album', 'reply', 'text', 'video', 'video:album']),
  2917. 404,
  2918. );
  2919. if (! $author) {
  2920. if ($status->scope == 'private') {
  2921. abort_if(! FollowerService::follows($pid, $status->profile_id), 403);
  2922. } else {
  2923. abort_if(! in_array($status->scope, ['public', 'unlisted']), 403);
  2924. }
  2925. if ($request->has('cursor')) {
  2926. return $this->json([]);
  2927. }
  2928. }
  2929. $res = Status::where('reblog_of_id', $status->id)
  2930. ->orderByDesc('id')
  2931. ->cursorPaginate($limit)
  2932. ->withQueryString();
  2933. if (! $res) {
  2934. return $this->json([]);
  2935. }
  2936. $headers = [];
  2937. if ($author && $res->hasPages()) {
  2938. $links = '';
  2939. if ($res->onFirstPage()) {
  2940. if ($res->nextPageUrl()) {
  2941. $links = '<'.$res->nextPageUrl().'>; rel="prev"';
  2942. }
  2943. } else {
  2944. if ($res->previousPageUrl()) {
  2945. $links = '<'.$res->previousPageUrl().'>; rel="next"';
  2946. }
  2947. if ($res->nextPageUrl()) {
  2948. if (! empty($links)) {
  2949. $links .= ', ';
  2950. }
  2951. $links .= '<'.$res->nextPageUrl().'>; rel="prev"';
  2952. }
  2953. }
  2954. $headers = ['Link' => $links];
  2955. }
  2956. $res = $res->map(function ($status) use ($pid, $napi) {
  2957. $account = $napi ? AccountService::get($status->profile_id, true) : AccountService::getMastodon($status->profile_id, true);
  2958. if (! $account) {
  2959. return false;
  2960. }
  2961. if ($napi) {
  2962. $account['follows'] = $status->profile_id == $pid ? null : FollowerService::follows($pid, $status->profile_id);
  2963. }
  2964. return $account;
  2965. })
  2966. ->filter(function ($account) {
  2967. return $account && isset($account['id']);
  2968. })
  2969. ->values();
  2970. return $this->json($res, 200, $headers);
  2971. }
  2972. /**
  2973. * GET /api/v1/statuses/{id}/favourited_by
  2974. *
  2975. * @param int $id
  2976. * @return AccountTransformer
  2977. */
  2978. public function statusFavouritedBy(Request $request, $id)
  2979. {
  2980. abort_if(! $request->user() || ! $request->user()->token(), 403);
  2981. abort_unless($request->user()->tokenCan('read'), 403);
  2982. $this->validate($request, [
  2983. 'limit' => 'sometimes|integer|min:1',
  2984. ]);
  2985. $limit = $request->input('limit', 40);
  2986. if ($limit > 80) {
  2987. $limit = 80;
  2988. }
  2989. $user = $request->user();
  2990. $pid = $user->profile_id;
  2991. $status = Status::findOrFail($id);
  2992. $account = AccountService::get($status->profile_id, true);
  2993. abort_if(! $account, 404);
  2994. abort_if(isset($account['moved'], $account['moved']['id']), 404, 'Account moved');
  2995. if ($account && strpos($account['acct'], '@') != -1) {
  2996. $domain = parse_url($account['url'], PHP_URL_HOST);
  2997. abort_if(in_array($domain, InstanceService::getBannedDomains()), 404);
  2998. }
  2999. $author = intval($status->profile_id) === intval($pid) || $user->is_admin;
  3000. $napi = $request->has(self::PF_API_ENTITY_KEY);
  3001. abort_if(
  3002. ! $status->type ||
  3003. ! in_array($status->type, ['photo', 'photo:album', 'photo:video:album', 'reply', 'text', 'video', 'video:album']),
  3004. 404,
  3005. );
  3006. if (! $author) {
  3007. if ($status->scope == 'private') {
  3008. abort_if(! FollowerService::follows($pid, $status->profile_id), 403);
  3009. } else {
  3010. abort_if(! in_array($status->scope, ['public', 'unlisted']), 403);
  3011. }
  3012. if ($request->has('cursor')) {
  3013. return $this->json([]);
  3014. }
  3015. }
  3016. $res = Like::where('status_id', $status->id)
  3017. ->orderByDesc('id')
  3018. ->cursorPaginate($limit)
  3019. ->withQueryString();
  3020. if (! $res) {
  3021. return $this->json([]);
  3022. }
  3023. $headers = [];
  3024. if ($author && $res->hasPages()) {
  3025. $links = '';
  3026. if ($res->onFirstPage()) {
  3027. if ($res->nextPageUrl()) {
  3028. $links = '<'.$res->nextPageUrl().'>; rel="prev"';
  3029. }
  3030. } else {
  3031. if ($res->previousPageUrl()) {
  3032. $links = '<'.$res->previousPageUrl().'>; rel="next"';
  3033. }
  3034. if ($res->nextPageUrl()) {
  3035. if (! empty($links)) {
  3036. $links .= ', ';
  3037. }
  3038. $links .= '<'.$res->nextPageUrl().'>; rel="prev"';
  3039. }
  3040. }
  3041. $headers = ['Link' => $links];
  3042. }
  3043. $res = $res->map(function ($like) use ($pid, $napi) {
  3044. $account = $napi ? AccountService::get($like->profile_id, true) : AccountService::getMastodon($like->profile_id, true);
  3045. if (! $account) {
  3046. return false;
  3047. }
  3048. if ($napi) {
  3049. $account['follows'] = $like->profile_id == $pid ? null : FollowerService::follows($pid, $like->profile_id);
  3050. }
  3051. return $account;
  3052. })
  3053. ->filter(function ($account) {
  3054. return $account && isset($account['id']);
  3055. })
  3056. ->values();
  3057. return $this->json($res, 200, $headers);
  3058. }
  3059. /**
  3060. * POST /api/v1/statuses
  3061. *
  3062. *
  3063. * @return StatusTransformer
  3064. */
  3065. public function statusCreate(Request $request)
  3066. {
  3067. abort_if(! $request->user() || ! $request->user()->token(), 403);
  3068. abort_unless($request->user()->tokenCan('write'), 403);
  3069. $this->validate($request, [
  3070. 'status' => 'nullable|string|max:'.(int) config_cache('pixelfed.max_caption_length'),
  3071. 'in_reply_to_id' => 'nullable',
  3072. 'media_ids' => 'sometimes|array|max:'.(int) config_cache('pixelfed.max_album_length'),
  3073. 'sensitive' => 'nullable',
  3074. 'visibility' => 'string|in:private,unlisted,public,direct',
  3075. 'spoiler_text' => 'sometimes|max:140',
  3076. 'place_id' => 'sometimes|integer|min:1|max:128769',
  3077. 'collection_ids' => 'sometimes|array|max:3',
  3078. 'comments_disabled' => 'sometimes|boolean',
  3079. ]);
  3080. if ($request->filled('visibility') && $request->input('visibility') === 'direct') {
  3081. return $this->json([
  3082. 'error' => 'Direct visibility is not available.',
  3083. ], 400);
  3084. }
  3085. if ($request->hasHeader('idempotency-key')) {
  3086. $key = 'pf:api:v1:status:idempotency-key:'.$request->user()->id.':'.hash('sha1', $request->header('idempotency-key'));
  3087. $exists = Cache::has($key);
  3088. abort_if($exists, 400, 'Duplicate idempotency key.');
  3089. Cache::put($key, 1, 3600);
  3090. }
  3091. if (config('costar.enabled') == true) {
  3092. $blockedKeywords = config('costar.keyword.block');
  3093. if ($blockedKeywords !== null && $request->status) {
  3094. $keywords = config('costar.keyword.block');
  3095. foreach ($keywords as $kw) {
  3096. if (Str::contains($request->status, $kw) == true) {
  3097. abort(400, 'Invalid object. Contains banned keyword.');
  3098. }
  3099. }
  3100. }
  3101. }
  3102. if (! $request->filled('media_ids') && ! $request->filled('in_reply_to_id')) {
  3103. abort(403, 'Empty statuses are not allowed');
  3104. }
  3105. $ids = $request->input('media_ids');
  3106. $in_reply_to_id = $request->input('in_reply_to_id');
  3107. $user = $request->user();
  3108. if ($user->has_roles) {
  3109. if ($in_reply_to_id != null) {
  3110. abort_if(! UserRoleService::can('can-comment', $user->id), 403, 'Invalid permissions for this action');
  3111. } else {
  3112. abort_if(! UserRoleService::can('can-post', $user->id), 403, 'Invalid permissions for this action');
  3113. }
  3114. }
  3115. $profile = $user->profile;
  3116. $limitKey = 'compose:rate-limit:store:'.$user->id;
  3117. $limitTtl = now()->addMinutes(15);
  3118. $limitReached = Cache::remember($limitKey, $limitTtl, function () use ($user) {
  3119. $minId = SnowflakeService::byDate(now()->subDays(1));
  3120. $dailyLimit = Status::whereProfileId($user->profile_id)
  3121. ->where('id', '>', $minId)
  3122. ->count();
  3123. return $dailyLimit >= 1000;
  3124. });
  3125. abort_if($limitReached == true, 429);
  3126. $visibility = $profile->is_private ? 'private' : (
  3127. $profile->unlisted == true &&
  3128. $request->input('visibility', 'public') == 'public' ?
  3129. 'unlisted' :
  3130. $request->input('visibility', 'public'));
  3131. if ($user->last_active_at == null) {
  3132. return [];
  3133. }
  3134. $defaultCaption = '';
  3135. $content = $request->filled('status') ? strip_tags($request->input('status')) : $defaultCaption;
  3136. $cw = $user->profile->cw == true ? true : $request->boolean('sensitive', false);
  3137. $spoilerText = $cw && $request->filled('spoiler_text') ? $request->input('spoiler_text') : null;
  3138. if ($in_reply_to_id) {
  3139. $parent = Status::findOrFail($in_reply_to_id);
  3140. if ($parent->comments_disabled) {
  3141. return $this->json('Comments have been disabled on this post', 422);
  3142. }
  3143. $blocks = UserFilterService::blocks($parent->profile_id);
  3144. abort_if(in_array($profile->id, $blocks), 422, 'Cannot reply to this post at this time.');
  3145. $status = new Status;
  3146. $status->caption = $content;
  3147. $status->rendered = $defaultCaption;
  3148. $status->scope = $visibility;
  3149. $status->visibility = $visibility;
  3150. $status->profile_id = $user->profile_id;
  3151. $status->is_nsfw = $cw;
  3152. $status->cw_summary = $spoilerText;
  3153. $status->in_reply_to_id = $parent->id;
  3154. $status->in_reply_to_profile_id = $parent->profile_id;
  3155. $status->save();
  3156. StatusService::del($parent->id);
  3157. Cache::forget('status:replies:all:'.$parent->id);
  3158. }
  3159. if ($ids) {
  3160. if (Media::whereUserId($user->id)
  3161. ->whereNull('status_id')
  3162. ->find($ids)
  3163. ->count() == 0
  3164. ) {
  3165. abort(400, 'Invalid media_ids');
  3166. }
  3167. if (! $in_reply_to_id) {
  3168. $status = new Status;
  3169. $status->caption = $content;
  3170. $status->rendered = $defaultCaption;
  3171. $status->profile_id = $user->profile_id;
  3172. $status->is_nsfw = $cw;
  3173. $status->cw_summary = $spoilerText;
  3174. $status->scope = 'draft';
  3175. $status->visibility = 'draft';
  3176. if ($request->has('place_id')) {
  3177. $status->place_id = $request->input('place_id');
  3178. }
  3179. $status->save();
  3180. }
  3181. $mimes = [];
  3182. foreach ($ids as $k => $v) {
  3183. if ($k + 1 > (int) config_cache('pixelfed.max_album_length')) {
  3184. continue;
  3185. }
  3186. $m = Media::whereUserId($user->id)->whereNull('status_id')->findOrFail($v);
  3187. if ($m->profile_id !== $user->profile_id || $m->status_id) {
  3188. abort(403, 'Invalid media id');
  3189. }
  3190. $m->order = $k + 1;
  3191. $m->status_id = $status->id;
  3192. $m->save();
  3193. array_push($mimes, $m->mime);
  3194. }
  3195. if (empty($mimes)) {
  3196. $status->delete();
  3197. abort(400, 'Invalid media ids');
  3198. }
  3199. if ($request->has('comments_disabled') && $request->input('comments_disabled')) {
  3200. $status->comments_disabled = true;
  3201. }
  3202. $status->scope = $visibility;
  3203. $status->visibility = $visibility;
  3204. $status->type = StatusController::mimeTypeCheck($mimes);
  3205. $status->save();
  3206. }
  3207. if (! $status) {
  3208. abort(500, 'An error occured.');
  3209. }
  3210. NewStatusPipeline::dispatch($status);
  3211. if ($status->in_reply_to_id) {
  3212. CommentPipeline::dispatch($parent, $status);
  3213. }
  3214. Cache::forget('user:account:id:'.$user->id);
  3215. Cache::forget('_api:statuses:recent_9:'.$user->profile_id);
  3216. Cache::forget('profile:status_count:'.$user->profile_id);
  3217. Cache::forget($user->storageUsedKey());
  3218. Cache::forget('profile:embed:'.$status->profile_id);
  3219. Cache::forget($limitKey);
  3220. if ($request->has('collection_ids') && $ids) {
  3221. $collections = Collection::whereProfileId($user->profile_id)
  3222. ->find($request->input('collection_ids'))
  3223. ->each(function ($collection) use ($status) {
  3224. $count = $collection->items()->count();
  3225. $item = CollectionItem::firstOrCreate([
  3226. 'collection_id' => $collection->id,
  3227. 'object_type' => 'App\Status',
  3228. 'object_id' => $status->id,
  3229. ], [
  3230. 'order' => $count,
  3231. ]);
  3232. CollectionService::addItem(
  3233. $collection->id,
  3234. $status->id,
  3235. $count
  3236. );
  3237. $collection->updated_at = now();
  3238. $collection->save();
  3239. CollectionService::setCollection($collection->id, $collection);
  3240. });
  3241. }
  3242. $res = StatusService::getMastodon($status->id, false);
  3243. $res['favourited'] = false;
  3244. $res['language'] = 'en';
  3245. $res['bookmarked'] = false;
  3246. $res['card'] = null;
  3247. return $this->json($res);
  3248. }
  3249. /**
  3250. * DELETE /api/v1/statuses
  3251. *
  3252. * @param int $id
  3253. * @return null
  3254. */
  3255. public function statusDelete(Request $request, $id)
  3256. {
  3257. abort_if(! $request->user() || ! $request->user()->token(), 403);
  3258. abort_unless($request->user()->tokenCan('write'), 403);
  3259. AccountService::setLastActive($request->user()->id);
  3260. $status = Status::whereProfileId($request->user()->profile->id)
  3261. ->findOrFail($id);
  3262. $resource = new Fractal\Resource\Item($status, new StatusTransformer);
  3263. Cache::forget('profile:status_count:'.$status->profile_id);
  3264. StatusDelete::dispatch($status);
  3265. $res = $this->fractal->createData($resource)->toArray();
  3266. $res['text'] = $res['content'];
  3267. unset($res['content']);
  3268. return $this->json($res);
  3269. }
  3270. /**
  3271. * POST /api/v1/statuses/{id}/reblog
  3272. *
  3273. * @param int $id
  3274. * @return StatusTransformer
  3275. */
  3276. public function statusShare(Request $request, $id)
  3277. {
  3278. abort_if(! $request->user() || ! $request->user()->token(), 403);
  3279. abort_unless($request->user()->tokenCan('write'), 403);
  3280. $user = $request->user();
  3281. abort_if($user->has_roles && ! UserRoleService::can('can-share', $user->id), 403, 'Invalid permissions for this action');
  3282. AccountService::setLastActive($user->id);
  3283. $status = Status::whereScope('public')->findOrFail($id);
  3284. $account = AccountService::get($status->profile_id);
  3285. abort_if(isset($account['moved'], $account['moved']['id']), 422, 'Cannot share a post from an account that has migrated');
  3286. if ($status && ($status->uri || $status->url || $status->object_url)) {
  3287. $url = $status->uri ?? $status->url ?? $status->object_url;
  3288. $domain = parse_url($url, PHP_URL_HOST);
  3289. abort_if(in_array($domain, InstanceService::getBannedDomains()), 404);
  3290. }
  3291. if (intval($status->profile_id) !== intval($user->profile_id)) {
  3292. if ($status->scope == 'private') {
  3293. abort_if(! FollowerService::follows($user->profile_id, $status->profile_id), 403);
  3294. } else {
  3295. abort_if(! in_array($status->scope, ['public', 'unlisted']), 403);
  3296. }
  3297. $blocks = UserFilterService::blocks($status->profile_id);
  3298. if ($blocks && in_array($user->profile_id, $blocks)) {
  3299. abort(422);
  3300. }
  3301. }
  3302. $defaultCaption = config_cache('database.default') === 'mysql' ? null : '';
  3303. $share = Status::firstOrCreate([
  3304. 'caption' => $defaultCaption,
  3305. 'rendered' => $defaultCaption,
  3306. 'profile_id' => $user->profile_id,
  3307. 'reblog_of_id' => $status->id,
  3308. 'type' => 'share',
  3309. 'in_reply_to_profile_id' => $status->profile_id,
  3310. 'scope' => 'public',
  3311. 'visibility' => 'public',
  3312. ]);
  3313. SharePipeline::dispatch($share)->onQueue('low');
  3314. StatusService::del($status->id);
  3315. ReblogService::add($user->profile_id, $status->id);
  3316. $res = StatusService::getMastodon($status->id);
  3317. $res['reblogged'] = true;
  3318. $res['favourited'] = LikeService::liked($user->profile_id, $status->id);
  3319. $res['bookmarked'] = BookmarkService::get($user->profile_id, $status->id);
  3320. return $this->json($res);
  3321. }
  3322. /**
  3323. * POST /api/v1/statuses/{id}/unreblog
  3324. *
  3325. * @param int $id
  3326. * @return StatusTransformer
  3327. */
  3328. public function statusUnshare(Request $request, $id)
  3329. {
  3330. abort_if(! $request->user() || ! $request->user()->token(), 403);
  3331. abort_unless($request->user()->tokenCan('write'), 403);
  3332. $user = $request->user();
  3333. abort_if($user->has_roles && ! UserRoleService::can('can-share', $user->id), 403, 'Invalid permissions for this action');
  3334. AccountService::setLastActive($user->id);
  3335. $status = Status::whereScope('public')->findOrFail($id);
  3336. $account = AccountService::get($status->profile_id);
  3337. abort_if(isset($account['moved'], $account['moved']['id']), 422, 'Cannot unshare a post from an account that has migrated');
  3338. if (intval($status->profile_id) !== intval($user->profile_id)) {
  3339. if ($status->scope == 'private') {
  3340. abort_if(! FollowerService::follows($user->profile_id, $status->profile_id), 403);
  3341. } else {
  3342. abort_if(! in_array($status->scope, ['public', 'unlisted']), 403);
  3343. }
  3344. }
  3345. $reblog = Status::whereProfileId($user->profile_id)
  3346. ->whereReblogOfId($status->id)
  3347. ->first();
  3348. if (! $reblog) {
  3349. $res = StatusService::getMastodon($status->id);
  3350. $res['reblogged'] = false;
  3351. return $this->json($res);
  3352. }
  3353. UndoSharePipeline::dispatch($reblog)->onQueue('low');
  3354. ReblogService::del($user->profile_id, $status->id);
  3355. $res = StatusService::getMastodon($status->id);
  3356. $res['reblogged'] = false;
  3357. $res['favourited'] = LikeService::liked($user->profile_id, $status->id);
  3358. $res['bookmarked'] = BookmarkService::get($user->profile_id, $status->id);
  3359. return $this->json($res);
  3360. }
  3361. /**
  3362. * GET /api/v1/timelines/tag/{hashtag}
  3363. *
  3364. * @param string $hashtag
  3365. * @return StatusTransformer
  3366. */
  3367. public function timelineHashtag(Request $request, $hashtag)
  3368. {
  3369. abort_if(! $request->user() || ! $request->user()->token(), 403);
  3370. abort_unless($request->user()->tokenCan('read'), 403);
  3371. $this->validate($request, [
  3372. 'page' => 'nullable|integer|max:40',
  3373. 'min_id' => 'nullable|integer|min:0|max:'.PHP_INT_MAX,
  3374. 'max_id' => 'nullable|integer|min:0|max:'.PHP_INT_MAX,
  3375. 'limit' => 'sometimes|integer|min:1',
  3376. 'only_media' => 'sometimes',
  3377. '_pe' => 'sometimes',
  3378. ]);
  3379. $user = $request->user();
  3380. abort_if(
  3381. $user->has_roles && ! UserRoleService::can('can-view-hashtag-feed', $user->id),
  3382. 403,
  3383. 'Invalid permissions for this action'
  3384. );
  3385. if (config('database.default') === 'pgsql') {
  3386. $tag = Hashtag::where('name', 'ilike', $hashtag)
  3387. ->orWhere('slug', 'ilike', $hashtag)
  3388. ->first();
  3389. } else {
  3390. $tag = Hashtag::whereName($hashtag)
  3391. ->orWhere('slug', $hashtag)
  3392. ->first();
  3393. }
  3394. if (! $tag) {
  3395. return response()->json([]);
  3396. }
  3397. if ($tag->is_banned == true) {
  3398. return $this->json([]);
  3399. }
  3400. $min = $request->input('min_id');
  3401. $max = $request->input('max_id');
  3402. $limit = $request->input('limit', 20);
  3403. if ($limit > 40) {
  3404. $limit = 40;
  3405. }
  3406. $onlyMedia = $request->boolean('only_media', true);
  3407. $pe = $request->has(self::PF_API_ENTITY_KEY);
  3408. $pid = $request->user()->profile_id;
  3409. $cachedFilters = CustomFilter::getCachedFiltersForAccount($pid);
  3410. $tagFilters = array_filter($cachedFilters, function ($item) {
  3411. [$filter, $rules] = $item;
  3412. return in_array('tags', $filter->context);
  3413. });
  3414. if ($min || $max) {
  3415. $minMax = SnowflakeService::byDate(now()->subMonths(9));
  3416. if ($min && intval($min) < $minMax) {
  3417. return [];
  3418. }
  3419. if ($max && intval($max) < $minMax) {
  3420. return [];
  3421. }
  3422. }
  3423. $filters = UserFilterService::filters($pid);
  3424. $domainBlocks = UserFilterService::domainBlocks($pid);
  3425. if (! $min && ! $max) {
  3426. $id = 1;
  3427. $dir = '>';
  3428. } else {
  3429. $dir = $min ? '>' : '<';
  3430. $id = $min ?? $max;
  3431. }
  3432. $res = StatusHashtag::whereHashtagId($tag->id)
  3433. ->where('status_id', $dir, $id)
  3434. ->orderBy('status_id', 'desc')
  3435. ->limit(100)
  3436. ->pluck('status_id')
  3437. ->map(function ($i) use ($pe) {
  3438. return $pe ? StatusService::get($i, false) : StatusService::getMastodon($i, false);
  3439. })
  3440. ->filter(function ($i) use ($onlyMedia, $pid) {
  3441. if (! $i || ! isset($i['account'], $i['account']['id'])) {
  3442. return false;
  3443. }
  3444. if ($i['visibility'] === 'unlisted') {
  3445. if ((int) $i['account']['id'] !== $pid) {
  3446. return false;
  3447. }
  3448. }
  3449. // if ($i['visibility'] === 'private') {
  3450. // if ((int) $i['account']['id'] !== $pid) {
  3451. // return FollowerService::follows($pid, $i['account']['id'], true);
  3452. // }
  3453. // }
  3454. if ($onlyMedia == true) {
  3455. if (! isset($i['media_attachments']) || ! count($i['media_attachments'])) {
  3456. return false;
  3457. }
  3458. }
  3459. return $i && isset($i['account'], $i['url']);
  3460. })
  3461. ->filter(function ($i) use ($filters, $domainBlocks) {
  3462. $domain = strtolower(parse_url($i['url'], PHP_URL_HOST));
  3463. return ! in_array($i['account']['id'], $filters) && ! in_array($domain, $domainBlocks);
  3464. })
  3465. ->map(function ($status) use ($tagFilters) {
  3466. $filterResults = CustomFilter::applyCachedFilters($tagFilters, $status);
  3467. if (! empty($filterResults)) {
  3468. $status['filtered'] = $filterResults;
  3469. $shouldHide = collect($filterResults)->contains(function ($result) {
  3470. return $result['filter']['filter_action'] === 'hide';
  3471. });
  3472. if ($shouldHide) {
  3473. return null;
  3474. }
  3475. }
  3476. return $status;
  3477. })
  3478. ->filter()
  3479. ->take($limit)
  3480. ->values()
  3481. ->toArray();
  3482. return $this->json($res);
  3483. }
  3484. /**
  3485. * GET /api/v1/bookmarks
  3486. *
  3487. *
  3488. *
  3489. * @return StatusTransformer
  3490. */
  3491. public function bookmarks(Request $request)
  3492. {
  3493. abort_if(! $request->user() || ! $request->user()->token(), 403);
  3494. abort_unless($request->user()->tokenCan('read'), 403);
  3495. $this->validate($request, [
  3496. 'limit' => 'sometimes|integer|min:1',
  3497. 'max_id' => 'nullable|integer|min:0',
  3498. 'since_id' => 'nullable|integer|min:0',
  3499. 'min_id' => 'nullable|integer|min:0',
  3500. ]);
  3501. $pe = $request->has('_pe');
  3502. $pid = $request->user()->profile_id;
  3503. $limit = $request->input('limit') ?? 20;
  3504. if ($limit > 40) {
  3505. $limit = 40;
  3506. }
  3507. $max_id = $request->input('max_id');
  3508. $since_id = $request->input('since_id');
  3509. $min_id = $request->input('min_id');
  3510. $dir = $min_id ? '>' : '<';
  3511. $id = $min_id ?? $max_id;
  3512. $bookmarkQuery = Bookmark::whereProfileId($pid)
  3513. ->orderByDesc('id')
  3514. ->cursorPaginate($limit);
  3515. $bookmarks = $bookmarkQuery->map(function ($bookmark) use ($pid, $pe) {
  3516. $status = $pe ? StatusService::get($bookmark->status_id, false) : StatusService::getMastodon($bookmark->status_id, false);
  3517. if ($status) {
  3518. $status['bookmarked'] = true;
  3519. $status['favourited'] = LikeService::liked($pid, $status['id']);
  3520. $status['reblogged'] = ReblogService::get($pid, $status['id']);
  3521. }
  3522. return $status;
  3523. })
  3524. ->filter()
  3525. ->values()
  3526. ->toArray();
  3527. $links = null;
  3528. $headers = [];
  3529. if ($bookmarkQuery->nextCursor()) {
  3530. $links .= '<'.$bookmarkQuery->nextPageUrl().'&limit='.$limit.'>; rel="next"';
  3531. }
  3532. if ($bookmarkQuery->previousCursor()) {
  3533. if ($links != null) {
  3534. $links .= ', ';
  3535. }
  3536. $links .= '<'.$bookmarkQuery->previousPageUrl().'&limit='.$limit.'>; rel="prev"';
  3537. }
  3538. if ($links) {
  3539. $headers = ['Link' => $links];
  3540. }
  3541. return $this->json($bookmarks, 200, $headers);
  3542. }
  3543. /**
  3544. * POST /api/v1/statuses/{id}/bookmark
  3545. *
  3546. *
  3547. *
  3548. * @return StatusTransformer
  3549. */
  3550. public function bookmarkStatus(Request $request, $id)
  3551. {
  3552. abort_if(! $request->user() || ! $request->user()->token(), 403);
  3553. abort_unless($request->user()->tokenCan('write'), 403);
  3554. $status = Status::findOrFail($id);
  3555. $user = $request->user();
  3556. $pid = $request->user()->profile_id;
  3557. $account = AccountService::get($status->profile_id);
  3558. abort_if(isset($account['moved'], $account['moved']['id']), 422, 'Cannot bookmark a post from an account that has migrated');
  3559. abort_if($user->has_roles && ! UserRoleService::can('can-bookmark', $user->id), 403, 'Invalid permissions for this action');
  3560. abort_if($status->in_reply_to_id || $status->reblog_of_id, 404);
  3561. abort_if(! in_array($status->scope, ['public', 'unlisted', 'private']), 404);
  3562. abort_if(! in_array($status->type, ['photo', 'photo:album', 'video', 'video:album', 'photo:video:album']), 404);
  3563. if ($status->scope == 'private') {
  3564. abort_if(
  3565. $pid !== $status->profile_id && ! FollowerService::follows($pid, $status->profile_id),
  3566. 404,
  3567. 'Error: You cannot bookmark private posts from accounts you do not follow.'
  3568. );
  3569. }
  3570. Bookmark::firstOrCreate([
  3571. 'status_id' => $status->id,
  3572. 'profile_id' => $pid,
  3573. ]);
  3574. BookmarkService::add($pid, $status->id);
  3575. $res = StatusService::getMastodon($status->id, false);
  3576. $res['bookmarked'] = true;
  3577. return $this->json($res);
  3578. }
  3579. /**
  3580. * POST /api/v1/statuses/{id}/unbookmark
  3581. *
  3582. *
  3583. *
  3584. * @return StatusTransformer
  3585. */
  3586. public function unbookmarkStatus(Request $request, $id)
  3587. {
  3588. abort_if(! $request->user() || ! $request->user()->token(), 403);
  3589. abort_unless($request->user()->tokenCan('write'), 403);
  3590. $status = Status::findOrFail($id);
  3591. $pid = $request->user()->profile_id;
  3592. $user = $request->user();
  3593. abort_if($user->has_roles && ! UserRoleService::can('can-bookmark', $user->id), 403, 'Invalid permissions for this action');
  3594. abort_if($status->in_reply_to_id || $status->reblog_of_id, 404);
  3595. abort_if(! in_array($status->scope, ['public', 'unlisted', 'private']), 404);
  3596. abort_if(! in_array($status->type, ['photo', 'photo:album', 'video', 'video:album', 'photo:video:album']), 404);
  3597. $bookmark = Bookmark::whereStatusId($status->id)
  3598. ->whereProfileId($pid)
  3599. ->first();
  3600. if ($bookmark) {
  3601. BookmarkService::del($pid, $status->id);
  3602. $bookmark->delete();
  3603. }
  3604. $res = StatusService::getMastodon($status->id, false);
  3605. $res['bookmarked'] = false;
  3606. return $this->json($res);
  3607. }
  3608. /**
  3609. * GET /api/v1/discover/posts
  3610. *
  3611. *
  3612. * @return array
  3613. */
  3614. public function discoverPosts(Request $request)
  3615. {
  3616. abort_if(! $request->user() || ! $request->user()->token(), 403);
  3617. abort_unless($request->user()->tokenCan('read'), 403);
  3618. $this->validate($request, [
  3619. 'limit' => 'integer|min:1|max:40',
  3620. ]);
  3621. $limit = $request->input('limit', 40);
  3622. $pid = $request->user()->profile_id;
  3623. $filters = UserFilterService::filters($pid);
  3624. $forYou = DiscoverService::getForYou();
  3625. $posts = $forYou->take(50)->map(function ($post) {
  3626. return StatusService::getMastodon($post);
  3627. })
  3628. ->filter(function ($post) use ($filters) {
  3629. return $post &&
  3630. isset($post['account']) &&
  3631. isset($post['account']['id']) &&
  3632. ! in_array($post['account']['id'], $filters);
  3633. })
  3634. ->take(12)
  3635. ->values();
  3636. return $this->json(compact('posts'));
  3637. }
  3638. /**
  3639. * GET /api/v2/statuses/{id}/replies
  3640. *
  3641. *
  3642. * @return array
  3643. */
  3644. public function statusReplies(Request $request, $id)
  3645. {
  3646. abort_if(! $request->user(), 403);
  3647. $this->validate($request, [
  3648. 'limit' => 'sometimes|integer|min:1',
  3649. 'sort' => 'in:all,newest,popular',
  3650. ]);
  3651. $limit = $request->input('limit', 3);
  3652. if ($limit > 10) {
  3653. $limit = 10;
  3654. }
  3655. $pid = $request->user()->profile_id;
  3656. $status = StatusService::getMastodon($id, false);
  3657. abort_if(! $status, 404);
  3658. abort_if(isset($status['account'], $account['account']['moved']['id']), 404, 'Account moved');
  3659. if ($status['visibility'] == 'private') {
  3660. if ($pid != $status['account']['id']) {
  3661. abort_unless(FollowerService::follows($pid, $status['account']['id']), 404);
  3662. }
  3663. }
  3664. $sortBy = $request->input('sort', 'all');
  3665. if ($sortBy == 'all' && isset($status['replies_count']) && $status['replies_count'] && $request->has('refresh_cache')) {
  3666. if (! Cache::has('status:replies:all-rc:'.$id)) {
  3667. Cache::forget('status:replies:all:'.$id);
  3668. Cache::put('status:replies:all-rc:'.$id, true, 300);
  3669. }
  3670. }
  3671. if ($sortBy == 'all' && ! $request->has('cursor')) {
  3672. $ids = Cache::remember('status:replies:all:'.$id, 3600, function () use ($id) {
  3673. return DB::table('statuses')
  3674. ->where('in_reply_to_id', $id)
  3675. ->orderBy('id')
  3676. ->cursorPaginate(3);
  3677. });
  3678. } else {
  3679. $ids = DB::table('statuses')
  3680. ->where('in_reply_to_id', $id)
  3681. ->when($sortBy, function ($q, $sortBy) {
  3682. if ($sortBy === 'all') {
  3683. return $q->orderBy('id');
  3684. }
  3685. if ($sortBy === 'newest') {
  3686. return $q->orderByDesc('created_at');
  3687. }
  3688. if ($sortBy === 'popular') {
  3689. return $q->orderByDesc('likes_count');
  3690. }
  3691. })
  3692. ->cursorPaginate($limit);
  3693. }
  3694. $filters = UserFilterService::filters($pid);
  3695. $data = $ids->filter(function ($post) use ($filters) {
  3696. return ! in_array($post->profile_id, $filters);
  3697. })
  3698. ->map(function ($post) use ($pid) {
  3699. $status = StatusService::get($post->id, false);
  3700. if (! $status || ! isset($status['id'])) {
  3701. return false;
  3702. }
  3703. $status['favourited'] = LikeService::liked($pid, $post->id);
  3704. return $status;
  3705. })
  3706. ->map(function ($post) {
  3707. if (isset($post['account']) && isset($post['account']['id'])) {
  3708. $account = AccountService::get($post['account']['id'], true);
  3709. $post['account'] = $account;
  3710. }
  3711. return $post;
  3712. })
  3713. ->filter(function ($post) {
  3714. return $post && isset($post['id']) && isset($post['account']) && isset($post['account']['id']);
  3715. })
  3716. ->values();
  3717. $res = [
  3718. 'data' => $data,
  3719. 'next' => $ids->nextPageUrl(),
  3720. ];
  3721. return $this->json($res);
  3722. }
  3723. /**
  3724. * GET /api/v2/statuses/{id}/state
  3725. *
  3726. *
  3727. * @return array
  3728. */
  3729. public function statusState(Request $request, $id)
  3730. {
  3731. abort_if(! $request->user(), 403);
  3732. $status = StatusService::get($id, false, true);
  3733. abort_if(! $status, 404);
  3734. abort_if(! in_array($status['visibility'], ['public', 'unlisted', 'private']), 404);
  3735. return $this->json(StatusService::getState($status['id'], $request->user()->profile_id));
  3736. }
  3737. /**
  3738. * GET /api/v1.1/discover/accounts/popular
  3739. *
  3740. *
  3741. * @return array
  3742. */
  3743. public function discoverAccountsPopular(Request $request)
  3744. {
  3745. abort_if(! $request->user() || ! $request->user()->token(), 403);
  3746. abort_unless($request->user()->tokenCan('read'), 403);
  3747. $pid = $request->user()->profile_id;
  3748. $ids = Cache::remember('api:v1.1:discover:accounts:popular', 14400, function () {
  3749. return DB::table('profiles')
  3750. ->where('is_private', false)
  3751. ->whereNull('status')
  3752. ->orderByDesc('profiles.followers_count')
  3753. ->limit(30)
  3754. ->get();
  3755. });
  3756. $filters = UserFilterService::filters($pid);
  3757. $asf = AdminShadowFilterService::getHideFromPublicFeedsList();
  3758. $ids = $ids->map(function ($profile) {
  3759. return AccountService::get($profile->id, true);
  3760. })
  3761. ->filter(function ($profile) {
  3762. return $profile && isset($profile['id'], $profile['locked']) && ! $profile['locked'];
  3763. })
  3764. ->filter(function ($profile) use ($pid) {
  3765. return $profile['id'] != $pid;
  3766. })
  3767. ->filter(function ($profile) use ($pid) {
  3768. return ! FollowerService::follows($pid, $profile['id'], true);
  3769. })
  3770. ->filter(function ($profile) use ($asf) {
  3771. return ! in_array($profile['id'], $asf);
  3772. })
  3773. ->filter(function ($profile) use ($filters) {
  3774. return ! in_array($profile['id'], $filters);
  3775. })
  3776. ->take(16)
  3777. ->values();
  3778. return $this->json($ids);
  3779. }
  3780. /**
  3781. * GET /api/v1/preferences
  3782. *
  3783. *
  3784. * @return array
  3785. */
  3786. public function getPreferences(Request $request)
  3787. {
  3788. abort_if(! $request->user() || ! $request->user()->token(), 403);
  3789. abort_unless($request->user()->tokenCan('read'), 403);
  3790. $pid = $request->user()->profile_id;
  3791. $account = AccountService::get($pid);
  3792. return $this->json([
  3793. 'posting:default:visibility' => $account['locked'] ? 'private' : 'public',
  3794. 'posting:default:sensitive' => false,
  3795. 'posting:default:language' => null,
  3796. 'reading:expand:media' => 'default',
  3797. 'reading:expand:spoilers' => false,
  3798. ]);
  3799. }
  3800. /**
  3801. * GET /api/v1/trends
  3802. *
  3803. *
  3804. * @return array
  3805. */
  3806. public function getTrends(Request $request)
  3807. {
  3808. abort_if(! $request->user() || ! $request->user()->token(), 403);
  3809. abort_unless($request->user()->tokenCan('read'), 403);
  3810. return $this->json([]);
  3811. }
  3812. /**
  3813. * GET /api/v1/announcements
  3814. *
  3815. *
  3816. * @return array
  3817. */
  3818. public function getAnnouncements(Request $request)
  3819. {
  3820. abort_if(! $request->user() || ! $request->user()->token(), 403);
  3821. abort_unless($request->user()->tokenCan('read'), 403);
  3822. return $this->json([]);
  3823. }
  3824. /**
  3825. * GET /api/v1/markers
  3826. *
  3827. *
  3828. * @return array
  3829. */
  3830. public function getMarkers(Request $request)
  3831. {
  3832. abort_if(! $request->user() || ! $request->user()->token(), 403);
  3833. abort_unless($request->user()->tokenCan('read'), 403);
  3834. $type = $request->input('timeline');
  3835. if (is_array($type)) {
  3836. $type = $type[0];
  3837. }
  3838. if (! $type || ! in_array($type, ['home', 'notifications'])) {
  3839. return $this->json([]);
  3840. }
  3841. $pid = $request->user()->profile_id;
  3842. return $this->json(MarkerService::get($pid, $type));
  3843. }
  3844. /**
  3845. * POST /api/v1/markers
  3846. *
  3847. *
  3848. * @return array
  3849. */
  3850. public function setMarkers(Request $request)
  3851. {
  3852. abort_if(! $request->user() || ! $request->user()->token(), 403);
  3853. abort_unless($request->user()->tokenCan('write'), 403);
  3854. $pid = $request->user()->profile_id;
  3855. $home = $request->input('home[last_read_id]');
  3856. $notifications = $request->input('notifications[last_read_id]');
  3857. if ($home) {
  3858. return $this->json(MarkerService::set($pid, 'home', $home));
  3859. }
  3860. if ($notifications) {
  3861. return $this->json(MarkerService::set($pid, 'notifications', $notifications));
  3862. }
  3863. return $this->json([]);
  3864. }
  3865. /**
  3866. * GET /api/v1/instance/peers
  3867. *
  3868. *
  3869. * @return array
  3870. */
  3871. public function instancePeers(Request $request)
  3872. {
  3873. if ((bool) config('instance.show_peers') == false) {
  3874. return $this->json([]);
  3875. }
  3876. return $this->json(
  3877. Cache::remember(InstanceService::CACHE_KEY_API_PEERS_LIST, now()->addHours(24), function () {
  3878. return Instance::whereNotNull('nodeinfo_last_fetched')
  3879. ->whereBanned(false)
  3880. ->where('nodeinfo_last_fetched', '>', now()->subDays(8))
  3881. ->pluck('domain');
  3882. })
  3883. );
  3884. }
  3885. public function accountRemoveFollowById(Request $request, $id)
  3886. {
  3887. abort_if(! $request->user(), 403);
  3888. $pid = $request->user()->profile_id;
  3889. if ($pid === $id) {
  3890. return $this->json(['error' => 'Request invalid! target_id is same user id.'], 500);
  3891. }
  3892. $exists = Follower::whereProfileId($id)
  3893. ->whereFollowingId($pid)
  3894. ->first();
  3895. abort_unless($exists, 404);
  3896. $exists->delete();
  3897. RelationshipService::refresh($pid, $id);
  3898. RelationshipService::refresh($pid, $id);
  3899. UnfollowPipeline::dispatch($id, $pid)->onQueue('high');
  3900. Cache::forget('profile:following:'.$id);
  3901. Cache::forget('profile:followers:'.$id);
  3902. Cache::forget('profile:following:'.$pid);
  3903. Cache::forget('profile:followers:'.$pid);
  3904. Cache::forget('api:local:exp:rec:'.$pid);
  3905. Cache::forget('user:account:id:'.$id);
  3906. Cache::forget('user:account:id:'.$pid);
  3907. Cache::forget('profile:follower_count:'.$id);
  3908. Cache::forget('profile:follower_count:'.$pid);
  3909. Cache::forget('profile:following_count:'.$id);
  3910. Cache::forget('profile:following_count:'.$pid);
  3911. AccountService::del($pid);
  3912. AccountService::del($id);
  3913. $res = RelationshipService::get($id, $pid);
  3914. return $this->json($res);
  3915. }
  3916. /**
  3917. * GET /api/v1/statuses/{id}/pin
  3918. */
  3919. public function statusPin(Request $request, $id)
  3920. {
  3921. abort_if(! $request->user(), 403);
  3922. abort_unless($request->user()->tokenCan('write'), 403);
  3923. $user = $request->user();
  3924. $status = Status::whereScope('public')->find($id);
  3925. if (! $status) {
  3926. return $this->json(['error' => 'Record not found'], 404);
  3927. }
  3928. if ($status->profile_id != $user->profile_id) {
  3929. return $this->json(['error' => "Validation failed: Someone else's post cannot be pinned"], 422);
  3930. }
  3931. $res = StatusService::markPin($status->id);
  3932. if (! $res['success']) {
  3933. return $this->json([
  3934. 'error' => $res['error'],
  3935. ], 422);
  3936. }
  3937. $statusRes = StatusService::get($status->id, true, true);
  3938. $status['pinned'] = true;
  3939. return $this->json($statusRes);
  3940. }
  3941. /**
  3942. * GET /api/v1/statuses/{id}/unpin
  3943. */
  3944. public function statusUnpin(Request $request, $id)
  3945. {
  3946. abort_if(! $request->user(), 403);
  3947. abort_unless($request->user()->tokenCan('write'), 403);
  3948. $status = Status::whereScope('public')->findOrFail($id);
  3949. $user = $request->user();
  3950. if ($status->profile_id != $user->profile_id) {
  3951. return $this->json(['error' => 'Record not found'], 404);
  3952. }
  3953. $res = StatusService::unmarkPin($status->id);
  3954. if (! $res) {
  3955. return $this->json($res, 422);
  3956. }
  3957. $status = StatusService::get($status->id, true, true);
  3958. $status['pinned'] = false;
  3959. return $this->json($status);
  3960. }
  3961. }