ApiV1Controller.php 156 KB

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