ApiV1Controller.php 124 KB

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