1
0

ApiV1Controller.php 101 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805
  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. if(config_cache('instance.admin.pid')) {
  1339. return AccountService::getMastodon(config_cache('instance.admin.pid'), true);
  1340. }
  1341. $admin = User::whereIsAdmin(true)->first();
  1342. return $admin && isset($admin->profile_id) ?
  1343. AccountService::getMastodon($admin->profile_id, true) :
  1344. null;
  1345. });
  1346. $stats = Cache::remember('api:v1:instance-data:stats', 43200, function () {
  1347. return [
  1348. 'user_count' => User::count(),
  1349. 'status_count' => Status::whereNull('uri')->count(),
  1350. 'domain_count' => Instance::count(),
  1351. ];
  1352. });
  1353. $rules = Cache::remember('api:v1:instance-data:rules', 604800, function () {
  1354. return config_cache('app.rules') ?
  1355. collect(json_decode(config_cache('app.rules'), true))
  1356. ->map(function($rule, $key) {
  1357. $id = $key + 1;
  1358. return [
  1359. 'id' => "{$id}",
  1360. 'text' => $rule
  1361. ];
  1362. })
  1363. ->toArray() : [];
  1364. });
  1365. return [
  1366. 'uri' => config('pixelfed.domain.app'),
  1367. 'title' => config('app.name'),
  1368. 'short_description' => config_cache('app.short_description'),
  1369. 'description' => config_cache('app.description'),
  1370. 'email' => config('instance.email'),
  1371. 'version' => '2.7.2 (compatible; Pixelfed ' . config('pixelfed.version') .')',
  1372. 'urls' => [
  1373. 'streaming_api' => 'wss://' . config('pixelfed.domain.app')
  1374. ],
  1375. 'stats' => $stats,
  1376. 'thumbnail' => config_cache('app.banner_image') ?? url(Storage::url('public/headers/default.jpg')),
  1377. 'languages' => [config('app.locale')],
  1378. 'registrations' => (bool) config_cache('pixelfed.open_registration'),
  1379. 'approval_required' => false,
  1380. 'contact_account' => $contact,
  1381. 'rules' => $rules,
  1382. 'configuration' => [
  1383. 'media_attachments' => [
  1384. 'image_matrix_limit' => 16777216,
  1385. 'image_size_limit' => config('pixelfed.max_photo_size') * 1024,
  1386. 'supported_mime_types' => explode(',', config('pixelfed.media_types')),
  1387. 'video_frame_rate_limit' => 120,
  1388. 'video_matrix_limit' => 2304000,
  1389. 'video_size_limit' => config('pixelfed.max_photo_size') * 1024,
  1390. ],
  1391. 'polls' => [
  1392. 'max_characters_per_option' => 50,
  1393. 'max_expiration' => 2629746,
  1394. 'max_options' => 4,
  1395. 'min_expiration' => 300
  1396. ],
  1397. 'statuses' => [
  1398. 'characters_reserved_per_url' => 23,
  1399. 'max_characters' => (int) config('pixelfed.max_caption_length'),
  1400. 'max_media_attachments' => (int) config('pixelfed.max_album_length')
  1401. ]
  1402. ]
  1403. ];
  1404. });
  1405. return $this->json($res);
  1406. }
  1407. /**
  1408. * GET /api/v1/lists
  1409. *
  1410. * Return empty array as we don't support lists
  1411. *
  1412. * @return null
  1413. */
  1414. public function accountLists(Request $request)
  1415. {
  1416. abort_if(!$request->user(), 403);
  1417. return response()->json([]);
  1418. }
  1419. /**
  1420. * GET /api/v1/accounts/{id}/lists
  1421. *
  1422. * @param integer $id
  1423. *
  1424. * @return null
  1425. */
  1426. public function accountListsById(Request $request, $id)
  1427. {
  1428. abort_if(!$request->user(), 403);
  1429. return response()->json([]);
  1430. }
  1431. /**
  1432. * POST /api/v1/media
  1433. *
  1434. *
  1435. * @return MediaTransformer
  1436. */
  1437. public function mediaUpload(Request $request)
  1438. {
  1439. abort_if(!$request->user(), 403);
  1440. if(config('pixelfed.bouncer.cloud_ips.ban_api')) {
  1441. abort_if(BouncerService::checkIp($request->ip()), 404);
  1442. }
  1443. $this->validate($request, [
  1444. 'file.*' => [
  1445. 'required_without:file',
  1446. 'mimetypes:' . config_cache('pixelfed.media_types'),
  1447. 'max:' . config_cache('pixelfed.max_photo_size'),
  1448. ],
  1449. 'file' => [
  1450. 'required_without:file.*',
  1451. 'mimetypes:' . config_cache('pixelfed.media_types'),
  1452. 'max:' . config_cache('pixelfed.max_photo_size'),
  1453. ],
  1454. 'filter_name' => 'nullable|string|max:24',
  1455. 'filter_class' => 'nullable|alpha_dash|max:24',
  1456. 'description' => 'nullable|string|max:' . config_cache('pixelfed.max_altext_length')
  1457. ]);
  1458. $user = $request->user();
  1459. if($user->last_active_at == null) {
  1460. return [];
  1461. }
  1462. if(empty($request->file('file'))) {
  1463. return response('', 422);
  1464. }
  1465. $limitKey = 'compose:rate-limit:media-upload:' . $user->id;
  1466. $limitTtl = now()->addMinutes(15);
  1467. $limitReached = Cache::remember($limitKey, $limitTtl, function() use($user) {
  1468. $dailyLimit = Media::whereUserId($user->id)->where('created_at', '>', now()->subDays(1))->count();
  1469. return $dailyLimit >= 250;
  1470. });
  1471. abort_if($limitReached == true, 429);
  1472. $profile = $user->profile;
  1473. if(config_cache('pixelfed.enforce_account_limit') == true) {
  1474. $size = Cache::remember($user->storageUsedKey(), now()->addDays(3), function() use($user) {
  1475. return Media::whereUserId($user->id)->sum('size') / 1000;
  1476. });
  1477. $limit = (int) config_cache('pixelfed.max_account_size');
  1478. if ($size >= $limit) {
  1479. abort(403, 'Account size limit reached.');
  1480. }
  1481. }
  1482. $filterClass = in_array($request->input('filter_class'), Filter::classes()) ? $request->input('filter_class') : null;
  1483. $filterName = in_array($request->input('filter_name'), Filter::names()) ? $request->input('filter_name') : null;
  1484. $photo = $request->file('file');
  1485. $mimes = explode(',', config_cache('pixelfed.media_types'));
  1486. if(in_array($photo->getMimeType(), $mimes) == false) {
  1487. abort(403, 'Invalid or unsupported mime type.');
  1488. }
  1489. $storagePath = MediaPathService::get($user, 2);
  1490. $path = $photo->storePublicly($storagePath);
  1491. $hash = \hash_file('sha256', $photo);
  1492. $license = null;
  1493. $mime = $photo->getMimeType();
  1494. // if($photo->getMimeType() == 'image/heic') {
  1495. // abort_if(config('image.driver') !== 'imagick', 422, 'Invalid media type');
  1496. // abort_if(!in_array('HEIC', \Imagick::queryformats()), 422, 'Unsupported media type');
  1497. // $oldPath = $path;
  1498. // $path = str_replace('.heic', '.jpg', $path);
  1499. // $mime = 'image/jpeg';
  1500. // \Image::make($photo)->save(storage_path("app/{$path}"));
  1501. // @unlink(storage_path("app/{$oldPath}"));
  1502. // }
  1503. $settings = UserSetting::whereUserId($user->id)->first();
  1504. if($settings && !empty($settings->compose_settings)) {
  1505. $compose = $settings->compose_settings;
  1506. if(isset($compose['default_license']) && $compose['default_license'] != 1) {
  1507. $license = $compose['default_license'];
  1508. }
  1509. }
  1510. abort_if(MediaBlocklistService::exists($hash) == true, 451);
  1511. $media = new Media();
  1512. $media->status_id = null;
  1513. $media->profile_id = $profile->id;
  1514. $media->user_id = $user->id;
  1515. $media->media_path = $path;
  1516. $media->original_sha256 = $hash;
  1517. $media->size = $photo->getSize();
  1518. $media->mime = $mime;
  1519. $media->caption = $request->input('description');
  1520. $media->filter_class = $filterClass;
  1521. $media->filter_name = $filterName;
  1522. if($license) {
  1523. $media->license = $license;
  1524. }
  1525. $media->save();
  1526. switch ($media->mime) {
  1527. case 'image/jpeg':
  1528. case 'image/png':
  1529. ImageOptimize::dispatch($media)->onQueue('mmo');
  1530. break;
  1531. case 'video/mp4':
  1532. VideoThumbnail::dispatch($media)->onQueue('mmo');
  1533. $preview_url = '/storage/no-preview.png';
  1534. $url = '/storage/no-preview.png';
  1535. break;
  1536. }
  1537. Cache::forget($limitKey);
  1538. $resource = new Fractal\Resource\Item($media, new MediaTransformer());
  1539. $res = $this->fractal->createData($resource)->toArray();
  1540. $res['preview_url'] = $media->url(). '?v=' . time();
  1541. $res['url'] = $media->url(). '?v=' . time();
  1542. return $this->json($res);
  1543. }
  1544. /**
  1545. * PUT /api/v1/media/{id}
  1546. *
  1547. * @param integer $id
  1548. *
  1549. * @return MediaTransformer
  1550. */
  1551. public function mediaUpdate(Request $request, $id)
  1552. {
  1553. abort_if(!$request->user(), 403);
  1554. if(config('pixelfed.bouncer.cloud_ips.ban_api')) {
  1555. abort_if(BouncerService::checkIp($request->ip()), 404);
  1556. }
  1557. $this->validate($request, [
  1558. 'description' => 'nullable|string|max:' . config_cache('pixelfed.max_altext_length')
  1559. ]);
  1560. $user = $request->user();
  1561. $media = Media::whereUserId($user->id)
  1562. ->whereProfileId($user->profile_id)
  1563. ->findOrFail($id);
  1564. $executed = RateLimiter::attempt(
  1565. 'media:update:'.$user->id,
  1566. 10,
  1567. function() use($media, $request) {
  1568. $caption = Purify::clean($request->input('description'));
  1569. if($caption != $media->caption) {
  1570. $media->caption = $caption;
  1571. $media->save();
  1572. if($media->status_id) {
  1573. MediaService::del($media->status_id);
  1574. StatusService::del($media->status_id);
  1575. }
  1576. }
  1577. });
  1578. if(!$executed) {
  1579. return response()->json([
  1580. 'error' => 'Too many attempts. Try again in a few minutes.'
  1581. ], 429);
  1582. };
  1583. $fractal = new Fractal\Manager();
  1584. $fractal->setSerializer(new ArraySerializer());
  1585. $resource = new Fractal\Resource\Item($media, new MediaTransformer());
  1586. return $this->json($fractal->createData($resource)->toArray());
  1587. }
  1588. /**
  1589. * GET /api/v1/media/{id}
  1590. *
  1591. * @param integer $id
  1592. *
  1593. * @return MediaTransformer
  1594. */
  1595. public function mediaGet(Request $request, $id)
  1596. {
  1597. abort_if(!$request->user(), 403);
  1598. if(config('pixelfed.bouncer.cloud_ips.ban_api')) {
  1599. abort_if(BouncerService::checkIp($request->ip()), 404);
  1600. }
  1601. $user = $request->user();
  1602. $media = Media::whereUserId($user->id)
  1603. ->whereNull('status_id')
  1604. ->findOrFail($id);
  1605. $resource = new Fractal\Resource\Item($media, new MediaTransformer());
  1606. $res = $this->fractal->createData($resource)->toArray();
  1607. return $this->json($res);
  1608. }
  1609. /**
  1610. * POST /api/v2/media
  1611. *
  1612. *
  1613. * @return MediaTransformer
  1614. */
  1615. public function mediaUploadV2(Request $request)
  1616. {
  1617. abort_if(!$request->user(), 403);
  1618. if(config('pixelfed.bouncer.cloud_ips.ban_api')) {
  1619. abort_if(BouncerService::checkIp($request->ip()), 404);
  1620. }
  1621. $this->validate($request, [
  1622. 'file.*' => [
  1623. 'required_without:file',
  1624. 'mimetypes:' . config_cache('pixelfed.media_types'),
  1625. 'max:' . config_cache('pixelfed.max_photo_size'),
  1626. ],
  1627. 'file' => [
  1628. 'required_without:file.*',
  1629. 'mimetypes:' . config_cache('pixelfed.media_types'),
  1630. 'max:' . config_cache('pixelfed.max_photo_size'),
  1631. ],
  1632. 'filter_name' => 'nullable|string|max:24',
  1633. 'filter_class' => 'nullable|alpha_dash|max:24',
  1634. 'description' => 'nullable|string|max:' . config_cache('pixelfed.max_altext_length'),
  1635. 'replace_id' => 'sometimes'
  1636. ]);
  1637. $user = $request->user();
  1638. if($user->last_active_at == null) {
  1639. return [];
  1640. }
  1641. if(empty($request->file('file'))) {
  1642. return response('', 422);
  1643. }
  1644. $limitKey = 'compose:rate-limit:media-upload:' . $user->id;
  1645. $limitTtl = now()->addMinutes(15);
  1646. $limitReached = Cache::remember($limitKey, $limitTtl, function() use($user) {
  1647. $dailyLimit = Media::whereUserId($user->id)->where('created_at', '>', now()->subDays(1))->count();
  1648. return $dailyLimit >= 250;
  1649. });
  1650. abort_if($limitReached == true, 429);
  1651. $profile = $user->profile;
  1652. if(config_cache('pixelfed.enforce_account_limit') == true) {
  1653. $size = Cache::remember($user->storageUsedKey(), now()->addDays(3), function() use($user) {
  1654. return Media::whereUserId($user->id)->sum('size') / 1000;
  1655. });
  1656. $limit = (int) config_cache('pixelfed.max_account_size');
  1657. if ($size >= $limit) {
  1658. abort(403, 'Account size limit reached.');
  1659. }
  1660. }
  1661. $filterClass = in_array($request->input('filter_class'), Filter::classes()) ? $request->input('filter_class') : null;
  1662. $filterName = in_array($request->input('filter_name'), Filter::names()) ? $request->input('filter_name') : null;
  1663. $photo = $request->file('file');
  1664. $mimes = explode(',', config_cache('pixelfed.media_types'));
  1665. if(in_array($photo->getMimeType(), $mimes) == false) {
  1666. abort(403, 'Invalid or unsupported mime type.');
  1667. }
  1668. $storagePath = MediaPathService::get($user, 2);
  1669. $path = $photo->storePublicly($storagePath);
  1670. $hash = \hash_file('sha256', $photo);
  1671. $license = null;
  1672. $mime = $photo->getMimeType();
  1673. $settings = UserSetting::whereUserId($user->id)->first();
  1674. if($settings && !empty($settings->compose_settings)) {
  1675. $compose = $settings->compose_settings;
  1676. if(isset($compose['default_license']) && $compose['default_license'] != 1) {
  1677. $license = $compose['default_license'];
  1678. }
  1679. }
  1680. abort_if(MediaBlocklistService::exists($hash) == true, 451);
  1681. if($request->has('replace_id')) {
  1682. $rpid = $request->input('replace_id');
  1683. $removeMedia = Media::whereNull('status_id')
  1684. ->whereUserId($user->id)
  1685. ->whereProfileId($profile->id)
  1686. ->where('created_at', '>', now()->subHours(2))
  1687. ->find($rpid);
  1688. if($removeMedia) {
  1689. $dateTime = Carbon::now();
  1690. MediaDeletePipeline::dispatch($removeMedia)
  1691. ->onQueue('mmo')
  1692. ->delay($dateTime->addMinutes(15));
  1693. }
  1694. }
  1695. $media = new Media();
  1696. $media->status_id = null;
  1697. $media->profile_id = $profile->id;
  1698. $media->user_id = $user->id;
  1699. $media->media_path = $path;
  1700. $media->original_sha256 = $hash;
  1701. $media->size = $photo->getSize();
  1702. $media->mime = $mime;
  1703. $media->caption = $request->input('description');
  1704. $media->filter_class = $filterClass;
  1705. $media->filter_name = $filterName;
  1706. if($license) {
  1707. $media->license = $license;
  1708. }
  1709. $media->save();
  1710. switch ($media->mime) {
  1711. case 'image/jpeg':
  1712. case 'image/png':
  1713. ImageOptimize::dispatch($media)->onQueue('mmo');
  1714. break;
  1715. case 'video/mp4':
  1716. VideoThumbnail::dispatch($media)->onQueue('mmo');
  1717. $preview_url = '/storage/no-preview.png';
  1718. $url = '/storage/no-preview.png';
  1719. break;
  1720. }
  1721. Cache::forget($limitKey);
  1722. $resource = new Fractal\Resource\Item($media, new MediaTransformer());
  1723. $res = $this->fractal->createData($resource)->toArray();
  1724. $res['preview_url'] = $media->url(). '?v=' . time();
  1725. $res['url'] = null;
  1726. return $this->json($res, 202);
  1727. }
  1728. /**
  1729. * GET /api/v1/mutes
  1730. *
  1731. *
  1732. * @return AccountTransformer
  1733. */
  1734. public function accountMutes(Request $request)
  1735. {
  1736. abort_if(!$request->user(), 403);
  1737. $this->validate($request, [
  1738. 'limit' => 'nullable|integer|min:1|max:40'
  1739. ]);
  1740. $user = $request->user();
  1741. $limit = $request->input('limit', 40);
  1742. $mutes = UserFilter::whereUserId($user->profile_id)
  1743. ->whereFilterableType('App\Profile')
  1744. ->whereFilterType('mute')
  1745. ->orderByDesc('id')
  1746. ->simplePaginate($limit)
  1747. ->pluck('filterable_id')
  1748. ->map(function($id) {
  1749. return AccountService::get($id, true);
  1750. })
  1751. ->filter(function($account) {
  1752. return $account && isset($account['id']);
  1753. })
  1754. ->values();
  1755. return $this->json($mutes);
  1756. }
  1757. /**
  1758. * POST /api/v1/accounts/{id}/mute
  1759. *
  1760. * @param integer $id
  1761. *
  1762. * @return RelationshipTransformer
  1763. */
  1764. public function accountMuteById(Request $request, $id)
  1765. {
  1766. abort_if(!$request->user(), 403);
  1767. if(config('pixelfed.bouncer.cloud_ips.ban_api')) {
  1768. abort_if(BouncerService::checkIp($request->ip()), 404);
  1769. }
  1770. $user = $request->user();
  1771. $pid = $user->profile_id;
  1772. if(intval($pid) === intval($id)) {
  1773. return $this->json(['error' => 'You cannot mute yourself'], 500);
  1774. }
  1775. $account = Profile::findOrFail($id);
  1776. $count = UserFilterService::muteCount($pid);
  1777. $maxLimit = intval(config('instance.user_filters.max_user_mutes'));
  1778. if($count == 0) {
  1779. $filterCount = UserFilter::whereUserId($pid)
  1780. ->whereFilterType('mute')
  1781. ->get()
  1782. ->map(function($rec) {
  1783. return AccountService::get($rec->filterable_id, true);
  1784. })
  1785. ->filter(function($account) {
  1786. return $account && isset($account['id']);
  1787. })
  1788. ->values()
  1789. ->count();
  1790. abort_if($filterCount >= $maxLimit, 422, AccountController::FILTER_LIMIT_MUTE_TEXT . $maxLimit . ' accounts');
  1791. } else {
  1792. abort_if($count >= $maxLimit, 422, AccountController::FILTER_LIMIT_MUTE_TEXT . $maxLimit . ' accounts');
  1793. }
  1794. $filter = UserFilter::firstOrCreate([
  1795. 'user_id' => $pid,
  1796. 'filterable_id' => $account->id,
  1797. 'filterable_type' => 'App\Profile',
  1798. 'filter_type' => 'mute',
  1799. ]);
  1800. RelationshipService::refresh($pid, $id);
  1801. $resource = new Fractal\Resource\Item($account, new RelationshipTransformer());
  1802. $res = $this->fractal->createData($resource)->toArray();
  1803. return $this->json($res);
  1804. }
  1805. /**
  1806. * POST /api/v1/accounts/{id}/unmute
  1807. *
  1808. * @param integer $id
  1809. *
  1810. * @return RelationshipTransformer
  1811. */
  1812. public function accountUnmuteById(Request $request, $id)
  1813. {
  1814. abort_if(!$request->user(), 403);
  1815. if(config('pixelfed.bouncer.cloud_ips.ban_api')) {
  1816. abort_if(BouncerService::checkIp($request->ip()), 404);
  1817. }
  1818. $user = $request->user();
  1819. $pid = $user->profile_id;
  1820. if(intval($pid) === intval($id)) {
  1821. return $this->json(['error' => 'You cannot unmute yourself'], 500);
  1822. }
  1823. $profile = Profile::findOrFail($id);
  1824. $filter = UserFilter::whereUserId($pid)
  1825. ->whereFilterableId($profile->id)
  1826. ->whereFilterableType('App\Profile')
  1827. ->whereFilterType('mute')
  1828. ->first();
  1829. if($filter) {
  1830. $filter->delete();
  1831. UserFilterService::unmute($pid, $profile->id);
  1832. RelationshipService::refresh($pid, $id);
  1833. }
  1834. $resource = new Fractal\Resource\Item($profile, new RelationshipTransformer());
  1835. $res = $this->fractal->createData($resource)->toArray();
  1836. return $this->json($res);
  1837. }
  1838. /**
  1839. * GET /api/v1/notifications
  1840. *
  1841. *
  1842. * @return NotificationTransformer
  1843. */
  1844. public function accountNotifications(Request $request)
  1845. {
  1846. abort_if(!$request->user(), 403);
  1847. if(config('pixelfed.bouncer.cloud_ips.ban_api_strict_mode')) {
  1848. abort_if(BouncerService::checkIp($request->ip()), 404);
  1849. }
  1850. $this->validate($request, [
  1851. 'limit' => 'nullable|integer|min:1|max:100',
  1852. 'min_id' => 'nullable|integer|min:1|max:'.PHP_INT_MAX,
  1853. 'max_id' => 'nullable|integer|min:1|max:'.PHP_INT_MAX,
  1854. 'since_id' => 'nullable|integer|min:1|max:'.PHP_INT_MAX,
  1855. ]);
  1856. $pid = $request->user()->profile_id;
  1857. $limit = $request->input('limit', 20);
  1858. $since = $request->input('since_id');
  1859. $min = $request->input('min_id');
  1860. $max = $request->input('max_id');
  1861. if(!$since && !$min && !$max) {
  1862. $min = 1;
  1863. }
  1864. $maxId = null;
  1865. $minId = null;
  1866. if($max) {
  1867. $res = NotificationService::getMaxMastodon($pid, $max, $limit);
  1868. $ids = NotificationService::getRankedMaxId($pid, $max, $limit);
  1869. if(!empty($ids)) {
  1870. $maxId = max($ids);
  1871. $minId = min($ids);
  1872. }
  1873. } else {
  1874. $res = NotificationService::getMinMastodon($pid, $min ?? $since, $limit);
  1875. $ids = NotificationService::getRankedMinId($pid, $min ?? $since, $limit);
  1876. if(!empty($ids)) {
  1877. $maxId = max($ids);
  1878. $minId = min($ids);
  1879. }
  1880. }
  1881. if(empty($res) && !Cache::has('pf:services:notifications:hasSynced:'.$pid)) {
  1882. Cache::put('pf:services:notifications:hasSynced:'.$pid, 1, 1209600);
  1883. NotificationService::warmCache($pid, 400, true);
  1884. }
  1885. $baseUrl = config('app.url') . '/api/v1/notifications?limit=' . $limit . '&';
  1886. if($minId == $maxId) {
  1887. $minId = null;
  1888. }
  1889. if($maxId) {
  1890. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next"';
  1891. }
  1892. if($minId) {
  1893. $link = '<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  1894. }
  1895. if($maxId && $minId) {
  1896. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next",<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  1897. }
  1898. $headers = isset($link) ? ['Link' => $link] : [];
  1899. return $this->json($res, 200, $headers);
  1900. }
  1901. /**
  1902. * GET /api/v1/timelines/home
  1903. *
  1904. *
  1905. * @return StatusTransformer
  1906. */
  1907. public function timelineHome(Request $request)
  1908. {
  1909. $this->validate($request,[
  1910. 'page' => 'sometimes|integer|max:40',
  1911. 'min_id' => 'sometimes|integer|min:0|max:' . PHP_INT_MAX,
  1912. 'max_id' => 'sometimes|integer|min:0|max:' . PHP_INT_MAX,
  1913. 'limit' => 'sometimes|integer|min:1|max:100'
  1914. ]);
  1915. if(config('pixelfed.bouncer.cloud_ips.ban_api_strict_mode')) {
  1916. abort_if(BouncerService::checkIp($request->ip()), 404);
  1917. }
  1918. $napi = $request->has(self::PF_API_ENTITY_KEY);
  1919. $page = $request->input('page');
  1920. $min = $request->input('min_id');
  1921. $max = $request->input('max_id');
  1922. $limit = $request->input('limit') ?? 20;
  1923. $pid = $request->user()->profile_id;
  1924. $following = Cache::remember('profile:following:'.$pid, 1209600, function() use($pid) {
  1925. $following = Follower::whereProfileId($pid)->pluck('following_id');
  1926. return $following->push($pid)->toArray();
  1927. });
  1928. if($min || $max) {
  1929. $dir = $min ? '>' : '<';
  1930. $id = $min ?? $max;
  1931. $res = Status::select(
  1932. 'id',
  1933. 'profile_id',
  1934. 'type',
  1935. 'visibility',
  1936. 'in_reply_to_id',
  1937. 'reblog_of_id'
  1938. )
  1939. ->where('id', $dir, $id)
  1940. ->whereNull(['in_reply_to_id', 'reblog_of_id'])
  1941. ->whereIntegerInRaw('profile_id', $following)
  1942. ->whereIn('type', ['photo', 'photo:album', 'video', 'video:album', 'photo:video:album'])
  1943. ->whereIn('visibility',['public', 'unlisted', 'private'])
  1944. ->orderByDesc('id')
  1945. ->take(($limit * 2))
  1946. ->get()
  1947. ->map(function($s) use($pid, $napi) {
  1948. try {
  1949. $account = $napi ? AccountService::get($s['profile_id'], true) : AccountService::getMastodon($s['profile_id'], true);
  1950. if(!$account) {
  1951. return false;
  1952. }
  1953. $status = $napi ? StatusService::get($s['id'], false) : StatusService::getMastodon($s['id'], false);
  1954. if(!$status || !isset($status['account']) || !isset($status['account']['id'])) {
  1955. return false;
  1956. }
  1957. } catch(\Exception $e) {
  1958. return false;
  1959. }
  1960. $status['account'] = $account;
  1961. if($pid) {
  1962. $status['favourited'] = (bool) LikeService::liked($pid, $s['id']);
  1963. $status['reblogged'] = (bool) ReblogService::get($pid, $status['id']);
  1964. }
  1965. return $status;
  1966. })
  1967. ->filter(function($status) {
  1968. return $status && isset($status['account']);
  1969. })
  1970. ->take($limit)
  1971. ->values();
  1972. } else {
  1973. $res = Status::select(
  1974. 'id',
  1975. 'profile_id',
  1976. 'type',
  1977. 'visibility',
  1978. 'in_reply_to_id',
  1979. 'reblog_of_id',
  1980. )
  1981. ->whereNull(['in_reply_to_id', 'reblog_of_id'])
  1982. ->whereIntegerInRaw('profile_id', $following)
  1983. ->whereIn('type', ['photo', 'photo:album', 'video', 'video:album', 'photo:video:album'])
  1984. ->whereIn('visibility',['public', 'unlisted', 'private'])
  1985. ->orderByDesc('id')
  1986. ->take(($limit * 2))
  1987. ->get()
  1988. ->map(function($s) use($pid, $napi) {
  1989. try {
  1990. $account = $napi ? AccountService::get($s['profile_id'], true) : AccountService::getMastodon($s['profile_id'], true);
  1991. if(!$account) {
  1992. return false;
  1993. }
  1994. $status = $napi ? StatusService::get($s['id'], false) : StatusService::getMastodon($s['id'], false);
  1995. if(!$status || !isset($status['account']) || !isset($status['account']['id'])) {
  1996. return false;
  1997. }
  1998. } catch(\Exception $e) {
  1999. return false;
  2000. }
  2001. $status['account'] = $account;
  2002. if($pid) {
  2003. $status['favourited'] = (bool) LikeService::liked($pid, $s['id']);
  2004. $status['reblogged'] = (bool) ReblogService::get($pid, $status['id']);
  2005. }
  2006. return $status;
  2007. })
  2008. ->filter(function($status) {
  2009. return $status && isset($status['account']);
  2010. })
  2011. ->take($limit)
  2012. ->values();
  2013. }
  2014. $baseUrl = config('app.url') . '/api/v1/timelines/home?limit=' . $limit . '&';
  2015. $minId = $res->map(function($s) {
  2016. return ['id' => $s['id']];
  2017. })->min('id');
  2018. $maxId = $res->map(function($s) {
  2019. return ['id' => $s['id']];
  2020. })->max('id');
  2021. if($minId == $maxId) {
  2022. $minId = null;
  2023. }
  2024. if($maxId) {
  2025. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next"';
  2026. }
  2027. if($minId) {
  2028. $link = '<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  2029. }
  2030. if($maxId && $minId) {
  2031. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next",<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  2032. }
  2033. $headers = isset($link) ? ['Link' => $link] : [];
  2034. return $this->json($res->toArray(), 200, $headers);
  2035. }
  2036. /**
  2037. * GET /api/v1/timelines/public
  2038. *
  2039. *
  2040. * @return StatusTransformer
  2041. */
  2042. public function timelinePublic(Request $request)
  2043. {
  2044. $this->validate($request,[
  2045. 'min_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  2046. 'max_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  2047. 'limit' => 'nullable|integer|max:100',
  2048. 'remote' => 'sometimes',
  2049. 'local' => 'sometimes'
  2050. ]);
  2051. if(config('pixelfed.bouncer.cloud_ips.ban_api_strict_mode')) {
  2052. abort_if(BouncerService::checkIp($request->ip()), 404);
  2053. }
  2054. $napi = $request->has(self::PF_API_ENTITY_KEY);
  2055. $min = $request->input('min_id');
  2056. $max = $request->input('max_id');
  2057. $limit = $request->input('limit') ?? 20;
  2058. $user = $request->user();
  2059. $remote = ($request->has('remote') && $request->input('remote') == true) || ($request->filled('local') && $request->input('local') != true);
  2060. $filtered = $user ? UserFilterService::filters($user->profile_id) : [];
  2061. if((!$request->has('local') || $remote) && config('instance.timeline.network.cached')) {
  2062. Cache::remember('api:v1:timelines:network:cache_check', 10368000, function() {
  2063. if(NetworkTimelineService::count() == 0) {
  2064. NetworkTimelineService::warmCache(true, config('instance.timeline.network.cache_dropoff'));
  2065. }
  2066. });
  2067. if ($max) {
  2068. $feed = NetworkTimelineService::getRankedMaxId($max, $limit + 5);
  2069. } else if ($min) {
  2070. $feed = NetworkTimelineService::getRankedMinId($min, $limit + 5);
  2071. } else {
  2072. $feed = NetworkTimelineService::get(0, $limit + 5);
  2073. }
  2074. } else {
  2075. Cache::remember('api:v1:timelines:public:cache_check', 10368000, function() {
  2076. if(PublicTimelineService::count() == 0) {
  2077. PublicTimelineService::warmCache(true, 400);
  2078. }
  2079. });
  2080. if ($max) {
  2081. $feed = PublicTimelineService::getRankedMaxId($max, $limit + 5);
  2082. } else if ($min) {
  2083. $feed = PublicTimelineService::getRankedMinId($min, $limit + 5);
  2084. } else {
  2085. $feed = PublicTimelineService::get(0, $limit + 5);
  2086. }
  2087. }
  2088. $res = collect($feed)
  2089. ->filter(function($k) use($min, $max) {
  2090. if(!$min && !$max) {
  2091. return true;
  2092. }
  2093. if($min) {
  2094. return $min != $k;
  2095. }
  2096. if($max) {
  2097. return $max != $k;
  2098. }
  2099. })
  2100. ->map(function($k) use($user, $napi) {
  2101. try {
  2102. $status = $napi ? StatusService::get($k) : StatusService::getMastodon($k);
  2103. if(!$status || !isset($status['account']) || !isset($status['account']['id'])) {
  2104. return false;
  2105. }
  2106. } catch(\Exception $e) {
  2107. return false;
  2108. }
  2109. $account = $napi ? AccountService::get($status['account']['id'], true) : AccountService::getMastodon($status['account']['id'], true);
  2110. if(!$account) {
  2111. return false;
  2112. }
  2113. $status['account'] = $account;
  2114. if($user) {
  2115. $status['favourited'] = (bool) LikeService::liked($user->profile_id, $k);
  2116. $status['reblogged'] = (bool) ReblogService::get($user->profile_id, $status['id']);
  2117. }
  2118. return $status;
  2119. })
  2120. ->filter(function($s) use($filtered) {
  2121. return $s && isset($s['account']) && in_array($s['account']['id'], $filtered) == false;
  2122. })
  2123. ->take($limit)
  2124. ->values();
  2125. $baseUrl = config('app.url') . '/api/v1/timelines/public?limit=' . $limit . '&';
  2126. if($remote) {
  2127. $baseUrl .= 'remote=1&';
  2128. }
  2129. $minId = $res->map(function($s) {
  2130. return ['id' => $s['id']];
  2131. })->min('id');
  2132. $maxId = $res->map(function($s) {
  2133. return ['id' => $s['id']];
  2134. })->max('id');
  2135. if($minId == $maxId) {
  2136. $minId = null;
  2137. }
  2138. if($maxId) {
  2139. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next"';
  2140. }
  2141. if($minId) {
  2142. $link = '<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  2143. }
  2144. if($maxId && $minId) {
  2145. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next",<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  2146. }
  2147. $headers = isset($link) ? ['Link' => $link] : [];
  2148. return $this->json($res->toArray(), 200, $headers);
  2149. }
  2150. /**
  2151. * GET /api/v1/conversations
  2152. *
  2153. * Not implemented
  2154. *
  2155. * @return array
  2156. */
  2157. public function conversations(Request $request)
  2158. {
  2159. abort_if(!$request->user(), 403);
  2160. $this->validate($request, [
  2161. 'limit' => 'min:1|max:40',
  2162. 'scope' => 'nullable|in:inbox,sent,requests'
  2163. ]);
  2164. if(config('pixelfed.bouncer.cloud_ips.ban_api_strict_mode')) {
  2165. abort_if(BouncerService::checkIp($request->ip()), 404);
  2166. }
  2167. $limit = $request->input('limit', 20);
  2168. $scope = $request->input('scope', 'inbox');
  2169. $pid = $request->user()->profile_id;
  2170. if(config('database.default') == 'pgsql') {
  2171. $dms = DirectMessage::when($scope === 'inbox', function($q, $scope) use($pid) {
  2172. return $q->whereIsHidden(false)->where('to_id', $pid)->orWhere('from_id', $pid);
  2173. })
  2174. ->when($scope === 'sent', function($q, $scope) use($pid) {
  2175. return $q->whereFromId($pid)->groupBy(['to_id', 'id']);
  2176. })
  2177. ->when($scope === 'requests', function($q, $scope) use($pid) {
  2178. return $q->whereToId($pid)->whereIsHidden(true);
  2179. });
  2180. } else {
  2181. $dms = Conversation::when($scope === 'inbox', function($q, $scope) use($pid) {
  2182. return $q->whereIsHidden(false)
  2183. ->where('to_id', $pid)
  2184. ->orWhere('from_id', $pid)
  2185. ->orderByDesc('status_id')
  2186. ->groupBy(['to_id', 'from_id']);
  2187. })
  2188. ->when($scope === 'sent', function($q, $scope) use($pid) {
  2189. return $q->whereFromId($pid)->groupBy('to_id');
  2190. })
  2191. ->when($scope === 'requests', function($q, $scope) use($pid) {
  2192. return $q->whereToId($pid)->whereIsHidden(true);
  2193. });
  2194. }
  2195. $dms = $dms->orderByDesc('status_id')
  2196. ->simplePaginate($limit)
  2197. ->map(function($dm) use($pid) {
  2198. $from = $pid == $dm->to_id ? $dm->from_id : $dm->to_id;
  2199. $res = [
  2200. 'id' => $dm->id,
  2201. 'unread' => false,
  2202. 'accounts' => [
  2203. AccountService::getMastodon($from)
  2204. ],
  2205. 'last_status' => StatusService::getDirectMessage($dm->status_id)
  2206. ];
  2207. return $res;
  2208. })
  2209. ->filter(function($dm) {
  2210. return isset($dm['accounts']) && count($dm['accounts']) && !empty($dm['last_status']);
  2211. })
  2212. ->unique(function($item, $key) {
  2213. return $item['accounts'][0]['id'];
  2214. })
  2215. ->values();
  2216. return $this->json($dms);
  2217. }
  2218. /**
  2219. * GET /api/v1/statuses/{id}
  2220. *
  2221. * @param integer $id
  2222. *
  2223. * @return StatusTransformer
  2224. */
  2225. public function statusById(Request $request, $id)
  2226. {
  2227. abort_if(!$request->user(), 403);
  2228. if(config('pixelfed.bouncer.cloud_ips.ban_api_strict_mode')) {
  2229. abort_if(BouncerService::checkIp($request->ip()), 404);
  2230. }
  2231. $user = $request->user();
  2232. $res = $request->has(self::PF_API_ENTITY_KEY) ? StatusService::get($id, false) : StatusService::getMastodon($id, false);
  2233. if(!$res || !isset($res['visibility'])) {
  2234. abort(404);
  2235. }
  2236. $scope = $res['visibility'];
  2237. if(!in_array($scope, ['public', 'unlisted'])) {
  2238. if($scope === 'private') {
  2239. if(intval($res['account']['id']) !== intval($user->profile_id)) {
  2240. abort_unless(FollowerService::follows($user->profile_id, $res['account']['id']), 403);
  2241. }
  2242. } else {
  2243. abort(400, 'Invalid request');
  2244. }
  2245. }
  2246. $res['favourited'] = LikeService::liked($user->profile_id, $res['id']);
  2247. $res['reblogged'] = ReblogService::get($user->profile_id, $res['id']);
  2248. $res['bookmarked'] = BookmarkService::get($user->profile_id, $res['id']);
  2249. return $this->json($res);
  2250. }
  2251. /**
  2252. * GET /api/v1/statuses/{id}/context
  2253. *
  2254. * @param integer $id
  2255. *
  2256. * @return StatusTransformer
  2257. */
  2258. public function statusContext(Request $request, $id)
  2259. {
  2260. abort_if(!$request->user(), 403);
  2261. if(config('pixelfed.bouncer.cloud_ips.ban_api_strict_mode')) {
  2262. abort_if(BouncerService::checkIp($request->ip()), 404);
  2263. }
  2264. $user = $request->user();
  2265. $pid = $user->profile_id;
  2266. $status = StatusService::getMastodon($id, false);
  2267. if(!$status || !isset($status['account'])) {
  2268. return response('', 404);
  2269. }
  2270. if(intval($status['account']['id']) !== intval($user->profile_id)) {
  2271. if($status['visibility'] == 'private') {
  2272. if(!FollowerService::follows($user->profile_id, $status['account']['id'])) {
  2273. return response('', 404);
  2274. }
  2275. } else {
  2276. if(!in_array($status['visibility'], ['public','unlisted'])) {
  2277. return response('', 404);
  2278. }
  2279. }
  2280. }
  2281. $ancestors = [];
  2282. $descendants = [];
  2283. if($status['in_reply_to_id']) {
  2284. $ancestors[] = StatusService::getMastodon($status['in_reply_to_id'], false);
  2285. }
  2286. if($status['replies_count']) {
  2287. $filters = UserFilterService::filters($pid);
  2288. $descendants = DB::table('statuses')
  2289. ->where('in_reply_to_id', $id)
  2290. ->limit(20)
  2291. ->pluck('id')
  2292. ->map(function($sid) {
  2293. return StatusService::getMastodon($sid, false);
  2294. })
  2295. ->filter(function($post) use($filters) {
  2296. return $post && isset($post['account'], $post['account']['id']) && !in_array($post['account']['id'], $filters);
  2297. })
  2298. ->map(function($status) use($pid) {
  2299. $status['favourited'] = LikeService::liked($pid, $status['id']);
  2300. $status['reblogged'] = ReblogService::get($pid, $status['id']);
  2301. return $status;
  2302. })
  2303. ->values();
  2304. }
  2305. $res = [
  2306. 'ancestors' => $ancestors,
  2307. 'descendants' => $descendants
  2308. ];
  2309. return $this->json($res);
  2310. }
  2311. /**
  2312. * GET /api/v1/statuses/{id}/card
  2313. *
  2314. * @param integer $id
  2315. *
  2316. * @return StatusTransformer
  2317. */
  2318. public function statusCard(Request $request, $id)
  2319. {
  2320. abort_if(!$request->user(), 403);
  2321. $res = [];
  2322. return response()->json($res);
  2323. }
  2324. /**
  2325. * GET /api/v1/statuses/{id}/reblogged_by
  2326. *
  2327. * @param integer $id
  2328. *
  2329. * @return AccountTransformer
  2330. */
  2331. public function statusRebloggedBy(Request $request, $id)
  2332. {
  2333. abort_if(!$request->user(), 403);
  2334. $this->validate($request, [
  2335. 'limit' => 'sometimes|integer|min:1|max:80'
  2336. ]);
  2337. if(config('pixelfed.bouncer.cloud_ips.ban_api')) {
  2338. abort_if(BouncerService::checkIp($request->ip()), 404);
  2339. }
  2340. $limit = $request->input('limit', 10);
  2341. $user = $request->user();
  2342. $pid = $user->profile_id;
  2343. $status = Status::findOrFail($id);
  2344. $account = AccountService::get($status->profile_id, true);
  2345. abort_if(!$account, 404);
  2346. $author = intval($status->profile_id) === intval($pid) || $user->is_admin;
  2347. $napi = $request->has(self::PF_API_ENTITY_KEY);
  2348. abort_if(
  2349. !$status->type ||
  2350. !in_array($status->type, ['photo','photo:album', 'photo:video:album', 'reply', 'text', 'video', 'video:album']),
  2351. 404,
  2352. );
  2353. if(!$author) {
  2354. if($status->scope == 'private') {
  2355. abort_if(!FollowerService::follows($pid, $status->profile_id), 403);
  2356. } else {
  2357. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  2358. }
  2359. if($request->has('cursor')) {
  2360. return $this->json([]);
  2361. }
  2362. }
  2363. $res = Status::where('reblog_of_id', $status->id)
  2364. ->orderByDesc('id')
  2365. ->cursorPaginate($limit)
  2366. ->withQueryString();
  2367. if(!$res) {
  2368. return $this->json([]);
  2369. }
  2370. $headers = [];
  2371. if($author && $res->hasPages()) {
  2372. $links = '';
  2373. if($res->onFirstPage()) {
  2374. if($res->nextPageUrl()) {
  2375. $links = '<' . $res->nextPageUrl() .'>; rel="prev"';
  2376. }
  2377. } else {
  2378. if($res->previousPageUrl()) {
  2379. $links = '<' . $res->previousPageUrl() .'>; rel="next"';
  2380. }
  2381. if($res->nextPageUrl()) {
  2382. if(!empty($links)) {
  2383. $links .= ', ';
  2384. }
  2385. $links .= '<' . $res->nextPageUrl() .'>; rel="prev"';
  2386. }
  2387. }
  2388. $headers = ['Link' => $links];
  2389. }
  2390. $res = $res->map(function($status) use($pid, $napi) {
  2391. $account = $napi ? AccountService::get($status->profile_id, true) : AccountService::getMastodon($status->profile_id, true);
  2392. if(!$account) {
  2393. return false;
  2394. }
  2395. if($napi) {
  2396. $account['follows'] = $status->profile_id == $pid ? null : FollowerService::follows($pid, $status->profile_id);
  2397. }
  2398. return $account;
  2399. })
  2400. ->filter(function($account) {
  2401. return $account && isset($account['id']);
  2402. })
  2403. ->values();
  2404. return $this->json($res, 200, $headers);
  2405. }
  2406. /**
  2407. * GET /api/v1/statuses/{id}/favourited_by
  2408. *
  2409. * @param integer $id
  2410. *
  2411. * @return AccountTransformer
  2412. */
  2413. public function statusFavouritedBy(Request $request, $id)
  2414. {
  2415. abort_if(!$request->user(), 403);
  2416. $this->validate($request, [
  2417. 'limit' => 'nullable|integer|min:1|max:80'
  2418. ]);
  2419. if(config('pixelfed.bouncer.cloud_ips.ban_api')) {
  2420. abort_if(BouncerService::checkIp($request->ip()), 404);
  2421. }
  2422. $limit = $request->input('limit', 10);
  2423. $user = $request->user();
  2424. $pid = $user->profile_id;
  2425. $status = Status::findOrFail($id);
  2426. $account = AccountService::get($status->profile_id, true);
  2427. abort_if(!$account, 404);
  2428. $author = intval($status->profile_id) === intval($pid) || $user->is_admin;
  2429. $napi = $request->has(self::PF_API_ENTITY_KEY);
  2430. abort_if(
  2431. !$status->type ||
  2432. !in_array($status->type, ['photo','photo:album', 'photo:video:album', 'reply', 'text', 'video', 'video:album']),
  2433. 404,
  2434. );
  2435. if(!$author) {
  2436. if($status->scope == 'private') {
  2437. abort_if(!FollowerService::follows($pid, $status->profile_id), 403);
  2438. } else {
  2439. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  2440. }
  2441. if($request->has('cursor')) {
  2442. return $this->json([]);
  2443. }
  2444. }
  2445. $res = Like::where('status_id', $status->id)
  2446. ->orderByDesc('id')
  2447. ->cursorPaginate($limit)
  2448. ->withQueryString();
  2449. if(!$res) {
  2450. return $this->json([]);
  2451. }
  2452. $headers = [];
  2453. if($author && $res->hasPages()) {
  2454. $links = '';
  2455. if($res->onFirstPage()) {
  2456. if($res->nextPageUrl()) {
  2457. $links = '<' . $res->nextPageUrl() .'>; rel="prev"';
  2458. }
  2459. } else {
  2460. if($res->previousPageUrl()) {
  2461. $links = '<' . $res->previousPageUrl() .'>; rel="next"';
  2462. }
  2463. if($res->nextPageUrl()) {
  2464. if(!empty($links)) {
  2465. $links .= ', ';
  2466. }
  2467. $links .= '<' . $res->nextPageUrl() .'>; rel="prev"';
  2468. }
  2469. }
  2470. $headers = ['Link' => $links];
  2471. }
  2472. $res = $res->map(function($like) use($pid, $napi) {
  2473. $account = $napi ? AccountService::get($like->profile_id, true) : AccountService::getMastodon($like->profile_id, true);
  2474. if(!$account) {
  2475. return false;
  2476. }
  2477. if($napi) {
  2478. $account['follows'] = $like->profile_id == $pid ? null : FollowerService::follows($pid, $like->profile_id);
  2479. }
  2480. return $account;
  2481. })
  2482. ->filter(function($account) {
  2483. return $account && isset($account['id']);
  2484. })
  2485. ->values();
  2486. return $this->json($res, 200, $headers);
  2487. }
  2488. /**
  2489. * POST /api/v1/statuses
  2490. *
  2491. *
  2492. * @return StatusTransformer
  2493. */
  2494. public function statusCreate(Request $request)
  2495. {
  2496. abort_if(!$request->user(), 403);
  2497. if(config('pixelfed.bouncer.cloud_ips.ban_api')) {
  2498. abort_if(BouncerService::checkIp($request->ip()), 404);
  2499. }
  2500. $this->validate($request, [
  2501. 'status' => 'nullable|string',
  2502. 'in_reply_to_id' => 'nullable',
  2503. 'media_ids' => 'sometimes|array|max:' . config_cache('pixelfed.max_album_length'),
  2504. 'sensitive' => 'nullable',
  2505. 'visibility' => 'string|in:private,unlisted,public',
  2506. 'spoiler_text' => 'sometimes|max:140',
  2507. 'place_id' => 'sometimes|integer|min:1|max:128769',
  2508. 'collection_ids' => 'sometimes|array|max:3',
  2509. 'comments_disabled' => 'sometimes|boolean',
  2510. ]);
  2511. if(config('costar.enabled') == true) {
  2512. $blockedKeywords = config('costar.keyword.block');
  2513. if($blockedKeywords !== null && $request->status) {
  2514. $keywords = config('costar.keyword.block');
  2515. foreach($keywords as $kw) {
  2516. if(Str::contains($request->status, $kw) == true) {
  2517. abort(400, 'Invalid object. Contains banned keyword.');
  2518. }
  2519. }
  2520. }
  2521. }
  2522. if(!$request->filled('media_ids') && !$request->filled('in_reply_to_id')) {
  2523. abort(403, 'Empty statuses are not allowed');
  2524. }
  2525. $ids = $request->input('media_ids');
  2526. $in_reply_to_id = $request->input('in_reply_to_id');
  2527. $user = $request->user();
  2528. $profile = $user->profile;
  2529. $limitKey = 'compose:rate-limit:store:' . $user->id;
  2530. $limitTtl = now()->addMinutes(15);
  2531. $limitReached = Cache::remember($limitKey, $limitTtl, function() use($user) {
  2532. $dailyLimit = Status::whereProfileId($user->profile_id)
  2533. ->whereNull('in_reply_to_id')
  2534. ->whereNull('reblog_of_id')
  2535. ->where('created_at', '>', now()->subDays(1))
  2536. ->count();
  2537. return $dailyLimit >= 100;
  2538. });
  2539. abort_if($limitReached == true, 429);
  2540. $visibility = $profile->is_private ? 'private' : (
  2541. $profile->unlisted == true &&
  2542. $request->input('visibility', 'public') == 'public' ?
  2543. 'unlisted' :
  2544. $request->input('visibility', 'public'));
  2545. if($user->last_active_at == null) {
  2546. return [];
  2547. }
  2548. $content = strip_tags($request->input('status'));
  2549. $rendered = Autolink::create()->autolink($content);
  2550. $cw = $user->profile->cw == true ? true : $request->input('sensitive', false);
  2551. $spoilerText = $cw && $request->filled('spoiler_text') ? $request->input('spoiler_text') : null;
  2552. if($in_reply_to_id) {
  2553. $parent = Status::findOrFail($in_reply_to_id);
  2554. if($parent->comments_disabled) {
  2555. return $this->json("Comments have been disabled on this post", 422);
  2556. }
  2557. $blocks = UserFilterService::blocks($parent->profile_id);
  2558. abort_if(in_array($profile->id, $blocks), 422, 'Cannot reply to this post at this time.');
  2559. $status = new Status;
  2560. $status->caption = $content;
  2561. $status->rendered = $rendered;
  2562. $status->scope = $visibility;
  2563. $status->visibility = $visibility;
  2564. $status->profile_id = $user->profile_id;
  2565. $status->is_nsfw = $cw;
  2566. $status->cw_summary = $spoilerText;
  2567. $status->in_reply_to_id = $parent->id;
  2568. $status->in_reply_to_profile_id = $parent->profile_id;
  2569. $status->save();
  2570. StatusService::del($parent->id);
  2571. Cache::forget('status:replies:all:' . $parent->id);
  2572. }
  2573. if($ids) {
  2574. if(Media::whereUserId($user->id)
  2575. ->whereNull('status_id')
  2576. ->find($ids)
  2577. ->count() == 0
  2578. ) {
  2579. abort(400, 'Invalid media_ids');
  2580. }
  2581. if(!$in_reply_to_id) {
  2582. $status = new Status;
  2583. $status->caption = $content;
  2584. $status->rendered = $rendered;
  2585. $status->profile_id = $user->profile_id;
  2586. $status->is_nsfw = $cw;
  2587. $status->cw_summary = $spoilerText;
  2588. $status->scope = 'draft';
  2589. $status->visibility = 'draft';
  2590. if($request->has('place_id')) {
  2591. $status->place_id = $request->input('place_id');
  2592. }
  2593. $status->save();
  2594. }
  2595. $mimes = [];
  2596. foreach($ids as $k => $v) {
  2597. if($k + 1 > config_cache('pixelfed.max_album_length')) {
  2598. continue;
  2599. }
  2600. $m = Media::whereUserId($user->id)->whereNull('status_id')->findOrFail($v);
  2601. if($m->profile_id !== $user->profile_id || $m->status_id) {
  2602. abort(403, 'Invalid media id');
  2603. }
  2604. $m->order = $k + 1;
  2605. $m->status_id = $status->id;
  2606. $m->save();
  2607. array_push($mimes, $m->mime);
  2608. }
  2609. if(empty($mimes)) {
  2610. $status->delete();
  2611. abort(400, 'Invalid media ids');
  2612. }
  2613. if($request->has('comments_disabled') && $request->input('comments_disabled')) {
  2614. $status->comments_disabled = true;
  2615. }
  2616. $status->scope = $visibility;
  2617. $status->visibility = $visibility;
  2618. $status->type = StatusController::mimeTypeCheck($mimes);
  2619. $status->save();
  2620. }
  2621. if(!$status) {
  2622. abort(500, 'An error occured.');
  2623. }
  2624. NewStatusPipeline::dispatch($status);
  2625. if($status->in_reply_to_id) {
  2626. CommentPipeline::dispatch($parent, $status);
  2627. }
  2628. Cache::forget('user:account:id:'.$user->id);
  2629. Cache::forget('_api:statuses:recent_9:'.$user->profile_id);
  2630. Cache::forget('profile:status_count:'.$user->profile_id);
  2631. Cache::forget($user->storageUsedKey());
  2632. Cache::forget('profile:embed:' . $status->profile_id);
  2633. Cache::forget($limitKey);
  2634. if($request->has('collection_ids') && $ids) {
  2635. $collections = Collection::whereProfileId($user->profile_id)
  2636. ->find($request->input('collection_ids'))
  2637. ->each(function($collection) use($status) {
  2638. $count = $collection->items()->count();
  2639. $item = CollectionItem::firstOrCreate([
  2640. 'collection_id' => $collection->id,
  2641. 'object_type' => 'App\Status',
  2642. 'object_id' => $status->id
  2643. ],[
  2644. 'order' => $count,
  2645. ]);
  2646. CollectionService::addItem(
  2647. $collection->id,
  2648. $status->id,
  2649. $count
  2650. );
  2651. $collection->updated_at = now();
  2652. $collection->save();
  2653. CollectionService::setCollection($collection->id, $collection);
  2654. });
  2655. }
  2656. $res = StatusService::getMastodon($status->id, false);
  2657. $res['favourited'] = false;
  2658. $res['language'] = 'en';
  2659. $res['bookmarked'] = false;
  2660. $res['card'] = null;
  2661. return $this->json($res);
  2662. }
  2663. /**
  2664. * DELETE /api/v1/statuses
  2665. *
  2666. * @param integer $id
  2667. *
  2668. * @return null
  2669. */
  2670. public function statusDelete(Request $request, $id)
  2671. {
  2672. abort_if(!$request->user(), 403);
  2673. if(config('pixelfed.bouncer.cloud_ips.ban_api')) {
  2674. abort_if(BouncerService::checkIp($request->ip()), 404);
  2675. }
  2676. $status = Status::whereProfileId($request->user()->profile->id)
  2677. ->findOrFail($id);
  2678. $resource = new Fractal\Resource\Item($status, new StatusTransformer());
  2679. Cache::forget('profile:status_count:'.$status->profile_id);
  2680. StatusDelete::dispatch($status);
  2681. $res = $this->fractal->createData($resource)->toArray();
  2682. $res['text'] = $res['content'];
  2683. unset($res['content']);
  2684. return $this->json($res);
  2685. }
  2686. /**
  2687. * POST /api/v1/statuses/{id}/reblog
  2688. *
  2689. * @param integer $id
  2690. *
  2691. * @return StatusTransformer
  2692. */
  2693. public function statusShare(Request $request, $id)
  2694. {
  2695. abort_if(!$request->user(), 403);
  2696. if(config('pixelfed.bouncer.cloud_ips.ban_api')) {
  2697. abort_if(BouncerService::checkIp($request->ip()), 404);
  2698. }
  2699. $user = $request->user();
  2700. $status = Status::whereScope('public')->findOrFail($id);
  2701. if(intval($status->profile_id) !== intval($user->profile_id)) {
  2702. if($status->scope == 'private') {
  2703. abort_if(!FollowerService::follows($user->profile_id, $status->profile_id), 403);
  2704. } else {
  2705. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  2706. }
  2707. $blocks = UserFilterService::blocks($status->profile_id);
  2708. if($blocks && in_array($user->profile_id, $blocks)) {
  2709. abort(422);
  2710. }
  2711. }
  2712. $share = Status::firstOrCreate([
  2713. 'profile_id' => $user->profile_id,
  2714. 'reblog_of_id' => $status->id,
  2715. 'type' => 'share',
  2716. 'in_reply_to_profile_id' => $status->profile_id,
  2717. 'scope' => 'public',
  2718. 'visibility' => 'public'
  2719. ]);
  2720. SharePipeline::dispatch($share)->onQueue('low');
  2721. StatusService::del($status->id);
  2722. ReblogService::add($user->profile_id, $status->id);
  2723. $res = StatusService::getMastodon($status->id);
  2724. $res['reblogged'] = true;
  2725. return $this->json($res);
  2726. }
  2727. /**
  2728. * POST /api/v1/statuses/{id}/unreblog
  2729. *
  2730. * @param integer $id
  2731. *
  2732. * @return StatusTransformer
  2733. */
  2734. public function statusUnshare(Request $request, $id)
  2735. {
  2736. abort_if(!$request->user(), 403);
  2737. if(config('pixelfed.bouncer.cloud_ips.ban_api')) {
  2738. abort_if(BouncerService::checkIp($request->ip()), 404);
  2739. }
  2740. $user = $request->user();
  2741. $status = Status::whereScope('public')->findOrFail($id);
  2742. if(intval($status->profile_id) !== intval($user->profile_id)) {
  2743. if($status->scope == 'private') {
  2744. abort_if(!FollowerService::follows($user->profile_id, $status->profile_id), 403);
  2745. } else {
  2746. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  2747. }
  2748. }
  2749. $reblog = Status::whereProfileId($user->profile_id)
  2750. ->whereReblogOfId($status->id)
  2751. ->first();
  2752. if(!$reblog) {
  2753. $res = StatusService::getMastodon($status->id);
  2754. $res['reblogged'] = false;
  2755. return $this->json($res);
  2756. }
  2757. UndoSharePipeline::dispatch($reblog)->onQueue('low');
  2758. ReblogService::del($user->profile_id, $status->id);
  2759. $res = StatusService::getMastodon($status->id);
  2760. $res['reblogged'] = false;
  2761. return $this->json($res);
  2762. }
  2763. /**
  2764. * GET /api/v1/timelines/tag/{hashtag}
  2765. *
  2766. * @param string $hashtag
  2767. *
  2768. * @return StatusTransformer
  2769. */
  2770. public function timelineHashtag(Request $request, $hashtag)
  2771. {
  2772. abort_if(!$request->user(), 403);
  2773. if(config('pixelfed.bouncer.cloud_ips.ban_api')) {
  2774. abort_if(BouncerService::checkIp($request->ip()), 404);
  2775. }
  2776. $this->validate($request,[
  2777. 'page' => 'nullable|integer|max:40',
  2778. 'min_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  2779. 'max_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  2780. 'limit' => 'nullable|integer|max:100'
  2781. ]);
  2782. if(config('database.default') === 'pgsql') {
  2783. $tag = Hashtag::where('name', 'ilike', $hashtag)
  2784. ->orWhere('slug', 'ilike', $hashtag)
  2785. ->first();
  2786. } else {
  2787. $tag = Hashtag::whereName($hashtag)
  2788. ->orWhere('slug', $hashtag)
  2789. ->first();
  2790. }
  2791. if(!$tag) {
  2792. return response()->json([]);
  2793. }
  2794. if($tag->is_banned == true) {
  2795. return $this->json([]);
  2796. }
  2797. $min = $request->input('min_id');
  2798. $max = $request->input('max_id');
  2799. $limit = $request->input('limit', 20);
  2800. if($min || $max) {
  2801. $minMax = SnowflakeService::byDate(now()->subMonths(6));
  2802. if($min && intval($min) < $minMax) {
  2803. return [];
  2804. }
  2805. if($max && intval($max) < $minMax) {
  2806. return [];
  2807. }
  2808. }
  2809. if(!$min && !$max) {
  2810. $id = 1;
  2811. $dir = '>';
  2812. } else {
  2813. $dir = $min ? '>' : '<';
  2814. $id = $min ?? $max;
  2815. }
  2816. $res = StatusHashtag::whereHashtagId($tag->id)
  2817. ->where('status_id', $dir, $id)
  2818. ->whereStatusVisibility('public')
  2819. ->orderBy('status_id', 'desc')
  2820. ->limit($limit)
  2821. ->pluck('status_id')
  2822. ->map(function ($i) {
  2823. return StatusService::getMastodon($i);
  2824. })
  2825. ->filter(function($i) {
  2826. return $i && isset($i['account']);
  2827. })
  2828. ->values()
  2829. ->toArray();
  2830. return $this->json($res);
  2831. }
  2832. /**
  2833. * GET /api/v1/bookmarks
  2834. *
  2835. *
  2836. *
  2837. * @return StatusTransformer
  2838. */
  2839. public function bookmarks(Request $request)
  2840. {
  2841. abort_if(!$request->user(), 403);
  2842. if(config('pixelfed.bouncer.cloud_ips.ban_api')) {
  2843. abort_if(BouncerService::checkIp($request->ip()), 404);
  2844. }
  2845. $this->validate($request, [
  2846. 'limit' => 'nullable|integer|min:1|max:40',
  2847. 'max_id' => 'nullable|integer|min:0',
  2848. 'since_id' => 'nullable|integer|min:0',
  2849. 'min_id' => 'nullable|integer|min:0'
  2850. ]);
  2851. $pe = $request->has('_pe');
  2852. $pid = $request->user()->profile_id;
  2853. $limit = $request->input('limit') ?? 20;
  2854. $max_id = $request->input('max_id');
  2855. $since_id = $request->input('since_id');
  2856. $min_id = $request->input('min_id');
  2857. $dir = $min_id ? '>' : '<';
  2858. $id = $min_id ?? $max_id;
  2859. $bookmarkQuery = Bookmark::whereProfileId($pid)
  2860. ->orderByDesc('id')
  2861. ->cursorPaginate($limit);
  2862. $bookmarks = $bookmarkQuery->map(function($bookmark) use($pid, $pe) {
  2863. $status = $pe ? StatusService::get($bookmark->status_id, false) : StatusService::getMastodon($bookmark->status_id, false);
  2864. if($status) {
  2865. $status['bookmarked'] = true;
  2866. $status['favourited'] = LikeService::liked($pid, $status['id']);
  2867. $status['reblogged'] = ReblogService::get($pid, $status['id']);
  2868. }
  2869. return $status;
  2870. })
  2871. ->filter()
  2872. ->values()
  2873. ->toArray();
  2874. $links = null;
  2875. $headers = [];
  2876. if($bookmarkQuery->nextCursor()) {
  2877. $links .= '<'.$bookmarkQuery->nextPageUrl().'&limit='.$limit.'>; rel="next"';
  2878. }
  2879. if($bookmarkQuery->previousCursor()) {
  2880. if($links != null) {
  2881. $links .= ', ';
  2882. }
  2883. $links .= '<'.$bookmarkQuery->previousPageUrl().'&limit='.$limit.'>; rel="prev"';
  2884. }
  2885. if($links) {
  2886. $headers = ['Link' => $links];
  2887. }
  2888. return $this->json($bookmarks, 200, $headers);
  2889. }
  2890. /**
  2891. * POST /api/v1/statuses/{id}/bookmark
  2892. *
  2893. *
  2894. *
  2895. * @return StatusTransformer
  2896. */
  2897. public function bookmarkStatus(Request $request, $id)
  2898. {
  2899. abort_if(!$request->user(), 403);
  2900. if(config('pixelfed.bouncer.cloud_ips.ban_api')) {
  2901. abort_if(BouncerService::checkIp($request->ip()), 404);
  2902. }
  2903. $status = Status::findOrFail($id);
  2904. $pid = $request->user()->profile_id;
  2905. abort_if($status->in_reply_to_id || $status->reblog_of_id, 404);
  2906. abort_if(!in_array($status->scope, ['public', 'unlisted', 'private']), 404);
  2907. abort_if(!in_array($status->type, ['photo','photo:album', 'video', 'video:album', 'photo:video:album']), 404);
  2908. if($status->scope == 'private') {
  2909. abort_if(
  2910. $pid !== $status->profile_id && !FollowerService::follows($pid, $status->profile_id),
  2911. 404,
  2912. 'Error: You cannot bookmark private posts from accounts you do not follow.'
  2913. );
  2914. }
  2915. Bookmark::firstOrCreate([
  2916. 'status_id' => $status->id,
  2917. 'profile_id' => $pid
  2918. ]);
  2919. BookmarkService::add($pid, $status->id);
  2920. $res = StatusService::getMastodon($status->id, false);
  2921. $res['bookmarked'] = true;
  2922. return $this->json($res);
  2923. }
  2924. /**
  2925. * POST /api/v1/statuses/{id}/unbookmark
  2926. *
  2927. *
  2928. *
  2929. * @return StatusTransformer
  2930. */
  2931. public function unbookmarkStatus(Request $request, $id)
  2932. {
  2933. abort_if(!$request->user(), 403);
  2934. if(config('pixelfed.bouncer.cloud_ips.ban_api')) {
  2935. abort_if(BouncerService::checkIp($request->ip()), 404);
  2936. }
  2937. $status = Status::findOrFail($id);
  2938. $pid = $request->user()->profile_id;
  2939. abort_if($status->in_reply_to_id || $status->reblog_of_id, 404);
  2940. abort_if(!in_array($status->scope, ['public', 'unlisted', 'private']), 404);
  2941. abort_if(!in_array($status->type, ['photo','photo:album', 'video', 'video:album', 'photo:video:album']), 404);
  2942. $bookmark = Bookmark::whereStatusId($status->id)
  2943. ->whereProfileId($pid)
  2944. ->first();
  2945. if($bookmark) {
  2946. BookmarkService::del($pid, $status->id);
  2947. $bookmark->delete();
  2948. }
  2949. $res = StatusService::getMastodon($status->id, false);
  2950. $res['bookmarked'] = false;
  2951. return $this->json($res);
  2952. }
  2953. /**
  2954. * GET /api/v2/search
  2955. *
  2956. *
  2957. * @return array
  2958. */
  2959. public function searchV2(Request $request)
  2960. {
  2961. abort_if(!$request->user(), 403);
  2962. if(config('pixelfed.bouncer.cloud_ips.ban_api')) {
  2963. abort_if(BouncerService::checkIp($request->ip()), 404);
  2964. }
  2965. $this->validate($request, [
  2966. 'q' => 'required|string|min:1|max:100',
  2967. 'account_id' => 'nullable|string',
  2968. 'max_id' => 'nullable|string',
  2969. 'min_id' => 'nullable|string',
  2970. 'type' => 'nullable|in:accounts,hashtags,statuses',
  2971. 'exclude_unreviewed' => 'nullable',
  2972. 'resolve' => 'nullable',
  2973. 'limit' => 'nullable|integer|max:40',
  2974. 'offset' => 'nullable|integer',
  2975. 'following' => 'nullable'
  2976. ]);
  2977. $mastodonMode = !$request->has('_pe');
  2978. return $this->json(SearchApiV2Service::query($request, $mastodonMode));
  2979. }
  2980. /**
  2981. * GET /api/v1/discover/posts
  2982. *
  2983. *
  2984. * @return array
  2985. */
  2986. public function discoverPosts(Request $request)
  2987. {
  2988. abort_if(!$request->user(), 403);
  2989. if(config('pixelfed.bouncer.cloud_ips.ban_api')) {
  2990. abort_if(BouncerService::checkIp($request->ip()), 404);
  2991. }
  2992. $this->validate($request, [
  2993. 'limit' => 'integer|min:1|max:40'
  2994. ]);
  2995. $limit = $request->input('limit', 40);
  2996. $pid = $request->user()->profile_id;
  2997. $filters = UserFilterService::filters($pid);
  2998. $forYou = DiscoverService::getForYou();
  2999. $posts = $forYou->take(50)->map(function($post) {
  3000. return StatusService::getMastodon($post);
  3001. })
  3002. ->filter(function($post) use($filters) {
  3003. return $post &&
  3004. isset($post['account']) &&
  3005. isset($post['account']['id']) &&
  3006. !in_array($post['account']['id'], $filters);
  3007. })
  3008. ->take(12)
  3009. ->values();
  3010. return $this->json(compact('posts'));
  3011. }
  3012. /**
  3013. * GET /api/v2/statuses/{id}/replies
  3014. *
  3015. *
  3016. * @return array
  3017. */
  3018. public function statusReplies(Request $request, $id)
  3019. {
  3020. abort_if(!$request->user(), 403);
  3021. $this->validate($request, [
  3022. 'limit' => 'int|min:1|max:10',
  3023. 'sort' => 'in:all,newest,popular'
  3024. ]);
  3025. if(config('pixelfed.bouncer.cloud_ips.ban_api')) {
  3026. abort_if(BouncerService::checkIp($request->ip()), 404);
  3027. }
  3028. $limit = $request->input('limit', 3);
  3029. $pid = $request->user()->profile_id;
  3030. $status = StatusService::getMastodon($id, false);
  3031. abort_if(!$status, 404);
  3032. if($status['visibility'] == 'private') {
  3033. if($pid != $status['account']['id']) {
  3034. abort_unless(FollowerService::follows($pid, $status['account']['id']), 404);
  3035. }
  3036. }
  3037. $sortBy = $request->input('sort', 'all');
  3038. if($sortBy == 'all' && isset($status['replies_count']) && $status['replies_count'] && $request->has('refresh_cache')) {
  3039. if(!Cache::has('status:replies:all-rc:' . $id)) {
  3040. Cache::forget('status:replies:all:' . $id);
  3041. Cache::put('status:replies:all-rc:' . $id, true, 300);
  3042. }
  3043. }
  3044. if($sortBy == 'all' && !$request->has('cursor')) {
  3045. $ids = Cache::remember('status:replies:all:' . $id, 3600, function() use($id) {
  3046. return DB::table('statuses')
  3047. ->where('in_reply_to_id', $id)
  3048. ->orderBy('id')
  3049. ->cursorPaginate(3);
  3050. });
  3051. } else {
  3052. $ids = DB::table('statuses')
  3053. ->where('in_reply_to_id', $id)
  3054. ->when($sortBy, function($q, $sortBy) {
  3055. if($sortBy === 'all') {
  3056. return $q->orderBy('id');
  3057. }
  3058. if($sortBy === 'newest') {
  3059. return $q->orderByDesc('created_at');
  3060. }
  3061. if($sortBy === 'popular') {
  3062. return $q->orderByDesc('likes_count');
  3063. }
  3064. })
  3065. ->cursorPaginate($limit);
  3066. }
  3067. $filters = UserFilterService::filters($pid);
  3068. $data = $ids->filter(function($post) use($filters) {
  3069. return !in_array($post->profile_id, $filters);
  3070. })
  3071. ->map(function($post) use($pid) {
  3072. $status = StatusService::get($post->id, false);
  3073. if(!$status || !isset($status['id'])) {
  3074. return false;
  3075. }
  3076. $status['favourited'] = LikeService::liked($pid, $post->id);
  3077. return $status;
  3078. })
  3079. ->map(function($post) {
  3080. if(isset($post['account']) && isset($post['account']['id'])) {
  3081. $account = AccountService::get($post['account']['id'], true);
  3082. $post['account'] = $account;
  3083. }
  3084. return $post;
  3085. })
  3086. ->filter(function($post) {
  3087. return $post && isset($post['id']) && isset($post['account']) && isset($post['account']['id']);
  3088. })
  3089. ->values();
  3090. $res = [
  3091. 'data' => $data,
  3092. 'next' => $ids->nextPageUrl()
  3093. ];
  3094. return $this->json($res);
  3095. }
  3096. /**
  3097. * GET /api/v2/statuses/{id}/state
  3098. *
  3099. *
  3100. * @return array
  3101. */
  3102. public function statusState(Request $request, $id)
  3103. {
  3104. abort_if(!$request->user(), 403);
  3105. if(config('pixelfed.bouncer.cloud_ips.ban_api')) {
  3106. abort_if(BouncerService::checkIp($request->ip()), 404);
  3107. }
  3108. $status = Status::findOrFail($id);
  3109. $pid = $request->user()->profile_id;
  3110. abort_if(!in_array($status->scope, ['public', 'unlisted', 'private']), 404);
  3111. return $this->json(StatusService::getState($status->id, $pid));
  3112. }
  3113. /**
  3114. * GET /api/v1.1/discover/accounts/popular
  3115. *
  3116. *
  3117. * @return array
  3118. */
  3119. public function discoverAccountsPopular(Request $request)
  3120. {
  3121. abort_if(!$request->user(), 403);
  3122. if(config('pixelfed.bouncer.cloud_ips.ban_api')) {
  3123. abort_if(BouncerService::checkIp($request->ip()), 404);
  3124. }
  3125. $pid = $request->user()->profile_id;
  3126. $ids = Cache::remember('api:v1.1:discover:accounts:popular', 86400, function() {
  3127. return DB::table('profiles')
  3128. ->where('is_private', false)
  3129. ->whereNull('status')
  3130. ->orderByDesc('profiles.followers_count')
  3131. ->limit(20)
  3132. ->get();
  3133. });
  3134. $ids = $ids->map(function($profile) {
  3135. return AccountService::get($profile->id, true);
  3136. })
  3137. ->filter(function($profile) use($pid) {
  3138. return $profile && isset($profile['id']);
  3139. })
  3140. ->filter(function($profile) use($pid) {
  3141. return $profile['id'] != $pid;
  3142. })
  3143. ->map(function($profile) {
  3144. $ids = collect(ProfileStatusService::get($profile['id'], 0, 9))
  3145. ->map(function($id) {
  3146. return StatusService::get($id, true);
  3147. })
  3148. ->filter(function($post) {
  3149. return $post && isset($post['id']);
  3150. })
  3151. ->take(3)
  3152. ->values();
  3153. $profile['recent_posts'] = $ids;
  3154. return $profile;
  3155. })
  3156. ->take(6)
  3157. ->values();
  3158. return $this->json($ids);
  3159. }
  3160. /**
  3161. * GET /api/v1/preferences
  3162. *
  3163. *
  3164. * @return array
  3165. */
  3166. public function getPreferences(Request $request)
  3167. {
  3168. abort_if(!$request->user(), 403);
  3169. if(config('pixelfed.bouncer.cloud_ips.ban_api')) {
  3170. abort_if(BouncerService::checkIp($request->ip()), 404);
  3171. }
  3172. $pid = $request->user()->profile_id;
  3173. $account = AccountService::get($pid);
  3174. return $this->json([
  3175. 'posting:default:visibility' => $account['locked'] ? 'private' : 'public',
  3176. 'posting:default:sensitive' => false,
  3177. 'posting:default:language' => null,
  3178. 'reading:expand:media' => 'default',
  3179. 'reading:expand:spoilers' => false
  3180. ]);
  3181. }
  3182. /**
  3183. * GET /api/v1/trends
  3184. *
  3185. *
  3186. * @return array
  3187. */
  3188. public function getTrends(Request $request)
  3189. {
  3190. abort_if(!$request->user(), 403);
  3191. return $this->json([]);
  3192. }
  3193. /**
  3194. * GET /api/v1/announcements
  3195. *
  3196. *
  3197. * @return array
  3198. */
  3199. public function getAnnouncements(Request $request)
  3200. {
  3201. abort_if(!$request->user(), 403);
  3202. return $this->json([]);
  3203. }
  3204. /**
  3205. * GET /api/v1/markers
  3206. *
  3207. *
  3208. * @return array
  3209. */
  3210. public function getMarkers(Request $request)
  3211. {
  3212. abort_if(!$request->user(), 403);
  3213. if(config('pixelfed.bouncer.cloud_ips.ban_api')) {
  3214. abort_if(BouncerService::checkIp($request->ip()), 404);
  3215. }
  3216. $type = $request->input('timeline');
  3217. if(is_array($type)) {
  3218. $type = $type[0];
  3219. }
  3220. if(!$type || !in_array($type, ['home', 'notifications'])) {
  3221. return $this->json([]);
  3222. }
  3223. $pid = $request->user()->profile_id;
  3224. return $this->json(MarkerService::get($pid, $type));
  3225. }
  3226. /**
  3227. * POST /api/v1/markers
  3228. *
  3229. *
  3230. * @return array
  3231. */
  3232. public function setMarkers(Request $request)
  3233. {
  3234. abort_if(!$request->user(), 403);
  3235. if(config('pixelfed.bouncer.cloud_ips.ban_api')) {
  3236. abort_if(BouncerService::checkIp($request->ip()), 404);
  3237. }
  3238. $pid = $request->user()->profile_id;
  3239. $home = $request->input('home.last_read_id');
  3240. $notifications = $request->input('notifications.last_read_id');
  3241. if($home) {
  3242. return $this->json(MarkerService::set($pid, 'home', $home));
  3243. }
  3244. if($notifications) {
  3245. return $this->json(MarkerService::set($pid, 'notifications', $notifications));
  3246. }
  3247. return $this->json([]);
  3248. }
  3249. }