ApiV1Controller.php 69 KB

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