ApiV1Controller.php 152 KB

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