ApiV1Controller.php 162 KB

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