ApiV1Controller.php 103 KB

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