ApiV1Controller.php 152 KB

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