1
0

ApiV1Controller.php 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686
  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, URL;
  10. use App\{
  11. Avatar,
  12. Bookmark,
  13. DirectMessage,
  14. Follower,
  15. FollowRequest,
  16. Hashtag,
  17. Instance,
  18. Like,
  19. Media,
  20. Notification,
  21. Profile,
  22. Status,
  23. StatusHashtag,
  24. User,
  25. UserSetting,
  26. UserFilter,
  27. };
  28. use League\Fractal;
  29. use App\Transformer\Api\Mastodon\v1\{
  30. AccountTransformer,
  31. MediaTransformer,
  32. NotificationTransformer,
  33. StatusTransformer,
  34. };
  35. use App\Transformer\Api\{
  36. RelationshipTransformer,
  37. };
  38. use App\Http\Controllers\FollowerController;
  39. use League\Fractal\Serializer\ArraySerializer;
  40. use League\Fractal\Pagination\IlluminatePaginatorAdapter;
  41. use App\Http\Controllers\StatusController;
  42. use App\Jobs\AvatarPipeline\AvatarOptimize;
  43. use App\Jobs\CommentPipeline\CommentPipeline;
  44. use App\Jobs\LikePipeline\LikePipeline;
  45. use App\Jobs\SharePipeline\SharePipeline;
  46. use App\Jobs\SharePipeline\UndoSharePipeline;
  47. use App\Jobs\StatusPipeline\NewStatusPipeline;
  48. use App\Jobs\StatusPipeline\StatusDelete;
  49. use App\Jobs\FollowPipeline\FollowPipeline;
  50. use App\Jobs\ImageOptimizePipeline\ImageOptimize;
  51. use App\Jobs\VideoPipeline\{
  52. VideoOptimize,
  53. VideoPostProcess,
  54. VideoThumbnail
  55. };
  56. use App\Services\{
  57. AccountService,
  58. FollowerService,
  59. InstanceService,
  60. LikeService,
  61. NotificationService,
  62. MediaPathService,
  63. PublicTimelineService,
  64. ReblogService,
  65. RelationshipService,
  66. SearchApiV2Service,
  67. StatusService,
  68. MediaBlocklistService,
  69. SnowflakeService,
  70. UserFilterService
  71. };
  72. use App\Util\Lexer\Autolink;
  73. use App\Util\Lexer\PrettyNumber;
  74. use App\Util\Localization\Localization;
  75. use App\Util\Media\License;
  76. use App\Jobs\MediaPipeline\MediaSyncLicensePipeline;
  77. use App\Services\DiscoverService;
  78. use App\Services\CustomEmojiService;
  79. class ApiV1Controller extends Controller
  80. {
  81. protected $fractal;
  82. public function __construct()
  83. {
  84. $this->fractal = new Fractal\Manager();
  85. $this->fractal->setSerializer(new ArraySerializer());
  86. }
  87. public function json($res, $code = 200, $headers = [])
  88. {
  89. return response()->json($res, $code, $headers, JSON_UNESCAPED_SLASHES);
  90. }
  91. public function apps(Request $request)
  92. {
  93. abort_if(!config_cache('pixelfed.oauth_enabled'), 404);
  94. $this->validate($request, [
  95. 'client_name' => 'required',
  96. 'redirect_uris' => 'required',
  97. 'scopes' => 'nullable',
  98. 'website' => 'nullable'
  99. ]);
  100. $uris = implode(',', explode('\n', $request->redirect_uris));
  101. $client = Passport::client()->forceFill([
  102. 'user_id' => null,
  103. 'name' => e($request->client_name),
  104. 'secret' => Str::random(40),
  105. 'redirect' => $uris,
  106. 'personal_access_client' => false,
  107. 'password_client' => false,
  108. 'revoked' => false,
  109. ]);
  110. $client->save();
  111. $res = [
  112. 'id' => $client->id,
  113. 'name' => $client->name,
  114. 'website' => null,
  115. 'redirect_uri' => $client->redirect,
  116. 'client_id' => $client->id,
  117. 'client_secret' => $client->secret,
  118. 'vapid_key' => null
  119. ];
  120. return $this->json($res, 200, [
  121. 'Access-Control-Allow-Origin' => '*'
  122. ]);
  123. }
  124. /**
  125. * GET /api/v1/accounts/verify_credentials
  126. *
  127. *
  128. * @return \App\Transformer\Api\AccountTransformer
  129. */
  130. public function verifyCredentials(Request $request)
  131. {
  132. $user = $request->user();
  133. abort_if(!$user, 403);
  134. abort_if($user->status != null, 403);
  135. $res = AccountService::getMastodon($user->profile_id);
  136. $res['source'] = [
  137. 'privacy' => $res['locked'] ? 'private' : 'public',
  138. 'sensitive' => false,
  139. 'language' => $user->language ?? 'en',
  140. 'note' => '',
  141. 'fields' => []
  142. ];
  143. return $this->json($res);
  144. }
  145. /**
  146. * GET /api/v1/accounts/{id}
  147. *
  148. * @param integer $id
  149. *
  150. * @return \App\Transformer\Api\AccountTransformer
  151. */
  152. public function accountById(Request $request, $id)
  153. {
  154. $res = AccountService::getMastodon($id, true);
  155. if(!$res) {
  156. return response()->json(['error' => 'Record not found'], 404);
  157. }
  158. return $this->json($res);
  159. }
  160. /**
  161. * PATCH /api/v1/accounts/update_credentials
  162. *
  163. * @return \App\Transformer\Api\AccountTransformer
  164. */
  165. public function accountUpdateCredentials(Request $request)
  166. {
  167. abort_if(!$request->user(), 403);
  168. $this->validate($request, [
  169. 'avatar' => 'sometimes|mimetypes:image/jpeg,image/png|min:10|max:' . config('pixelfed.max_avatar_size'),
  170. 'display_name' => 'nullable|string',
  171. 'note' => 'nullable|string',
  172. 'locked' => 'nullable',
  173. 'website' => 'nullable',
  174. // 'source.privacy' => 'nullable|in:unlisted,public,private',
  175. // 'source.sensitive' => 'nullable|boolean'
  176. ], [
  177. 'required' => 'The :attribute field is required.',
  178. 'avatar.mimetypes' => 'The file must be in jpeg or png format',
  179. 'avatar.max' => 'The :attribute exceeds the file size limit of ' . PrettyNumber::size(config('pixelfed.max_avatar_size'), true, false),
  180. ]);
  181. $user = $request->user();
  182. $profile = $user->profile;
  183. $settings = $user->settings;
  184. $changes = false;
  185. $other = array_merge(AccountService::defaultSettings()['other'], $settings->other ?? []);
  186. $syncLicenses = false;
  187. $licenseChanged = false;
  188. $composeSettings = array_merge(AccountService::defaultSettings()['compose_settings'], $settings->compose_settings ?? []);
  189. if($request->has('avatar')) {
  190. $av = Avatar::whereProfileId($profile->id)->first();
  191. if($av) {
  192. $currentAvatar = storage_path('app/'.$av->media_path);
  193. $file = $request->file('avatar');
  194. $path = "public/avatars/{$profile->id}";
  195. $name = strtolower(str_random(6)). '.' . $file->guessExtension();
  196. $request->file('avatar')->storeAs($path, $name);
  197. $av->media_path = "{$path}/{$name}";
  198. $av->save();
  199. Cache::forget("avatar:{$profile->id}");
  200. Cache::forget('user:account:id:'.$user->id);
  201. AvatarOptimize::dispatch($user->profile, $currentAvatar);
  202. }
  203. $changes = true;
  204. }
  205. if($request->has('source[language]')) {
  206. $lang = $request->input('source[language]');
  207. if(in_array($lang, Localization::languages())) {
  208. $user->language = $lang;
  209. $changes = true;
  210. $other['language'] = $lang;
  211. }
  212. }
  213. if($request->has('website')) {
  214. $website = $request->input('website');
  215. if($website != $profile->website) {
  216. if($website) {
  217. if(!strpos($website, '.')) {
  218. $website = null;
  219. }
  220. if($website && !strpos($website, '://')) {
  221. $website = 'https://' . $website;
  222. }
  223. $host = parse_url($website, PHP_URL_HOST);
  224. $bannedInstances = InstanceService::getBannedDomains();
  225. if(in_array($host, $bannedInstances)) {
  226. $website = null;
  227. }
  228. }
  229. $profile->website = $website ? $website : null;
  230. $changes = true;
  231. }
  232. }
  233. if($request->has('display_name')) {
  234. $displayName = $request->input('display_name');
  235. if($displayName !== $user->name) {
  236. $user->name = $displayName;
  237. $profile->name = $displayName;
  238. $changes = true;
  239. }
  240. }
  241. if($request->has('note')) {
  242. $note = $request->input('note');
  243. if($note !== strip_tags($profile->bio)) {
  244. $profile->bio = Autolink::create()->autolink(strip_tags($note));
  245. $changes = true;
  246. }
  247. }
  248. if($request->has('locked')) {
  249. $locked = $request->input('locked') == 'true';
  250. if($profile->is_private != $locked) {
  251. $profile->is_private = $locked;
  252. $changes = true;
  253. }
  254. }
  255. if($request->has('reduce_motion')) {
  256. $reduced = $request->input('reduce_motion');
  257. if($settings->reduce_motion != $reduced) {
  258. $settings->reduce_motion = $reduced;
  259. $changes = true;
  260. }
  261. }
  262. if($request->has('high_contrast_mode')) {
  263. $contrast = $request->input('high_contrast_mode');
  264. if($settings->high_contrast_mode != $contrast) {
  265. $settings->high_contrast_mode = $contrast;
  266. $changes = true;
  267. }
  268. }
  269. if($request->has('video_autoplay')) {
  270. $autoplay = $request->input('video_autoplay');
  271. if($settings->video_autoplay != $autoplay) {
  272. $settings->video_autoplay = $autoplay;
  273. $changes = true;
  274. }
  275. }
  276. if($request->has('license')) {
  277. $license = $request->input('license');
  278. abort_if(!in_array($license, License::keys()), 422, 'Invalid media license id');
  279. $syncLicenses = $request->input('sync_licenses') == true;
  280. abort_if($syncLicenses && Cache::get('pf:settings:mls_recently:'.$user->id) == 2, 422, 'You can only sync licenses twice per 24 hours');
  281. if($composeSettings['default_license'] != $license) {
  282. $composeSettings['default_license'] = $license;
  283. $licenseChanged = true;
  284. $changes = true;
  285. }
  286. }
  287. if($request->has('media_descriptions')) {
  288. $md = $request->input('media_descriptions') == true;
  289. if($composeSettings['media_descriptions'] != $md) {
  290. $composeSettings['media_descriptions'] = $md;
  291. $changes = true;
  292. }
  293. }
  294. if($request->has('crawlable')) {
  295. $crawlable = $request->input('crawlable');
  296. if($settings->crawlable != $crawlable) {
  297. $settings->crawlable = $crawlable;
  298. $changes = true;
  299. }
  300. }
  301. if($request->has('show_profile_follower_count')) {
  302. $show_profile_follower_count = $request->input('show_profile_follower_count');
  303. if($settings->show_profile_follower_count != $show_profile_follower_count) {
  304. $settings->show_profile_follower_count = $show_profile_follower_count;
  305. $changes = true;
  306. }
  307. }
  308. if($request->has('show_profile_following_count')) {
  309. $show_profile_following_count = $request->input('show_profile_following_count');
  310. if($settings->show_profile_following_count != $show_profile_following_count) {
  311. $settings->show_profile_following_count = $show_profile_following_count;
  312. $changes = true;
  313. }
  314. }
  315. if($request->has('public_dm')) {
  316. $public_dm = $request->input('public_dm');
  317. if($settings->public_dm != $public_dm) {
  318. $settings->public_dm = $public_dm;
  319. $changes = true;
  320. }
  321. }
  322. if($request->has('source[privacy]')) {
  323. $scope = $request->input('source[privacy]');
  324. if(in_array($scope, ['public', 'private', 'unlisted'])) {
  325. if($composeSettings['default_scope'] != $scope) {
  326. $composeSettings['default_scope'] = $profile->is_private ? 'private' : $scope;
  327. $changes = true;
  328. }
  329. }
  330. }
  331. if($request->has('disable_embeds')) {
  332. $disabledEmbeds = $request->input('disable_embeds');
  333. if($other['disable_embeds'] != $disabledEmbeds) {
  334. $other['disable_embeds'] = $disabledEmbeds;
  335. $changes = true;
  336. }
  337. }
  338. if($changes) {
  339. $settings->other = $other;
  340. $settings->compose_settings = $composeSettings;
  341. $settings->save();
  342. $user->save();
  343. $profile->save();
  344. Cache::forget('profile:settings:' . $profile->id);
  345. Cache::forget('user:account:id:' . $profile->user_id);
  346. Cache::forget('profile:follower_count:' . $profile->id);
  347. Cache::forget('profile:following_count:' . $profile->id);
  348. Cache::forget('profile:embed:' . $profile->id);
  349. Cache::forget('profile:compose:settings:' . $user->id);
  350. Cache::forget('profile:view:'.$user->username);
  351. AccountService::del($user->profile_id);
  352. }
  353. if($syncLicenses && $licenseChanged) {
  354. $key = 'pf:settings:mls_recently:'.$user->id;
  355. $val = Cache::has($key) ? 2 : 1;
  356. Cache::put($key, $val, 86400);
  357. MediaSyncLicensePipeline::dispatch($user->id, $request->input('license'));
  358. }
  359. $res = AccountService::getMastodon($user->profile_id);
  360. $res['bio'] = strip_tags($res['note']);
  361. $res = array_merge($res, $other);
  362. return $this->json($res);
  363. }
  364. /**
  365. * GET /api/v1/accounts/{id}/followers
  366. *
  367. * @param integer $id
  368. *
  369. * @return \App\Transformer\Api\AccountTransformer
  370. */
  371. public function accountFollowersById(Request $request, $id)
  372. {
  373. abort_if(!$request->user(), 403);
  374. $account = AccountService::get($id);
  375. abort_if(!$account, 404);
  376. $pid = $request->user()->profile_id;
  377. if($pid != $account['id']) {
  378. if($account['locked']) {
  379. if(FollowerService::follows($pid, $account['id'])) {
  380. return [];
  381. }
  382. }
  383. if(AccountService::hiddenFollowers($id)) {
  384. return [];
  385. }
  386. if($request->has('page') && $request->page >= 5) {
  387. return [];
  388. }
  389. }
  390. $res = DB::table('followers')
  391. ->select('id', 'profile_id', 'following_id')
  392. ->whereFollowingId($account['id'])
  393. ->orderByDesc('id')
  394. ->simplePaginate(10)
  395. ->map(function($follower) {
  396. return AccountService::getMastodon($follower->profile_id);
  397. })
  398. ->filter(function($account) {
  399. return $account && isset($account['id']);
  400. })
  401. ->values()
  402. ->toArray();
  403. return $this->json($res);
  404. }
  405. /**
  406. * GET /api/v1/accounts/{id}/following
  407. *
  408. * @param integer $id
  409. *
  410. * @return \App\Transformer\Api\AccountTransformer
  411. */
  412. public function accountFollowingById(Request $request, $id)
  413. {
  414. abort_if(!$request->user(), 403);
  415. $account = AccountService::get($id);
  416. abort_if(!$account, 404);
  417. $pid = $request->user()->profile_id;
  418. if($pid != $account['id']) {
  419. if($account['locked']) {
  420. if(FollowerService::follows($pid, $account['id'])) {
  421. return [];
  422. }
  423. }
  424. if(AccountService::hiddenFollowing($id)) {
  425. return [];
  426. }
  427. if($request->has('page') && $request->page >= 5) {
  428. return [];
  429. }
  430. }
  431. $res = DB::table('followers')
  432. ->select('id', 'profile_id', 'following_id')
  433. ->whereProfileId($account['id'])
  434. ->orderByDesc('id')
  435. ->simplePaginate(10)
  436. ->map(function($follower) {
  437. return AccountService::get($follower->following_id);
  438. })
  439. ->filter(function($account) {
  440. return $account && isset($account['id']);
  441. })
  442. ->values()
  443. ->toArray();
  444. return $this->json($res);
  445. }
  446. /**
  447. * GET /api/v1/accounts/{id}/statuses
  448. *
  449. * @param integer $id
  450. *
  451. * @return \App\Transformer\Api\StatusTransformer
  452. */
  453. public function accountStatusesById(Request $request, $id)
  454. {
  455. $user = $request->user();
  456. $this->validate($request, [
  457. 'only_media' => 'nullable',
  458. 'media_type' => 'sometimes|string|in:photo,video',
  459. 'pinned' => 'nullable',
  460. 'exclude_replies' => 'nullable',
  461. 'max_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  462. 'since_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  463. 'min_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  464. 'limit' => 'nullable|integer|min:1|max:80'
  465. ]);
  466. $profile = AccountService::getMastodon($id);
  467. abort_if(!$profile, 404);
  468. $limit = $request->limit ?? 20;
  469. $max_id = $request->max_id;
  470. $min_id = $request->min_id;
  471. if(!$max_id && !$min_id) {
  472. $min_id = 1;
  473. }
  474. $pid = $request->user()->profile_id;
  475. $scope = $request->only_media == true ?
  476. ['photo', 'photo:album', 'video', 'video:album'] :
  477. ['photo', 'photo:album', 'video', 'video:album', 'share', 'reply'];
  478. if($request->only_media && $request->has('media_type')) {
  479. $mt = $request->input('media_type');
  480. if($mt == 'video') {
  481. $scope = ['video', 'video:album'];
  482. }
  483. }
  484. if($pid == $profile['id']) {
  485. $visibility = ['public', 'unlisted', 'private'];
  486. } else if($profile['locked']) {
  487. $following = FollowerService::follows($pid, $profile['id']);
  488. abort_unless($following, 403);
  489. $visibility = ['public', 'unlisted', 'private'];
  490. } else {
  491. $following = FollowerService::follows($pid, $profile['id']);
  492. $visibility = $following ? ['public', 'unlisted', 'private'] : ['public', 'unlisted'];
  493. }
  494. $dir = $min_id ? '>' : '<';
  495. $id = $min_id ?? $max_id;
  496. $res = Status::whereProfileId($profile['id'])
  497. ->whereNull('in_reply_to_id')
  498. ->whereNull('reblog_of_id')
  499. ->whereIn('type', $scope)
  500. ->where('id', $dir, $id)
  501. ->whereIn('scope', $visibility)
  502. ->limit($limit)
  503. ->orderByDesc('id')
  504. ->get()
  505. ->map(function($s) use($user) {
  506. try {
  507. $status = StatusService::getMastodon($s->id, false);
  508. } catch (\Exception $e) {
  509. $status = false;
  510. }
  511. if($user && $status) {
  512. $status['favourited'] = (bool) LikeService::liked($user->profile_id, $s->id);
  513. }
  514. return $status;
  515. })
  516. ->filter(function($s) {
  517. return $s;
  518. })
  519. ->values();
  520. return $this->json($res);
  521. }
  522. /**
  523. * POST /api/v1/accounts/{id}/follow
  524. *
  525. * @param integer $id
  526. *
  527. * @return \App\Transformer\Api\RelationshipTransformer
  528. */
  529. public function accountFollowById(Request $request, $id)
  530. {
  531. abort_if(!$request->user(), 403);
  532. $user = $request->user();
  533. $target = Profile::where('id', '!=', $user->profile_id)
  534. ->whereNull('status')
  535. ->findOrFail($id);
  536. $private = (bool) $target->is_private;
  537. $remote = (bool) $target->domain;
  538. $blocked = UserFilter::whereUserId($target->id)
  539. ->whereFilterType('block')
  540. ->whereFilterableId($user->profile_id)
  541. ->whereFilterableType('App\Profile')
  542. ->exists();
  543. if($blocked == true) {
  544. abort(400, 'You cannot follow this user.');
  545. }
  546. $isFollowing = Follower::whereProfileId($user->profile_id)
  547. ->whereFollowingId($target->id)
  548. ->exists();
  549. // Following already, return empty relationship
  550. if($isFollowing == true) {
  551. $res = RelationshipService::get($user->profile_id, $target->id) ?? [];
  552. return $this->json($res);
  553. }
  554. // Rate limits, max 7500 followers per account
  555. if($user->profile->following()->count() >= Follower::MAX_FOLLOWING) {
  556. abort(400, 'You cannot follow more than ' . Follower::MAX_FOLLOWING . ' accounts');
  557. }
  558. // Rate limits, follow 30 accounts per hour max
  559. if($user->profile->following()->where('followers.created_at', '>', now()->subHour())->count() >= Follower::FOLLOW_PER_HOUR) {
  560. abort(400, 'You can only follow ' . Follower::FOLLOW_PER_HOUR . ' users per hour');
  561. }
  562. if($private == true) {
  563. $follow = FollowRequest::firstOrCreate([
  564. 'follower_id' => $user->profile_id,
  565. 'following_id' => $target->id
  566. ]);
  567. if($remote == true && config('federation.activitypub.remoteFollow') == true) {
  568. (new FollowerController())->sendFollow($user->profile, $target);
  569. }
  570. } else {
  571. $follower = new Follower();
  572. $follower->profile_id = $user->profile_id;
  573. $follower->following_id = $target->id;
  574. $follower->save();
  575. if($remote == true && config('federation.activitypub.remoteFollow') == true) {
  576. (new FollowerController())->sendFollow($user->profile, $target);
  577. }
  578. FollowPipeline::dispatch($follower);
  579. }
  580. RelationshipService::refresh($user->profile_id, $target->id);
  581. Cache::forget('profile:following:'.$target->id);
  582. Cache::forget('profile:followers:'.$target->id);
  583. Cache::forget('profile:following:'.$user->profile_id);
  584. Cache::forget('profile:followers:'.$user->profile_id);
  585. Cache::forget('api:local:exp:rec:'.$user->profile_id);
  586. Cache::forget('user:account:id:'.$target->user_id);
  587. Cache::forget('user:account:id:'.$user->id);
  588. Cache::forget('profile:follower_count:'.$target->id);
  589. Cache::forget('profile:follower_count:'.$user->profile_id);
  590. Cache::forget('profile:following_count:'.$target->id);
  591. Cache::forget('profile:following_count:'.$user->profile_id);
  592. AccountService::del($user->profile_id);
  593. AccountService::del($target->id);
  594. $res = RelationshipService::get($user->profile_id, $target->id);
  595. return $this->json($res);
  596. }
  597. /**
  598. * POST /api/v1/accounts/{id}/unfollow
  599. *
  600. * @param integer $id
  601. *
  602. * @return \App\Transformer\Api\RelationshipTransformer
  603. */
  604. public function accountUnfollowById(Request $request, $id)
  605. {
  606. abort_if(!$request->user(), 403);
  607. $user = $request->user();
  608. $target = Profile::where('id', '!=', $user->profile_id)
  609. ->whereNull('status')
  610. ->findOrFail($id);
  611. $private = (bool) $target->is_private;
  612. $remote = (bool) $target->domain;
  613. $isFollowing = Follower::whereProfileId($user->profile_id)
  614. ->whereFollowingId($target->id)
  615. ->exists();
  616. if($isFollowing == false) {
  617. $resource = new Fractal\Resource\Item($target, new RelationshipTransformer());
  618. $res = $this->fractal->createData($resource)->toArray();
  619. return $this->json($res);
  620. }
  621. // Rate limits, follow 30 accounts per hour max
  622. if($user->profile->following()->where('followers.updated_at', '>', now()->subHour())->count() >= Follower::FOLLOW_PER_HOUR) {
  623. abort(400, 'You can only follow or unfollow ' . Follower::FOLLOW_PER_HOUR . ' users per hour');
  624. }
  625. $user->profile->decrement('following_count');
  626. FollowRequest::whereFollowerId($user->profile_id)
  627. ->whereFollowingId($target->id)
  628. ->delete();
  629. Follower::whereProfileId($user->profile_id)
  630. ->whereFollowingId($target->id)
  631. ->delete();
  632. if($remote == true && config('federation.activitypub.remoteFollow') == true) {
  633. (new FollowerController())->sendUndoFollow($user->profile, $target);
  634. }
  635. RelationshipService::refresh($user->profile_id, $target->id);
  636. Cache::forget('profile:following:'.$target->id);
  637. Cache::forget('profile:followers:'.$target->id);
  638. Cache::forget('profile:following:'.$user->profile_id);
  639. Cache::forget('profile:followers:'.$user->profile_id);
  640. Cache::forget('api:local:exp:rec:'.$user->profile_id);
  641. Cache::forget('user:account:id:'.$target->user_id);
  642. Cache::forget('user:account:id:'.$user->id);
  643. Cache::forget('profile:follower_count:'.$target->id);
  644. Cache::forget('profile:follower_count:'.$user->profile_id);
  645. Cache::forget('profile:following_count:'.$target->id);
  646. Cache::forget('profile:following_count:'.$user->profile_id);
  647. AccountService::del($user->profile_id);
  648. AccountService::del($target->id);
  649. $res = RelationshipService::get($user->profile_id, $target->id);
  650. return $this->json($res);
  651. }
  652. /**
  653. * GET /api/v1/accounts/relationships
  654. *
  655. * @param array|integer $id
  656. *
  657. * @return \App\Services\RelationshipService
  658. */
  659. public function accountRelationshipsById(Request $request)
  660. {
  661. abort_if(!$request->user(), 403);
  662. $this->validate($request, [
  663. 'id' => 'required|array|min:1|max:20',
  664. 'id.*' => 'required|integer|min:1|max:' . PHP_INT_MAX
  665. ]);
  666. $pid = $request->user()->profile_id ?? $request->user()->profile->id;
  667. $res = collect($request->input('id'))
  668. ->filter(function($id) use($pid) {
  669. return $id != $pid;
  670. })
  671. ->map(function($id) use($pid) {
  672. return RelationshipService::get($pid, $id);
  673. });
  674. return $this->json($res);
  675. }
  676. /**
  677. * GET /api/v1/accounts/search
  678. *
  679. *
  680. *
  681. * @return \App\Transformer\Api\AccountTransformer
  682. */
  683. public function accountSearch(Request $request)
  684. {
  685. abort_if(!$request->user(), 403);
  686. $this->validate($request, [
  687. 'q' => 'required|string|min:1|max:255',
  688. 'limit' => 'nullable|integer|min:1|max:40',
  689. 'resolve' => 'nullable'
  690. ]);
  691. $user = $request->user();
  692. $query = $request->input('q');
  693. $limit = $request->input('limit') ?? 20;
  694. $resolve = (bool) $request->input('resolve', false);
  695. $q = '%' . $query . '%';
  696. $profiles = Profile::whereNull('status')
  697. ->where('username', 'like', $q)
  698. ->orWhere('name', 'like', $q)
  699. ->limit($limit)
  700. ->get();
  701. $resource = new Fractal\Resource\Collection($profiles, new AccountTransformer());
  702. $res = $this->fractal->createData($resource)->toArray();
  703. return $this->json($res);
  704. }
  705. /**
  706. * GET /api/v1/blocks
  707. *
  708. *
  709. *
  710. * @return \App\Transformer\Api\AccountTransformer
  711. */
  712. public function accountBlocks(Request $request)
  713. {
  714. abort_if(!$request->user(), 403);
  715. $this->validate($request, [
  716. 'limit' => 'nullable|integer|min:1|max:40',
  717. 'page' => 'nullable|integer|min:1|max:10'
  718. ]);
  719. $user = $request->user();
  720. $limit = $request->input('limit') ?? 40;
  721. $blocked = UserFilter::select('filterable_id','filterable_type','filter_type','user_id')
  722. ->whereUserId($user->profile_id)
  723. ->whereFilterableType('App\Profile')
  724. ->whereFilterType('block')
  725. ->simplePaginate($limit)
  726. ->pluck('filterable_id');
  727. $profiles = Profile::findOrFail($blocked);
  728. $resource = new Fractal\Resource\Collection($profiles, new AccountTransformer());
  729. $res = $this->fractal->createData($resource)->toArray();
  730. return $this->json($res);
  731. }
  732. /**
  733. * POST /api/v1/accounts/{id}/block
  734. *
  735. * @param integer $id
  736. *
  737. * @return \App\Transformer\Api\RelationshipTransformer
  738. */
  739. public function accountBlockById(Request $request, $id)
  740. {
  741. abort_if(!$request->user(), 403);
  742. $user = $request->user();
  743. $pid = $user->profile_id ?? $user->profile->id;
  744. if($id == $pid) {
  745. abort(400, 'You cannot block yourself');
  746. }
  747. $profile = Profile::findOrFail($id);
  748. if($profile->user->is_admin == true) {
  749. abort(400, 'You cannot block an admin');
  750. }
  751. Follower::whereProfileId($profile->id)->whereFollowingId($pid)->delete();
  752. Follower::whereProfileId($pid)->whereFollowingId($profile->id)->delete();
  753. Notification::whereProfileId($pid)->whereActorId($profile->id)->delete();
  754. $filter = UserFilter::firstOrCreate([
  755. 'user_id' => $pid,
  756. 'filterable_id' => $profile->id,
  757. 'filterable_type' => 'App\Profile',
  758. 'filter_type' => 'block',
  759. ]);
  760. Cache::forget("user:filter:list:$pid");
  761. Cache::forget("api:local:exp:rec:$pid");
  762. $resource = new Fractal\Resource\Item($profile, new RelationshipTransformer());
  763. $res = $this->fractal->createData($resource)->toArray();
  764. return $this->json($res);
  765. }
  766. /**
  767. * POST /api/v1/accounts/{id}/unblock
  768. *
  769. * @param integer $id
  770. *
  771. * @return \App\Transformer\Api\RelationshipTransformer
  772. */
  773. public function accountUnblockById(Request $request, $id)
  774. {
  775. abort_if(!$request->user(), 403);
  776. $user = $request->user();
  777. $pid = $user->profile_id ?? $user->profile->id;
  778. if($id == $pid) {
  779. abort(400, 'You cannot unblock yourself');
  780. }
  781. $profile = Profile::findOrFail($id);
  782. UserFilter::whereUserId($pid)
  783. ->whereFilterableId($profile->id)
  784. ->whereFilterableType('App\Profile')
  785. ->whereFilterType('block')
  786. ->delete();
  787. Cache::forget("user:filter:list:$pid");
  788. Cache::forget("api:local:exp:rec:$pid");
  789. $resource = new Fractal\Resource\Item($profile, new RelationshipTransformer());
  790. $res = $this->fractal->createData($resource)->toArray();
  791. return $this->json($res);
  792. }
  793. /**
  794. * GET /api/v1/custom_emojis
  795. *
  796. * Return custom emoji
  797. *
  798. * @return array
  799. */
  800. public function customEmojis()
  801. {
  802. return response(CustomEmojiService::all())->header('Content-Type', 'application/json');
  803. }
  804. /**
  805. * GET /api/v1/domain_blocks
  806. *
  807. * Return empty array
  808. *
  809. * @return array
  810. */
  811. public function accountDomainBlocks(Request $request)
  812. {
  813. abort_if(!$request->user(), 403);
  814. return response()->json([]);
  815. }
  816. /**
  817. * GET /api/v1/endorsements
  818. *
  819. * Return empty array
  820. *
  821. * @return array
  822. */
  823. public function accountEndorsements(Request $request)
  824. {
  825. abort_if(!$request->user(), 403);
  826. return response()->json([]);
  827. }
  828. /**
  829. * GET /api/v1/favourites
  830. *
  831. * Returns collection of liked statuses
  832. *
  833. * @return \App\Transformer\Api\StatusTransformer
  834. */
  835. public function accountFavourites(Request $request)
  836. {
  837. abort_if(!$request->user(), 403);
  838. $this->validate($request, [
  839. 'limit' => 'sometimes|integer|min:1|max:20'
  840. ]);
  841. $user = $request->user();
  842. $maxId = $request->input('max_id');
  843. $minId = $request->input('min_id');
  844. $limit = $request->input('limit') ?? 10;
  845. $res = Like::whereProfileId($user->profile_id)
  846. ->when($maxId, function($q, $maxId) {
  847. return $q->where('id', '<', $maxId);
  848. })
  849. ->when($minId, function($q, $minId) {
  850. return $q->where('id', '>', $minId);
  851. })
  852. ->orderByDesc('id')
  853. ->limit($limit)
  854. ->get()
  855. ->map(function($like) {
  856. $status = StatusService::getMastodon($like['status_id'], false);
  857. $status['like_id'] = $like->id;
  858. $status['liked_at'] = $like->created_at->format('c');
  859. return $status;
  860. })
  861. ->filter(function($status) {
  862. return $status && isset($status['id'], $status['like_id']);
  863. })
  864. ->values();
  865. if($res->count()) {
  866. $ids = $res->map(function($status) {
  867. return $status['like_id'];
  868. });
  869. $max = $ids->max();
  870. $min = $ids->min();
  871. $baseUrl = config('app.url') . '/api/v1/favourites?limit=' . $limit . '&';
  872. $link = '<'.$baseUrl.'max_id='.$max.'>; rel="next",<'.$baseUrl.'min_id='.$min.'>; rel="prev"';
  873. return $this->json($res, 200, ['Link' => $link]);
  874. } else {
  875. return $this->json($res);
  876. }
  877. }
  878. /**
  879. * POST /api/v1/statuses/{id}/favourite
  880. *
  881. * @param integer $id
  882. *
  883. * @return \App\Transformer\Api\StatusTransformer
  884. */
  885. public function statusFavouriteById(Request $request, $id)
  886. {
  887. abort_if(!$request->user(), 403);
  888. $user = $request->user();
  889. $status = StatusService::getMastodon($id, false);
  890. abort_unless($status, 400);
  891. $spid = $status['account']['id'];
  892. if($spid !== $user->profile_id) {
  893. if($status['visibility'] == 'private') {
  894. abort_if(!FollowerService::follows($user->profile_id, $spid), 403);
  895. } else {
  896. abort_if(!in_array($status['visibility'], ['public','unlisted']), 403);
  897. }
  898. }
  899. abort_if(
  900. Like::whereProfileId($user->profile_id)
  901. ->where('created_at', '>', now()->subDay())
  902. ->count() >= 100,
  903. 429
  904. );
  905. $like = Like::firstOrCreate([
  906. 'profile_id' => $user->profile_id,
  907. 'status_id' => $status['id']
  908. ]);
  909. if($like->wasRecentlyCreated == true) {
  910. $like->status_profile_id = $spid;
  911. $like->is_comment = !empty($status['in_reply_to_id']);
  912. $like->save();
  913. Status::findOrFail($status['id'])->update([
  914. 'favourites_count' => ($status['favourites_count'] ?? 0) + 1
  915. ]);
  916. LikePipeline::dispatch($like);
  917. }
  918. $status['favourited'] = true;
  919. $status['favourites_count'] = $status['favourites_count'] + 1;
  920. return $this->json($status);
  921. }
  922. /**
  923. * POST /api/v1/statuses/{id}/unfavourite
  924. *
  925. * @param integer $id
  926. *
  927. * @return \App\Transformer\Api\StatusTransformer
  928. */
  929. public function statusUnfavouriteById(Request $request, $id)
  930. {
  931. abort_if(!$request->user(), 403);
  932. $user = $request->user();
  933. $status = Status::findOrFail($id);
  934. if($status->profile_id !== $user->profile_id) {
  935. if($status->scope == 'private') {
  936. abort_if(!$status->profile->followedBy($user->profile), 403);
  937. } else {
  938. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  939. }
  940. }
  941. $like = Like::whereProfileId($user->profile_id)
  942. ->whereStatusId($status->id)
  943. ->first();
  944. if($like) {
  945. $like->forceDelete();
  946. $status->likes_count = $status->likes()->count();
  947. $status->save();
  948. }
  949. StatusService::del($status->id);
  950. $res = StatusService::getMastodon($status->id, false);
  951. $res['favourited'] = false;
  952. return $this->json($res);
  953. }
  954. /**
  955. * GET /api/v1/filters
  956. *
  957. * Return empty response since we filter server side
  958. *
  959. * @return array
  960. */
  961. public function accountFilters(Request $request)
  962. {
  963. abort_if(!$request->user(), 403);
  964. return response()->json([]);
  965. }
  966. /**
  967. * GET /api/v1/follow_requests
  968. *
  969. * Return array of Accounts that have sent follow requests
  970. *
  971. * @return \App\Transformer\Api\AccountTransformer
  972. */
  973. public function accountFollowRequests(Request $request)
  974. {
  975. abort_if(!$request->user(), 403);
  976. $user = $request->user();
  977. $followRequests = FollowRequest::whereFollowingId($user->profile->id)->pluck('follower_id');
  978. $profiles = Profile::find($followRequests);
  979. $resource = new Fractal\Resource\Collection($profiles, new AccountTransformer());
  980. $res = $this->fractal->createData($resource)->toArray();
  981. return $this->json($res);
  982. }
  983. /**
  984. * POST /api/v1/follow_requests/{id}/authorize
  985. *
  986. * @param integer $id
  987. *
  988. * @return null
  989. */
  990. public function accountFollowRequestAccept(Request $request, $id)
  991. {
  992. abort_if(!$request->user(), 403);
  993. // todo
  994. return response()->json([]);
  995. }
  996. /**
  997. * POST /api/v1/follow_requests/{id}/reject
  998. *
  999. * @param integer $id
  1000. *
  1001. * @return null
  1002. */
  1003. public function accountFollowRequestReject(Request $request, $id)
  1004. {
  1005. abort_if(!$request->user(), 403);
  1006. // todo
  1007. return response()->json([]);
  1008. }
  1009. /**
  1010. * GET /api/v1/suggestions
  1011. *
  1012. * Return empty array as we don't support suggestions
  1013. *
  1014. * @return null
  1015. */
  1016. public function accountSuggestions(Request $request)
  1017. {
  1018. abort_if(!$request->user(), 403);
  1019. // todo
  1020. return response()->json([]);
  1021. }
  1022. /**
  1023. * GET /api/v1/instance
  1024. *
  1025. * Information about the server.
  1026. *
  1027. * @return Instance
  1028. */
  1029. public function instance(Request $request)
  1030. {
  1031. $res = Cache::remember('api:v1:instance-data-response-v0', 1800, function () {
  1032. $contact = Cache::remember('api:v1:instance-data:contact', 604800, function () {
  1033. $admin = User::whereIsAdmin(true)->first();
  1034. return $admin && isset($admin->profile_id) ?
  1035. AccountService::getMastodon($admin->profile_id, true) :
  1036. null;
  1037. });
  1038. $stats = Cache::remember('api:v1:instance-data:stats', 43200, function () {
  1039. return [
  1040. 'user_count' => User::count(),
  1041. 'status_count' => Status::whereNull('uri')->count(),
  1042. 'domain_count' => Instance::count(),
  1043. ];
  1044. });
  1045. $rules = Cache::remember('api:v1:instance-data:rules', 604800, function () {
  1046. return config_cache('app.rules') ?
  1047. collect(json_decode(config_cache('app.rules'), true))
  1048. ->map(function($rule, $key) {
  1049. $id = $key + 1;
  1050. return [
  1051. 'id' => "{$id}",
  1052. 'text' => $rule
  1053. ];
  1054. })
  1055. ->toArray() : [];
  1056. });
  1057. return [
  1058. 'uri' => config('pixelfed.domain.app'),
  1059. 'title' => config('app.name'),
  1060. 'short_description' => 'Pixelfed is an image sharing platform, an ethical alternative to centralized platforms',
  1061. 'description' => 'Pixelfed is an image sharing platform, an ethical alternative to centralized platforms',
  1062. 'email' => config('instance.email'),
  1063. 'version' => '2.7.2 (compatible; Pixelfed ' . config('pixelfed.version') .')',
  1064. 'urls' => [
  1065. 'streaming_api' => 'wss://' . config('pixelfed.domain.app')
  1066. ],
  1067. 'stats' => $stats,
  1068. 'thumbnail' => url('img/pixelfed-icon-color.png'),
  1069. 'languages' => ['en'],
  1070. 'registrations' => (bool) config_cache('pixelfed.open_registration'),
  1071. 'approval_required' => false,
  1072. 'contact_account' => $contact,
  1073. 'rules' => $rules
  1074. ];
  1075. });
  1076. return $this->json($res);
  1077. }
  1078. /**
  1079. * GET /api/v1/lists
  1080. *
  1081. * Return empty array as we don't support lists
  1082. *
  1083. * @return null
  1084. */
  1085. public function accountLists(Request $request)
  1086. {
  1087. abort_if(!$request->user(), 403);
  1088. return response()->json([]);
  1089. }
  1090. /**
  1091. * GET /api/v1/accounts/{id}/lists
  1092. *
  1093. * @param integer $id
  1094. *
  1095. * @return null
  1096. */
  1097. public function accountListsById(Request $request, $id)
  1098. {
  1099. abort_if(!$request->user(), 403);
  1100. return response()->json([]);
  1101. }
  1102. /**
  1103. * POST /api/v1/media
  1104. *
  1105. *
  1106. * @return MediaTransformer
  1107. */
  1108. public function mediaUpload(Request $request)
  1109. {
  1110. abort_if(!$request->user(), 403);
  1111. $this->validate($request, [
  1112. 'file.*' => function() {
  1113. return [
  1114. 'required',
  1115. 'mimetypes:' . config_cache('pixelfed.media_types'),
  1116. 'max:' . config_cache('pixelfed.max_photo_size'),
  1117. ];
  1118. },
  1119. 'filter_name' => 'nullable|string|max:24',
  1120. 'filter_class' => 'nullable|alpha_dash|max:24',
  1121. 'description' => 'nullable|string|max:' . config_cache('pixelfed.max_altext_length')
  1122. ]);
  1123. $user = $request->user();
  1124. if($user->last_active_at == null) {
  1125. return [];
  1126. }
  1127. $limitKey = 'compose:rate-limit:media-upload:' . $user->id;
  1128. $limitTtl = now()->addMinutes(15);
  1129. $limitReached = Cache::remember($limitKey, $limitTtl, function() use($user) {
  1130. $dailyLimit = Media::whereUserId($user->id)->where('created_at', '>', now()->subDays(1))->count();
  1131. return $dailyLimit >= 250;
  1132. });
  1133. abort_if($limitReached == true, 429);
  1134. $profile = $user->profile;
  1135. if(config_cache('pixelfed.enforce_account_limit') == true) {
  1136. $size = Cache::remember($user->storageUsedKey(), now()->addDays(3), function() use($user) {
  1137. return Media::whereUserId($user->id)->sum('size') / 1000;
  1138. });
  1139. $limit = (int) config_cache('pixelfed.max_account_size');
  1140. if ($size >= $limit) {
  1141. abort(403, 'Account size limit reached.');
  1142. }
  1143. }
  1144. $filterClass = in_array($request->input('filter_class'), Filter::classes()) ? $request->input('filter_class') : null;
  1145. $filterName = in_array($request->input('filter_name'), Filter::names()) ? $request->input('filter_name') : null;
  1146. $photo = $request->file('file');
  1147. $mimes = explode(',', config_cache('pixelfed.media_types'));
  1148. if(in_array($photo->getMimeType(), $mimes) == false) {
  1149. abort(403, 'Invalid or unsupported mime type.');
  1150. }
  1151. $storagePath = MediaPathService::get($user, 2);
  1152. $path = $photo->store($storagePath);
  1153. $hash = \hash_file('sha256', $photo);
  1154. $license = null;
  1155. $mime = $photo->getMimeType();
  1156. // if($photo->getMimeType() == 'image/heic') {
  1157. // abort_if(config('image.driver') !== 'imagick', 422, 'Invalid media type');
  1158. // abort_if(!in_array('HEIC', \Imagick::queryformats()), 422, 'Unsupported media type');
  1159. // $oldPath = $path;
  1160. // $path = str_replace('.heic', '.jpg', $path);
  1161. // $mime = 'image/jpeg';
  1162. // \Image::make($photo)->save(storage_path("app/{$path}"));
  1163. // @unlink(storage_path("app/{$oldPath}"));
  1164. // }
  1165. $settings = UserSetting::whereUserId($user->id)->first();
  1166. if($settings && !empty($settings->compose_settings)) {
  1167. $compose = $settings->compose_settings;
  1168. if(isset($compose['default_license']) && $compose['default_license'] != 1) {
  1169. $license = $compose['default_license'];
  1170. }
  1171. }
  1172. abort_if(MediaBlocklistService::exists($hash) == true, 451);
  1173. $media = new Media();
  1174. $media->status_id = null;
  1175. $media->profile_id = $profile->id;
  1176. $media->user_id = $user->id;
  1177. $media->media_path = $path;
  1178. $media->original_sha256 = $hash;
  1179. $media->size = $photo->getSize();
  1180. $media->mime = $mime;
  1181. $media->caption = $request->input('description');
  1182. $media->filter_class = $filterClass;
  1183. $media->filter_name = $filterName;
  1184. if($license) {
  1185. $media->license = $license;
  1186. }
  1187. $media->save();
  1188. switch ($media->mime) {
  1189. case 'image/jpeg':
  1190. case 'image/png':
  1191. ImageOptimize::dispatch($media);
  1192. break;
  1193. case 'video/mp4':
  1194. VideoThumbnail::dispatch($media);
  1195. $preview_url = '/storage/no-preview.png';
  1196. $url = '/storage/no-preview.png';
  1197. break;
  1198. }
  1199. Cache::forget($limitKey);
  1200. $resource = new Fractal\Resource\Item($media, new MediaTransformer());
  1201. $res = $this->fractal->createData($resource)->toArray();
  1202. $res['preview_url'] = $media->url(). '?cb=1&_v=' . time();
  1203. $res['url'] = $media->url(). '?cb=1&_v=' . time();
  1204. return $this->json($res);
  1205. }
  1206. /**
  1207. * PUT /api/v1/media/{id}
  1208. *
  1209. * @param integer $id
  1210. *
  1211. * @return MediaTransformer
  1212. */
  1213. public function mediaUpdate(Request $request, $id)
  1214. {
  1215. abort_if(!$request->user(), 403);
  1216. $this->validate($request, [
  1217. 'description' => 'nullable|string|max:' . config_cache('pixelfed.max_altext_length')
  1218. ]);
  1219. $user = $request->user();
  1220. $media = Media::whereUserId($user->id)
  1221. ->whereNull('status_id')
  1222. ->findOrFail($id);
  1223. $media->caption = $request->input('description');
  1224. $media->save();
  1225. $resource = new Fractal\Resource\Item($media, new MediaTransformer());
  1226. $res = $this->fractal->createData($resource)->toArray();
  1227. $res['preview_url'] = url('/storage/no-preview.png');
  1228. $res['url'] = url('/storage/no-preview.png');
  1229. return $this->json($res);
  1230. }
  1231. /**
  1232. * GET /api/v1/media/{id}
  1233. *
  1234. * @param integer $id
  1235. *
  1236. * @return MediaTransformer
  1237. */
  1238. public function mediaGet(Request $request, $id)
  1239. {
  1240. abort_if(!$request->user(), 403);
  1241. $user = $request->user();
  1242. $media = Media::whereUserId($user->id)
  1243. ->whereNull('status_id')
  1244. ->findOrFail($id);
  1245. $resource = new Fractal\Resource\Item($media, new MediaTransformer());
  1246. $res = $this->fractal->createData($resource)->toArray();
  1247. $res['preview_url'] = url('/storage/no-preview.png');
  1248. $res['url'] = url('/storage/no-preview.png');
  1249. return $this->json($res);
  1250. }
  1251. /**
  1252. * GET /api/v1/mutes
  1253. *
  1254. *
  1255. * @return AccountTransformer
  1256. */
  1257. public function accountMutes(Request $request)
  1258. {
  1259. abort_if(!$request->user(), 403);
  1260. $this->validate($request, [
  1261. 'limit' => 'nullable|integer|min:1|max:40'
  1262. ]);
  1263. $user = $request->user();
  1264. $limit = $request->input('limit') ?? 40;
  1265. $mutes = UserFilter::whereUserId($user->profile_id)
  1266. ->whereFilterableType('App\Profile')
  1267. ->whereFilterType('mute')
  1268. ->simplePaginate($limit)
  1269. ->pluck('filterable_id');
  1270. $accounts = Profile::find($mutes);
  1271. $resource = new Fractal\Resource\Collection($accounts, new AccountTransformer());
  1272. $res = $this->fractal->createData($resource)->toArray();
  1273. return $this->json($res);
  1274. }
  1275. /**
  1276. * POST /api/v1/accounts/{id}/mute
  1277. *
  1278. * @param integer $id
  1279. *
  1280. * @return RelationshipTransformer
  1281. */
  1282. public function accountMuteById(Request $request, $id)
  1283. {
  1284. abort_if(!$request->user(), 403);
  1285. $user = $request->user();
  1286. $pid = $user->profile_id;
  1287. $account = Profile::findOrFail($id);
  1288. $filter = UserFilter::firstOrCreate([
  1289. 'user_id' => $pid,
  1290. 'filterable_id' => $account->id,
  1291. 'filterable_type' => 'App\Profile',
  1292. 'filter_type' => 'mute',
  1293. ]);
  1294. Cache::forget("user:filter:list:$pid");
  1295. Cache::forget("feature:discover:posts:$pid");
  1296. Cache::forget("api:local:exp:rec:$pid");
  1297. $resource = new Fractal\Resource\Item($account, new RelationshipTransformer());
  1298. $res = $this->fractal->createData($resource)->toArray();
  1299. return $this->json($res);
  1300. }
  1301. /**
  1302. * POST /api/v1/accounts/{id}/unmute
  1303. *
  1304. * @param integer $id
  1305. *
  1306. * @return RelationshipTransformer
  1307. */
  1308. public function accountUnmuteById(Request $request, $id)
  1309. {
  1310. abort_if(!$request->user(), 403);
  1311. $user = $request->user();
  1312. $pid = $user->profile_id;
  1313. $account = Profile::findOrFail($id);
  1314. $filter = UserFilter::whereUserId($pid)
  1315. ->whereFilterableId($account->id)
  1316. ->whereFilterableType('App\Profile')
  1317. ->whereFilterType('mute')
  1318. ->first();
  1319. if($filter) {
  1320. $filter->delete();
  1321. Cache::forget("user:filter:list:$pid");
  1322. Cache::forget("feature:discover:posts:$pid");
  1323. Cache::forget("api:local:exp:rec:$pid");
  1324. }
  1325. $resource = new Fractal\Resource\Item($account, new RelationshipTransformer());
  1326. $res = $this->fractal->createData($resource)->toArray();
  1327. return $this->json($res);
  1328. }
  1329. /**
  1330. * GET /api/v1/notifications
  1331. *
  1332. *
  1333. * @return NotificationTransformer
  1334. */
  1335. public function accountNotifications(Request $request)
  1336. {
  1337. abort_if(!$request->user(), 403);
  1338. $this->validate($request, [
  1339. 'limit' => 'nullable|integer|min:1|max:80',
  1340. 'min_id' => 'nullable|integer|min:1|max:'.PHP_INT_MAX,
  1341. 'max_id' => 'nullable|integer|min:1|max:'.PHP_INT_MAX,
  1342. 'since_id' => 'nullable|integer|min:1|max:'.PHP_INT_MAX,
  1343. ]);
  1344. $pid = $request->user()->profile_id;
  1345. $limit = $request->input('limit', 20);
  1346. $since = $request->input('since_id');
  1347. $min = $request->input('min_id');
  1348. $max = $request->input('max_id');
  1349. if(!$since && !$min && !$max) {
  1350. $min = 1;
  1351. }
  1352. $maxId = null;
  1353. $minId = null;
  1354. if($max) {
  1355. $res = NotificationService::getMax($pid, $max, $limit);
  1356. $ids = NotificationService::getRankedMaxId($pid, $max, $limit);
  1357. if(!empty($ids)) {
  1358. $maxId = max($ids);
  1359. $minId = min($ids);
  1360. }
  1361. } else {
  1362. $res = NotificationService::getMin($pid, $min ?? $since, $limit);
  1363. $ids = NotificationService::getRankedMinId($pid, $min ?? $since, $limit);
  1364. if(!empty($ids)) {
  1365. $maxId = max($ids);
  1366. $minId = min($ids);
  1367. }
  1368. }
  1369. if(empty($res) && !Cache::has('pf:services:notifications:hasSynced:'.$pid)) {
  1370. Cache::put('pf:services:notifications:hasSynced:'.$pid, 1, 1209600);
  1371. NotificationService::warmCache($pid, 400, true);
  1372. }
  1373. $baseUrl = config('app.url') . '/api/v1/notifications?limit=' . $limit . '&';
  1374. if($minId == $maxId) {
  1375. $minId = null;
  1376. }
  1377. if($maxId) {
  1378. $link = '<'.$baseUrl.'max_id='.$maxId.'>; rel="next"';
  1379. }
  1380. if($minId) {
  1381. $link = '<'.$baseUrl.'min_id='.$minId.'>; rel="prev"';
  1382. }
  1383. if($maxId && $minId) {
  1384. $link = '<'.$baseUrl.'max_id='.$maxId.'>; rel="next",<'.$baseUrl.'min_id='.$minId.'>; rel="prev"';
  1385. }
  1386. $headers = isset($link) ? ['Link' => $link] : [];
  1387. return $this->json($res, 200, $headers);
  1388. }
  1389. /**
  1390. * GET /api/v1/timelines/home
  1391. *
  1392. *
  1393. * @return StatusTransformer
  1394. */
  1395. public function timelineHome(Request $request)
  1396. {
  1397. $this->validate($request,[
  1398. 'page' => 'nullable|integer|max:40',
  1399. 'min_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  1400. 'max_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  1401. 'limit' => 'nullable|integer|max:80'
  1402. ]);
  1403. $page = $request->input('page');
  1404. $min = $request->input('min_id');
  1405. $max = $request->input('max_id');
  1406. $limit = $request->input('limit') ?? 3;
  1407. $pid = $request->user()->profile_id;
  1408. $following = Cache::remember('profile:following:'.$pid, now()->addMinutes(1440), function() use($pid) {
  1409. $following = Follower::whereProfileId($pid)->pluck('following_id');
  1410. return $following->push($pid)->toArray();
  1411. });
  1412. if($min || $max) {
  1413. $dir = $min ? '>' : '<';
  1414. $id = $min ?? $max;
  1415. $res = Status::select(
  1416. 'id',
  1417. 'profile_id',
  1418. 'type',
  1419. 'visibility',
  1420. 'created_at'
  1421. )
  1422. ->whereIn('type', ['photo', 'photo:album', 'video', 'video:album', 'photo:video:album'])
  1423. ->where('id', $dir, $id)
  1424. ->whereIn('profile_id', $following)
  1425. ->whereIn('visibility',['public', 'unlisted', 'private'])
  1426. ->latest()
  1427. ->take($limit)
  1428. ->get()
  1429. ->map(function($s) use($pid) {
  1430. $status = StatusService::getMastodon($s['id']);
  1431. if(!$status || !isset($status['account']) || !isset($status['account']['id'])) {
  1432. return false;
  1433. }
  1434. if($pid) {
  1435. $status['favourited'] = (bool) LikeService::liked($pid, $s['id']);
  1436. $status['reblogged'] = (bool) ReblogService::get($pid, $status['id']);
  1437. }
  1438. return $status;
  1439. })
  1440. ->filter(function($status) {
  1441. return $status && isset($status['account']);
  1442. })
  1443. ->values()
  1444. ->toArray();
  1445. } else {
  1446. $res = Status::select(
  1447. 'id',
  1448. 'profile_id',
  1449. 'type',
  1450. 'visibility',
  1451. 'created_at'
  1452. )
  1453. ->whereIn('type', ['photo', 'photo:album', 'video', 'video:album', 'photo:video:album'])
  1454. ->whereIn('profile_id', $following)
  1455. ->whereIn('visibility',['public', 'unlisted', 'private'])
  1456. ->latest()
  1457. ->take($limit)
  1458. ->get()
  1459. ->map(function($s) use($pid) {
  1460. $status = StatusService::getMastodon($s['id']);
  1461. if(!$status || !isset($status['account']) || !isset($status['account']['id'])) {
  1462. return false;
  1463. }
  1464. if($pid) {
  1465. $status['favourited'] = (bool) LikeService::liked($pid, $s['id']);
  1466. $status['reblogged'] = (bool) ReblogService::get($pid, $status['id']);
  1467. }
  1468. return $status;
  1469. })
  1470. ->filter(function($status) {
  1471. return $status && isset($status['account']);
  1472. })
  1473. ->values()
  1474. ->toArray();
  1475. }
  1476. return $this->json($res);
  1477. }
  1478. /**
  1479. * GET /api/v1/conversations
  1480. *
  1481. * Not implemented
  1482. *
  1483. * @return array
  1484. */
  1485. public function conversations(Request $request)
  1486. {
  1487. abort_if(!$request->user(), 403);
  1488. $this->validate($request, [
  1489. 'limit' => 'min:1|max:40',
  1490. 'scope' => 'nullable|in:inbox,sent,requests'
  1491. ]);
  1492. $limit = $request->input('limit', 20);
  1493. $scope = $request->input('scope', 'inbox');
  1494. $pid = $request->user()->profile_id;
  1495. if(config('database.default') == 'pgsql') {
  1496. $dms = DirectMessage::when($scope === 'inbox', function($q, $scope) use($pid) {
  1497. return $q->whereIsHidden(false)->whereToId($pid)->orWhere('from_id', $pid);
  1498. })
  1499. ->when($scope === 'sent', function($q, $scope) use($pid) {
  1500. return $q->whereFromId($pid);
  1501. })
  1502. ->when($scope === 'requests', function($q, $scope) use($pid) {
  1503. return $q->whereToId($pid)->whereIsHidden(true);
  1504. });
  1505. } else {
  1506. $dms = DirectMessage::when($scope === 'inbox', function($q, $scope) use($pid) {
  1507. return $q->whereIsHidden(false)->whereToId($pid)->orWhere('from_id', $pid)->groupBy('to_id');
  1508. })
  1509. ->when($scope === 'sent', function($q, $scope) use($pid) {
  1510. return $q->whereFromId($pid)->groupBy('to_id');
  1511. })
  1512. ->when($scope === 'requests', function($q, $scope) use($pid) {
  1513. return $q->whereToId($pid)->whereIsHidden(true);
  1514. });
  1515. }
  1516. $dms = $dms->latest()
  1517. ->simplePaginate($limit)
  1518. ->map(function($dm) use($pid) {
  1519. $from = $pid == $dm->to_id ? $dm->from_id : $dm->to_id;
  1520. $res = [
  1521. 'id' => $dm->id,
  1522. 'unread' => false,
  1523. 'accounts' => [
  1524. AccountService::getMastodon($from)
  1525. ],
  1526. 'last_status' => StatusService::getDirectMessage($dm->status_id)
  1527. ];
  1528. return $res;
  1529. })
  1530. ->filter(function($dm) {
  1531. return isset($dm['accounts']) && count($dm['accounts']);
  1532. })
  1533. ->unique(function($item, $key) {
  1534. return $item['accounts'][0]['id'];
  1535. })
  1536. ->values();
  1537. return $this->json($dms);
  1538. }
  1539. /**
  1540. * GET /api/v1/timelines/public
  1541. *
  1542. *
  1543. * @return StatusTransformer
  1544. */
  1545. public function timelinePublic(Request $request)
  1546. {
  1547. $this->validate($request,[
  1548. 'min_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  1549. 'max_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  1550. 'limit' => 'nullable|integer|max:80'
  1551. ]);
  1552. $min = $request->input('min_id');
  1553. $max = $request->input('max_id');
  1554. $limit = $request->input('limit') ?? 3;
  1555. $user = $request->user();
  1556. $filtered = $user ? UserFilterService::filters($user->profile_id) : [];
  1557. Cache::remember('api:v1:timelines:public:cache_check', 10368000, function() {
  1558. if(PublicTimelineService::count() == 0) {
  1559. PublicTimelineService::warmCache(true, 400);
  1560. }
  1561. });
  1562. if ($max) {
  1563. $feed = PublicTimelineService::getRankedMaxId($max, $limit);
  1564. } else if ($min) {
  1565. $feed = PublicTimelineService::getRankedMinId($min, $limit);
  1566. } else {
  1567. $feed = PublicTimelineService::get(0, $limit);
  1568. }
  1569. $res = collect($feed)
  1570. ->map(function($k) use($user) {
  1571. $status = StatusService::getMastodon($k);
  1572. if(!$status || !isset($status['account']) || !isset($status['account']['id'])) {
  1573. return false;
  1574. }
  1575. if($user) {
  1576. $status['favourited'] = (bool) LikeService::liked($user->profile_id, $k);
  1577. $status['reblogged'] = (bool) ReblogService::get($user->profile_id, $status['id']);
  1578. }
  1579. return $status;
  1580. })
  1581. ->filter(function($s) use($filtered) {
  1582. return $s && isset($s['account']) && in_array($s['account']['id'], $filtered) == false;
  1583. })
  1584. ->values()
  1585. ->toArray();
  1586. return $this->json($res);
  1587. }
  1588. /**
  1589. * GET /api/v1/statuses/{id}
  1590. *
  1591. * @param integer $id
  1592. *
  1593. * @return StatusTransformer
  1594. */
  1595. public function statusById(Request $request, $id)
  1596. {
  1597. abort_if(!$request->user(), 403);
  1598. $user = $request->user();
  1599. $res = StatusService::getMastodon($id, false);
  1600. if(!$res || !isset($res['visibility'])) {
  1601. abort(404);
  1602. }
  1603. $scope = $res['visibility'];
  1604. if(!in_array($scope, ['public', 'unlisted'])) {
  1605. if($scope === 'private') {
  1606. if($res['account']['id'] != $user->profile_id) {
  1607. abort_unless(FollowerService::follows($user->profile_id, $res['account']['id']), 403);
  1608. }
  1609. } else {
  1610. abort(400, 'Invalid request');
  1611. }
  1612. }
  1613. $res['favourited'] = LikeService::liked($user->profile_id, $res['id']);
  1614. $res['reblogged'] = ReblogService::get($user->profile_id, $res['id']);
  1615. return $this->json($res);
  1616. }
  1617. /**
  1618. * GET /api/v1/statuses/{id}/context
  1619. *
  1620. * @param integer $id
  1621. *
  1622. * @return StatusTransformer
  1623. */
  1624. public function statusContext(Request $request, $id)
  1625. {
  1626. abort_if(!$request->user(), 403);
  1627. $user = $request->user();
  1628. $status = Status::findOrFail($id);
  1629. if($status->profile_id !== $user->profile_id) {
  1630. if($status->scope == 'private') {
  1631. abort_if(!FollowerService::follows($user->profile_id, $status->profile_id), 403);
  1632. } else {
  1633. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  1634. }
  1635. }
  1636. if($status->comments_disabled) {
  1637. $res = [
  1638. 'ancestors' => [],
  1639. 'descendants' => []
  1640. ];
  1641. } else {
  1642. $ancestors = $status->parent();
  1643. if($ancestors) {
  1644. $ares = new Fractal\Resource\Item($ancestors, new StatusTransformer());
  1645. $ancestors = [
  1646. $this->fractal->createData($ares)->toArray()
  1647. ];
  1648. } else {
  1649. $ancestors = [];
  1650. }
  1651. $descendants = Status::whereInReplyToId($id)->latest()->limit(20)->get();
  1652. $dres = new Fractal\Resource\Collection($descendants, new StatusTransformer());
  1653. $descendants = $this->fractal->createData($dres)->toArray();
  1654. $res = [
  1655. 'ancestors' => $ancestors,
  1656. 'descendants' => $descendants
  1657. ];
  1658. }
  1659. return $this->json($res);
  1660. }
  1661. /**
  1662. * GET /api/v1/statuses/{id}/card
  1663. *
  1664. * @param integer $id
  1665. *
  1666. * @return StatusTransformer
  1667. */
  1668. public function statusCard(Request $request, $id)
  1669. {
  1670. abort_if(!$request->user(), 403);
  1671. $res = [];
  1672. return response()->json($res);
  1673. }
  1674. /**
  1675. * GET /api/v1/statuses/{id}/reblogged_by
  1676. *
  1677. * @param integer $id
  1678. *
  1679. * @return AccountTransformer
  1680. */
  1681. public function statusRebloggedBy(Request $request, $id)
  1682. {
  1683. abort_if(!$request->user(), 403);
  1684. $this->validate($request, [
  1685. 'page' => 'nullable|integer|min:1|max:40',
  1686. 'limit' => 'nullable|integer|min:1|max:80'
  1687. ]);
  1688. $limit = $request->input('limit') ?? 40;
  1689. $user = $request->user();
  1690. $status = Status::findOrFail($id);
  1691. if($status->profile_id !== $user->profile_id) {
  1692. if($status->scope == 'private') {
  1693. abort_if(!FollowerService::follows($user->profile_id, $status->profile_id), 403);
  1694. } else {
  1695. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  1696. }
  1697. }
  1698. $page = $request->input('page', 1);
  1699. $start = $page == 1 ? 0 : (($page * $limit) - $limit);
  1700. $end = $start + $limit - 1;
  1701. $ids = ReblogService::getPostReblogs($id, $start, $end);
  1702. if(empty($ids)) {
  1703. return [];
  1704. }
  1705. $res = collect($ids)
  1706. ->map(function($id) {
  1707. $status = StatusService::get($id);
  1708. if($status) {
  1709. return AccountService::get($status['account']['id']);
  1710. }
  1711. return;
  1712. })
  1713. ->filter(function($account) {
  1714. return $account && isset($account['id']);
  1715. })
  1716. ->values();
  1717. $url = $request->url();
  1718. $page = $request->input('page', 1);
  1719. $next = $page < 40 ? $page + 1 : 40;
  1720. $prev = $page > 1 ? $page - 1 : 1;
  1721. $links = '<'.$url.'?page='.$next.'&limit='.$limit.'>; rel="next", <'.$url.'?page='.$prev.'&limit='.$limit.'>; rel="prev"';
  1722. return $this->json($res, 200, ['Link' => $links]);
  1723. }
  1724. /**
  1725. * GET /api/v1/statuses/{id}/favourited_by
  1726. *
  1727. * @param integer $id
  1728. *
  1729. * @return AccountTransformer
  1730. */
  1731. public function statusFavouritedBy(Request $request, $id)
  1732. {
  1733. abort_if(!$request->user(), 403);
  1734. $this->validate($request, [
  1735. 'page' => 'nullable|integer|min:1|max:40',
  1736. 'limit' => 'nullable|integer|min:1|max:80'
  1737. ]);
  1738. $page = $request->input('page', 1);
  1739. $limit = $request->input('limit') ?? 40;
  1740. $user = $request->user();
  1741. $status = Status::findOrFail($id);
  1742. $offset = $page == 1 ? 0 : ($page * $limit - $limit);
  1743. if($offset > 100) {
  1744. if($user->profile_id != $status->profile_id) {
  1745. return [];
  1746. }
  1747. }
  1748. if($status->profile_id !== $user->profile_id) {
  1749. if($status->scope == 'private') {
  1750. abort_if(!$status->profile->followedBy($user->profile), 403);
  1751. } else {
  1752. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  1753. }
  1754. }
  1755. $res = DB::table('likes')
  1756. ->select('likes.id', 'likes.profile_id', 'likes.status_id', 'followers.created_at')
  1757. ->leftJoin('followers', function($join) use($user, $status) {
  1758. return $join->on('likes.profile_id', '=', 'followers.following_id')
  1759. ->where('followers.profile_id', $user->profile_id)
  1760. ->where('likes.status_id', $status->id);
  1761. })
  1762. ->whereStatusId($status->id)
  1763. ->orderByDesc('followers.created_at')
  1764. ->offset($offset)
  1765. ->limit($limit)
  1766. ->get()
  1767. ->map(function($like) {
  1768. $account = AccountService::getMastodon($like->profile_id);
  1769. $account['follows'] = isset($like->created_at);
  1770. return $account;
  1771. })
  1772. ->filter(function($account) use($user) {
  1773. return $account && isset($account['id']) && $account['id'] != $user->profile_id;
  1774. })
  1775. ->values();
  1776. $url = $request->url();
  1777. $page = $request->input('page', 1);
  1778. $next = $page < 40 ? $page + 1 : 40;
  1779. $prev = $page > 1 ? $page - 1 : 1;
  1780. $links = '<'.$url.'?page='.$next.'&limit='.$limit.'>; rel="next", <'.$url.'?page='.$prev.'&limit='.$limit.'>; rel="prev"';
  1781. return $this->json($res, 200, ['Link' => $links]);
  1782. }
  1783. /**
  1784. * POST /api/v1/statuses
  1785. *
  1786. *
  1787. * @return StatusTransformer
  1788. */
  1789. public function statusCreate(Request $request)
  1790. {
  1791. abort_if(!$request->user(), 403);
  1792. $this->validate($request, [
  1793. 'status' => 'nullable|string',
  1794. 'in_reply_to_id' => 'nullable',
  1795. 'media_ids' => 'array|max:' . config_cache('pixelfed.max_album_length'),
  1796. 'media_ids.*' => 'integer|min:1',
  1797. 'sensitive' => 'nullable|boolean',
  1798. 'visibility' => 'string|in:private,unlisted,public',
  1799. ]);
  1800. if(config('costar.enabled') == true) {
  1801. $blockedKeywords = config('costar.keyword.block');
  1802. if($blockedKeywords !== null && $request->status) {
  1803. $keywords = config('costar.keyword.block');
  1804. foreach($keywords as $kw) {
  1805. if(Str::contains($request->status, $kw) == true) {
  1806. abort(400, 'Invalid object. Contains banned keyword.');
  1807. }
  1808. }
  1809. }
  1810. }
  1811. if(!$request->filled('media_ids') && !$request->filled('in_reply_to_id')) {
  1812. abort(403, 'Empty statuses are not allowed');
  1813. }
  1814. $ids = $request->input('media_ids');
  1815. $in_reply_to_id = $request->input('in_reply_to_id');
  1816. $user = $request->user();
  1817. $profile = $user->profile;
  1818. $limitKey = 'compose:rate-limit:store:' . $user->id;
  1819. $limitTtl = now()->addMinutes(15);
  1820. $limitReached = Cache::remember($limitKey, $limitTtl, function() use($user) {
  1821. $dailyLimit = Status::whereProfileId($user->profile_id)
  1822. ->whereNull('in_reply_to_id')
  1823. ->whereNull('reblog_of_id')
  1824. ->where('created_at', '>', now()->subDays(1))
  1825. ->count();
  1826. return $dailyLimit >= 100;
  1827. });
  1828. abort_if($limitReached == true, 429);
  1829. $visibility = $profile->is_private ? 'private' : (
  1830. $profile->unlisted == true &&
  1831. $request->input('visibility', 'public') == 'public' ?
  1832. 'unlisted' :
  1833. $request->input('visibility', 'public'));
  1834. if($user->last_active_at == null) {
  1835. return [];
  1836. }
  1837. $content = strip_tags($request->input('status'));
  1838. $rendered = Autolink::create()->autolink($content);
  1839. if($in_reply_to_id) {
  1840. $parent = Status::findOrFail($in_reply_to_id);
  1841. $status = new Status;
  1842. $status->caption = $content;
  1843. $status->rendered = $rendered;
  1844. $status->scope = $visibility;
  1845. $status->visibility = $visibility;
  1846. $status->profile_id = $user->profile_id;
  1847. $status->is_nsfw = $user->profile->cw == true ? true : $request->input('sensitive', false);
  1848. $status->in_reply_to_id = $parent->id;
  1849. $status->in_reply_to_profile_id = $parent->profile_id;
  1850. $status->save();
  1851. StatusService::del($parent->id);
  1852. Cache::forget('status:replies:all:' . $parent->id);
  1853. }
  1854. if($ids) {
  1855. if(Media::whereUserId($user->id)
  1856. ->whereNull('status_id')
  1857. ->find($ids)
  1858. ->count() == 0
  1859. ) {
  1860. abort(400, 'Invalid media_ids');
  1861. }
  1862. if(!$in_reply_to_id) {
  1863. $status = new Status;
  1864. $status->caption = $content;
  1865. $status->rendered = $rendered;
  1866. $status->profile_id = $user->profile_id;
  1867. $status->scope = 'draft';
  1868. $status->is_nsfw = $user->profile->cw == true ? true : $request->input('sensitive', false);
  1869. $status->save();
  1870. }
  1871. $mimes = [];
  1872. foreach($ids as $k => $v) {
  1873. if($k + 1 > config_cache('pixelfed.max_album_length')) {
  1874. continue;
  1875. }
  1876. $m = Media::whereUserId($user->id)->whereNull('status_id')->findOrFail($v);
  1877. if($m->profile_id !== $user->profile_id || $m->status_id) {
  1878. abort(403, 'Invalid media id');
  1879. }
  1880. $m->status_id = $status->id;
  1881. $m->save();
  1882. array_push($mimes, $m->mime);
  1883. }
  1884. if(empty($mimes)) {
  1885. $status->delete();
  1886. abort(400, 'Invalid media ids');
  1887. }
  1888. $status->scope = $visibility;
  1889. $status->visibility = $visibility;
  1890. $status->type = StatusController::mimeTypeCheck($mimes);
  1891. $status->save();
  1892. }
  1893. if(!$status) {
  1894. abort(500, 'An error occured.');
  1895. }
  1896. NewStatusPipeline::dispatch($status);
  1897. if($status->in_reply_to_id) {
  1898. CommentPipeline::dispatch($parent, $status);
  1899. }
  1900. Cache::forget('user:account:id:'.$user->id);
  1901. Cache::forget('_api:statuses:recent_9:'.$user->profile_id);
  1902. Cache::forget('profile:status_count:'.$user->profile_id);
  1903. Cache::forget($user->storageUsedKey());
  1904. Cache::forget('profile:embed:' . $status->profile_id);
  1905. Cache::forget($limitKey);
  1906. $resource = new Fractal\Resource\Item($status, new StatusTransformer());
  1907. $res = $this->fractal->createData($resource)->toArray();
  1908. return $this->json($res);
  1909. }
  1910. /**
  1911. * DELETE /api/v1/statuses
  1912. *
  1913. * @param integer $id
  1914. *
  1915. * @return null
  1916. */
  1917. public function statusDelete(Request $request, $id)
  1918. {
  1919. abort_if(!$request->user(), 403);
  1920. $status = Status::whereProfileId($request->user()->profile->id)
  1921. ->findOrFail($id);
  1922. $resource = new Fractal\Resource\Item($status, new StatusTransformer());
  1923. Cache::forget('profile:status_count:'.$status->profile_id);
  1924. StatusDelete::dispatch($status);
  1925. $res = $this->fractal->createData($resource)->toArray();
  1926. $res['text'] = $res['content'];
  1927. unset($res['content']);
  1928. return $this->json($res);
  1929. }
  1930. /**
  1931. * POST /api/v1/statuses/{id}/reblog
  1932. *
  1933. * @param integer $id
  1934. *
  1935. * @return StatusTransformer
  1936. */
  1937. public function statusShare(Request $request, $id)
  1938. {
  1939. abort_if(!$request->user(), 403);
  1940. $user = $request->user();
  1941. $status = Status::whereScope('public')->findOrFail($id);
  1942. if($status->profile_id !== $user->profile_id) {
  1943. if($status->scope == 'private') {
  1944. abort_if(!FollowerService::follows($user->profile_id, $status->profile_id), 403);
  1945. } else {
  1946. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  1947. }
  1948. }
  1949. $share = Status::firstOrCreate([
  1950. 'profile_id' => $user->profile_id,
  1951. 'reblog_of_id' => $status->id,
  1952. 'type' => 'share',
  1953. 'in_reply_to_profile_id' => $status->profile_id,
  1954. 'scope' => 'public',
  1955. 'visibility' => 'public'
  1956. ]);
  1957. if($share->wasRecentlyCreated == true) {
  1958. SharePipeline::dispatch($share);
  1959. }
  1960. StatusService::del($status->id);
  1961. ReblogService::add($user->profile_id, $status->id);
  1962. $res = StatusService::getMastodon($status->id);
  1963. $res['reblogged'] = true;
  1964. return $this->json($res);
  1965. }
  1966. /**
  1967. * POST /api/v1/statuses/{id}/unreblog
  1968. *
  1969. * @param integer $id
  1970. *
  1971. * @return StatusTransformer
  1972. */
  1973. public function statusUnshare(Request $request, $id)
  1974. {
  1975. abort_if(!$request->user(), 403);
  1976. $user = $request->user();
  1977. $status = Status::whereScope('public')->findOrFail($id);
  1978. if($status->profile_id !== $user->profile_id) {
  1979. if($status->scope == 'private') {
  1980. abort_if(!FollowerService::follows($user->profile_id, $status->profile_id), 403);
  1981. } else {
  1982. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  1983. }
  1984. }
  1985. $reblog = Status::whereProfileId($user->profile_id)
  1986. ->whereReblogOfId($status->id)
  1987. ->first();
  1988. if(!$reblog) {
  1989. $resource = new Fractal\Resource\Item($status, new StatusTransformer());
  1990. $res = $this->fractal->createData($resource)->toArray();
  1991. return response()->json($res);
  1992. }
  1993. UndoSharePipeline::dispatch($reblog);
  1994. ReblogService::del($user->profile_id, $status->id);
  1995. $res = StatusService::getMastodon($status->id);
  1996. $res['reblogged'] = true;
  1997. return $this->json($res);
  1998. }
  1999. /**
  2000. * GET /api/v1/timelines/tag/{hashtag}
  2001. *
  2002. * @param string $hashtag
  2003. *
  2004. * @return StatusTransformer
  2005. */
  2006. public function timelineHashtag(Request $request, $hashtag)
  2007. {
  2008. $this->validate($request,[
  2009. 'page' => 'nullable|integer|max:40',
  2010. 'min_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  2011. 'max_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  2012. 'limit' => 'nullable|integer|max:40'
  2013. ]);
  2014. $tag = Hashtag::whereName($hashtag)
  2015. ->orWhere('slug', $hashtag)
  2016. ->first();
  2017. if(!$tag) {
  2018. return response()->json([]);
  2019. }
  2020. $min = $request->input('min_id');
  2021. $max = $request->input('max_id');
  2022. $limit = $request->input('limit', 20);
  2023. if(!$min && !$max) {
  2024. $id = 1;
  2025. $dir = '>';
  2026. } else {
  2027. $dir = $min ? '>' : '<';
  2028. $id = $min ?? $max;
  2029. }
  2030. $res = StatusHashtag::whereHashtagId($tag->id)
  2031. ->whereStatusVisibility('public')
  2032. ->whereHas('media')
  2033. ->where('status_id', $dir, $id)
  2034. ->latest()
  2035. ->limit($limit)
  2036. ->pluck('status_id')
  2037. ->filter(function($i) {
  2038. return StatusService::getMastodon($i);
  2039. })
  2040. ->map(function ($i) {
  2041. return StatusService::getMastodon($i);
  2042. })
  2043. ->filter()
  2044. ->values()
  2045. ->toArray();
  2046. return $this->json($res);
  2047. }
  2048. /**
  2049. * GET /api/v1/bookmarks
  2050. *
  2051. *
  2052. *
  2053. * @return StatusTransformer
  2054. */
  2055. public function bookmarks(Request $request)
  2056. {
  2057. abort_if(!$request->user(), 403);
  2058. $this->validate($request, [
  2059. 'limit' => 'nullable|integer|min:1|max:40',
  2060. 'max_id' => 'nullable|integer|min:0',
  2061. 'since_id' => 'nullable|integer|min:0',
  2062. 'min_id' => 'nullable|integer|min:0'
  2063. ]);
  2064. $pid = $request->user()->profile_id;
  2065. $limit = $request->input('limit') ?? 20;
  2066. $max_id = $request->input('max_id');
  2067. $since_id = $request->input('since_id');
  2068. $min_id = $request->input('min_id');
  2069. $dir = $min_id ? '>' : '<';
  2070. $id = $min_id ?? $max_id;
  2071. if($id) {
  2072. $bookmarks = Bookmark::whereProfileId($pid)
  2073. ->where('status_id', $dir, $id)
  2074. ->limit($limit)
  2075. ->pluck('status_id');
  2076. } else {
  2077. $bookmarks = Bookmark::whereProfileId($pid)
  2078. ->latest()
  2079. ->limit($limit)
  2080. ->pluck('status_id');
  2081. }
  2082. $res = [];
  2083. foreach($bookmarks as $id) {
  2084. $res[] = \App\Services\StatusService::getMastodon($id);
  2085. }
  2086. return $this->json($res);
  2087. }
  2088. /**
  2089. * POST /api/v1/statuses/{id}/bookmark
  2090. *
  2091. *
  2092. *
  2093. * @return StatusTransformer
  2094. */
  2095. public function bookmarkStatus(Request $request, $id)
  2096. {
  2097. abort_if(!$request->user(), 403);
  2098. $status = Status::whereNull('uri')
  2099. ->whereScope('public')
  2100. ->findOrFail($id);
  2101. Bookmark::firstOrCreate([
  2102. 'status_id' => $status->id,
  2103. 'profile_id' => $request->user()->profile_id
  2104. ]);
  2105. $resource = new Fractal\Resource\Item($status, new StatusTransformer());
  2106. $res = $this->fractal->createData($resource)->toArray();
  2107. return $this->json($res);
  2108. }
  2109. /**
  2110. * POST /api/v1/statuses/{id}/unbookmark
  2111. *
  2112. *
  2113. *
  2114. * @return StatusTransformer
  2115. */
  2116. public function unbookmarkStatus(Request $request, $id)
  2117. {
  2118. abort_if(!$request->user(), 403);
  2119. $status = Status::whereNull('uri')
  2120. ->whereScope('public')
  2121. ->findOrFail($id);
  2122. Bookmark::firstOrCreate([
  2123. 'status_id' => $status->id,
  2124. 'profile_id' => $request->user()->profile_id
  2125. ]);
  2126. $bookmark = Bookmark::whereStatusId($status->id)
  2127. ->whereProfileId($request->user()->profile_id)
  2128. ->firstOrFail();
  2129. $bookmark->delete();
  2130. $resource = new Fractal\Resource\Item($status, new StatusTransformer());
  2131. $res = $this->fractal->createData($resource)->toArray();
  2132. return $this->json($res);
  2133. }
  2134. /**
  2135. * GET /api/v2/search
  2136. *
  2137. *
  2138. * @return array
  2139. */
  2140. public function searchV2(Request $request)
  2141. {
  2142. abort_if(!$request->user(), 403);
  2143. $this->validate($request, [
  2144. 'q' => 'required|string|min:1|max:80',
  2145. 'account_id' => 'nullable|string',
  2146. 'max_id' => 'nullable|string',
  2147. 'min_id' => 'nullable|string',
  2148. 'type' => 'nullable|in:accounts,hashtags,statuses',
  2149. 'exclude_unreviewed' => 'nullable',
  2150. 'resolve' => 'nullable',
  2151. 'limit' => 'nullable|integer|max:40',
  2152. 'offset' => 'nullable|integer',
  2153. 'following' => 'nullable'
  2154. ]);
  2155. return $this->json(SearchApiV2Service::query($request));
  2156. }
  2157. /**
  2158. * GET /api/v1/discover/posts
  2159. *
  2160. *
  2161. * @return array
  2162. */
  2163. public function discoverPosts(Request $request)
  2164. {
  2165. abort_if(!$request->user(), 403);
  2166. $this->validate($request, [
  2167. 'limit' => 'integer|min:1|max:40'
  2168. ]);
  2169. $limit = $request->input('limit', 40);
  2170. $pid = $request->user()->profile_id;
  2171. $filters = UserFilterService::filters($pid);
  2172. $forYou = DiscoverService::getForYou();
  2173. $posts = $forYou->take(50)->map(function($post) {
  2174. return StatusService::getMastodon($post);
  2175. })
  2176. ->filter(function($post) use($filters) {
  2177. return $post &&
  2178. isset($post['account']) &&
  2179. isset($post['account']['id']) &&
  2180. !in_array($post['account']['id'], $filters);
  2181. })
  2182. ->take(12)
  2183. ->values();
  2184. return $this->json(compact('posts'));
  2185. }
  2186. /**
  2187. * GET /api/v2/statuses/{id}/replies
  2188. *
  2189. *
  2190. * @return array
  2191. */
  2192. public function statusReplies(Request $request, $id)
  2193. {
  2194. abort_if(!$request->user(), 403);
  2195. $this->validate($request, [
  2196. 'limit' => 'int|min:1|max:10',
  2197. 'sort' => 'in:all,newest,popular'
  2198. ]);
  2199. $limit = $request->input('limit', 3);
  2200. $pid = $request->user()->profile_id;
  2201. $status = StatusService::getMastodon($id, false);
  2202. abort_if(!$status, 404);
  2203. if($status['visibility'] == 'private') {
  2204. if($pid != $status['account']['id']) {
  2205. abort_unless(FollowerService::follows($pid, $status['account']['id']), 404);
  2206. }
  2207. }
  2208. $sortBy = $request->input('sort', 'all');
  2209. if($sortBy == 'all' && isset($status['replies_count']) && $status['replies_count'] && $request->has('refresh_cache')) {
  2210. if(!Cache::has('status:replies:all-rc:' . $id)) {
  2211. Cache::forget('status:replies:all:' . $id);
  2212. Cache::put('status:replies:all-rc:' . $id, true, 300);
  2213. }
  2214. }
  2215. if($sortBy == 'all' && !$request->has('cursor')) {
  2216. $ids = Cache::remember('status:replies:all:' . $id, 86400, function() use($id) {
  2217. return DB::table('statuses')
  2218. ->where('in_reply_to_id', $id)
  2219. ->orderBy('id')
  2220. ->cursorPaginate(3);
  2221. });
  2222. } else {
  2223. $ids = DB::table('statuses')
  2224. ->where('in_reply_to_id', $id)
  2225. ->when($sortBy, function($q, $sortBy) {
  2226. if($sortBy === 'all') {
  2227. return $q->orderBy('id');
  2228. }
  2229. if($sortBy === 'newest') {
  2230. return $q->orderByDesc('created_at');
  2231. }
  2232. if($sortBy === 'popular') {
  2233. return $q->orderByDesc('likes_count');
  2234. }
  2235. })
  2236. ->cursorPaginate($limit);
  2237. }
  2238. $data = $ids->map(function($post) use($pid) {
  2239. $status = StatusService::get($post->id, false);
  2240. if(!$status || !isset($status['id'])) {
  2241. return false;
  2242. }
  2243. $status['favourited'] = LikeService::liked($pid, $post->id);
  2244. return $status;
  2245. })
  2246. ->filter(function($post) {
  2247. return $post && isset($post['id']) && isset($post['account']);
  2248. })
  2249. ->values();
  2250. $res = [
  2251. 'data' => $data,
  2252. 'next' => $ids->nextPageUrl()
  2253. ];
  2254. return $this->json($res);
  2255. }
  2256. /**
  2257. * GET /api/v2/statuses/{id}/state
  2258. *
  2259. *
  2260. * @return array
  2261. */
  2262. public function statusState(Request $request, $id)
  2263. {
  2264. abort_if(!$request->user(), 403);
  2265. $status = Status::findOrFail($id);
  2266. $pid = $request->user()->profile_id;
  2267. abort_if(!in_array($status->scope, ['public', 'unlisted', 'private']), 404);
  2268. return $this->json(StatusService::getState($status->id, $pid));
  2269. }
  2270. /**
  2271. * GET /api/v1/discover/accounts/popular
  2272. *
  2273. *
  2274. * @return array
  2275. */
  2276. public function discoverAccountsPopular(Request $request)
  2277. {
  2278. abort_if(!$request->user(), 403);
  2279. $pid = $request->user()->profile_id;
  2280. $ids = DB::table('profiles')
  2281. ->where('is_private', false)
  2282. ->whereNull('status')
  2283. ->orderByDesc('profiles.followers_count')
  2284. ->limit(20)
  2285. ->get();
  2286. $ids = $ids->map(function($profile) {
  2287. return AccountService::getMastodon($profile->id);
  2288. })
  2289. ->filter(function($profile) use($pid) {
  2290. return $profile &&
  2291. isset($profile['id']) &&
  2292. !FollowerService::follows($pid, $profile['id']) &&
  2293. $profile['id'] != $pid;
  2294. })
  2295. ->take(6)
  2296. ->values();
  2297. return $this->json($ids);
  2298. }
  2299. }