1
0

ApiV1Controller.php 123 KB

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