ApiV1Controller.php 156 KB

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