ApiV1Controller.php 102 KB

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