ApiV1Controller.php 126 KB

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