ApiV1Controller.php 67 KB

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