1
0

ApiV1Controller.php 151 KB

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