ApiV1Controller.php 135 KB

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