ApiV1Controller.php 144 KB

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