ApiV1Controller.php 125 KB

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