ApiV1Controller.php 148 KB

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