1
0

ApiV1Controller.php 147 KB

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