ApiV1Controller.php 147 KB

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