ApiV1Controller.php 101 KB

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