ApiV1Controller.php 69 KB

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