ApiV1Controller.php 140 KB

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