ApiV1Controller.php 67 KB

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