ApiV1Controller.php 160 KB

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