ApiV1Controller.php 69 KB

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