ApiV1Controller.php 68 KB

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