ApiV1Controller.php 152 KB

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