ApiV1Controller.php 67 KB

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