ApiV1Controller.php 67 KB

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