ApiV1Controller.php 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462
  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. if($in_reply_to_id) {
  1777. $parent = Status::findOrFail($in_reply_to_id);
  1778. $status = new Status;
  1779. $status->caption = strip_tags($request->input('status'));
  1780. $status->scope = $visibility;
  1781. $status->visibility = $visibility;
  1782. $status->profile_id = $user->profile_id;
  1783. $status->is_nsfw = $user->profile->cw == true ? true : $request->input('sensitive', false);
  1784. $status->in_reply_to_id = $parent->id;
  1785. $status->in_reply_to_profile_id = $parent->profile_id;
  1786. $status->save();
  1787. StatusService::del($parent->id);
  1788. }
  1789. if($ids) {
  1790. if(Media::whereUserId($user->id)
  1791. ->whereNull('status_id')
  1792. ->find($ids)
  1793. ->count() == 0
  1794. ) {
  1795. abort(400, 'Invalid media_ids');
  1796. }
  1797. if(!$in_reply_to_id) {
  1798. $status = new Status;
  1799. $status->caption = strip_tags($request->input('status'));
  1800. $status->profile_id = $user->profile_id;
  1801. $status->scope = 'draft';
  1802. $status->is_nsfw = $user->profile->cw == true ? true : $request->input('sensitive', false);
  1803. $status->save();
  1804. }
  1805. $mimes = [];
  1806. foreach($ids as $k => $v) {
  1807. if($k + 1 > config_cache('pixelfed.max_album_length')) {
  1808. continue;
  1809. }
  1810. $m = Media::whereUserId($user->id)->whereNull('status_id')->findOrFail($v);
  1811. if($m->profile_id !== $user->profile_id || $m->status_id) {
  1812. abort(403, 'Invalid media id');
  1813. }
  1814. $m->status_id = $status->id;
  1815. $m->save();
  1816. array_push($mimes, $m->mime);
  1817. }
  1818. if(empty($mimes)) {
  1819. $status->delete();
  1820. abort(400, 'Invalid media ids');
  1821. }
  1822. $status->scope = $visibility;
  1823. $status->visibility = $visibility;
  1824. $status->type = StatusController::mimeTypeCheck($mimes);
  1825. $status->save();
  1826. }
  1827. if(!$status) {
  1828. abort(500, 'An error occured.');
  1829. }
  1830. NewStatusPipeline::dispatch($status);
  1831. if($status->in_reply_to_id) {
  1832. CommentPipeline::dispatch($parent, $status);
  1833. }
  1834. Cache::forget('user:account:id:'.$user->id);
  1835. Cache::forget('_api:statuses:recent_9:'.$user->profile_id);
  1836. Cache::forget('profile:status_count:'.$user->profile_id);
  1837. Cache::forget($user->storageUsedKey());
  1838. Cache::forget('profile:embed:' . $status->profile_id);
  1839. Cache::forget($limitKey);
  1840. $resource = new Fractal\Resource\Item($status, new StatusTransformer());
  1841. $res = $this->fractal->createData($resource)->toArray();
  1842. return response()->json($res);
  1843. }
  1844. /**
  1845. * DELETE /api/v1/statuses
  1846. *
  1847. * @param integer $id
  1848. *
  1849. * @return null
  1850. */
  1851. public function statusDelete(Request $request, $id)
  1852. {
  1853. abort_if(!$request->user(), 403);
  1854. $status = Status::whereProfileId($request->user()->profile->id)
  1855. ->findOrFail($id);
  1856. $resource = new Fractal\Resource\Item($status, new StatusTransformer());
  1857. Cache::forget('profile:status_count:'.$status->profile_id);
  1858. StatusDelete::dispatch($status);
  1859. $res = $this->fractal->createData($resource)->toArray();
  1860. $res['text'] = $res['content'];
  1861. unset($res['content']);
  1862. return response()->json($res);
  1863. }
  1864. /**
  1865. * POST /api/v1/statuses/{id}/reblog
  1866. *
  1867. * @param integer $id
  1868. *
  1869. * @return StatusTransformer
  1870. */
  1871. public function statusShare(Request $request, $id)
  1872. {
  1873. abort_if(!$request->user(), 403);
  1874. $user = $request->user();
  1875. $status = Status::findOrFail($id);
  1876. if($status->profile_id !== $user->profile_id) {
  1877. if($status->scope == 'private') {
  1878. abort_if(!$status->profile->followedBy($user->profile), 403);
  1879. } else {
  1880. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  1881. }
  1882. }
  1883. $share = Status::firstOrCreate([
  1884. 'profile_id' => $user->profile_id,
  1885. 'reblog_of_id' => $status->id,
  1886. 'in_reply_to_profile_id' => $status->profile_id,
  1887. 'scope' => 'public',
  1888. 'visibility' => 'public'
  1889. ]);
  1890. if($share->wasRecentlyCreated == true) {
  1891. SharePipeline::dispatch($share);
  1892. }
  1893. StatusService::del($status->id);
  1894. $resource = new Fractal\Resource\Item($status, new StatusTransformer());
  1895. $res = $this->fractal->createData($resource)->toArray();
  1896. return response()->json($res);
  1897. }
  1898. /**
  1899. * POST /api/v1/statuses/{id}/unreblog
  1900. *
  1901. * @param integer $id
  1902. *
  1903. * @return StatusTransformer
  1904. */
  1905. public function statusUnshare(Request $request, $id)
  1906. {
  1907. abort_if(!$request->user(), 403);
  1908. $user = $request->user();
  1909. $status = Status::findOrFail($id);
  1910. if($status->profile_id !== $user->profile_id) {
  1911. if($status->scope == 'private') {
  1912. abort_if(!$status->profile->followedBy($user->profile), 403);
  1913. } else {
  1914. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  1915. }
  1916. }
  1917. $reblog = Status::whereProfileId($user->profile_id)
  1918. ->whereReblogOfId($status->id)
  1919. ->first();
  1920. if(!$reblog) {
  1921. $resource = new Fractal\Resource\Item($status, new StatusTransformer());
  1922. $res = $this->fractal->createData($resource)->toArray();
  1923. return response()->json($res);
  1924. }
  1925. UndoSharePipeline::dispatch($reblog);
  1926. $resource = new Fractal\Resource\Item($status, new StatusTransformer());
  1927. $res = $this->fractal->createData($resource)->toArray();
  1928. $res['reblogged'] = false;
  1929. return response()->json($res);
  1930. }
  1931. /**
  1932. * GET /api/v1/timelines/tag/{hashtag}
  1933. *
  1934. * @param string $hashtag
  1935. *
  1936. * @return StatusTransformer
  1937. */
  1938. public function timelineHashtag(Request $request, $hashtag)
  1939. {
  1940. $this->validate($request,[
  1941. 'page' => 'nullable|integer|max:40',
  1942. 'min_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  1943. 'max_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  1944. 'limit' => 'nullable|integer|max:40'
  1945. ]);
  1946. $tag = Hashtag::whereName($hashtag)
  1947. ->orWhere('slug', $hashtag)
  1948. ->first();
  1949. if(!$tag) {
  1950. return response()->json([]);
  1951. }
  1952. $min = $request->input('min_id');
  1953. $max = $request->input('max_id');
  1954. $limit = $request->input('limit', 20);
  1955. if(!$min && !$max) {
  1956. $id = 1;
  1957. $dir = '>';
  1958. } else {
  1959. $dir = $min ? '>' : '<';
  1960. $id = $min ?? $max;
  1961. }
  1962. $res = StatusHashtag::whereHashtagId($tag->id)
  1963. ->whereStatusVisibility('public')
  1964. ->whereHas('media')
  1965. ->where('status_id', $dir, $id)
  1966. ->latest()
  1967. ->limit($limit)
  1968. ->pluck('status_id')
  1969. ->filter(function($i) {
  1970. return StatusService::get($i);
  1971. })
  1972. ->map(function ($i) {
  1973. return StatusService::get($i);
  1974. })
  1975. ->filter()
  1976. ->values()
  1977. ->toArray();
  1978. return response()->json($res, 200, [], JSON_PRETTY_PRINT);
  1979. }
  1980. /**
  1981. * GET /api/v1/bookmarks
  1982. *
  1983. *
  1984. *
  1985. * @return StatusTransformer
  1986. */
  1987. public function bookmarks(Request $request)
  1988. {
  1989. abort_if(!$request->user(), 403);
  1990. $this->validate($request, [
  1991. 'limit' => 'nullable|integer|min:1|max:40',
  1992. 'max_id' => 'nullable|integer|min:0',
  1993. 'since_id' => 'nullable|integer|min:0',
  1994. 'min_id' => 'nullable|integer|min:0'
  1995. ]);
  1996. $pid = $request->user()->profile_id;
  1997. $limit = $request->input('limit') ?? 20;
  1998. $max_id = $request->input('max_id');
  1999. $since_id = $request->input('since_id');
  2000. $min_id = $request->input('min_id');
  2001. $dir = $min_id ? '>' : '<';
  2002. $id = $min_id ?? $max_id;
  2003. if($id) {
  2004. $bookmarks = Bookmark::whereProfileId($pid)
  2005. ->where('status_id', $dir, $id)
  2006. ->limit($limit)
  2007. ->pluck('status_id');
  2008. } else {
  2009. $bookmarks = Bookmark::whereProfileId($pid)
  2010. ->latest()
  2011. ->limit($limit)
  2012. ->pluck('status_id');
  2013. }
  2014. $res = [];
  2015. foreach($bookmarks as $id) {
  2016. $res[] = \App\Services\StatusService::get($id);
  2017. }
  2018. return $res;
  2019. }
  2020. /**
  2021. * POST /api/v1/statuses/{id}/bookmark
  2022. *
  2023. *
  2024. *
  2025. * @return StatusTransformer
  2026. */
  2027. public function bookmarkStatus(Request $request, $id)
  2028. {
  2029. abort_if(!$request->user(), 403);
  2030. $status = Status::whereNull('uri')
  2031. ->whereScope('public')
  2032. ->findOrFail($id);
  2033. Bookmark::firstOrCreate([
  2034. 'status_id' => $status->id,
  2035. 'profile_id' => $request->user()->profile_id
  2036. ]);
  2037. $resource = new Fractal\Resource\Item($status, new StatusTransformer());
  2038. $res = $this->fractal->createData($resource)->toArray();
  2039. return response()->json($res);
  2040. }
  2041. /**
  2042. * POST /api/v1/statuses/{id}/unbookmark
  2043. *
  2044. *
  2045. *
  2046. * @return StatusTransformer
  2047. */
  2048. public function unbookmarkStatus(Request $request, $id)
  2049. {
  2050. abort_if(!$request->user(), 403);
  2051. $status = Status::whereNull('uri')
  2052. ->whereScope('public')
  2053. ->findOrFail($id);
  2054. Bookmark::firstOrCreate([
  2055. 'status_id' => $status->id,
  2056. 'profile_id' => $request->user()->profile_id
  2057. ]);
  2058. $bookmark = Bookmark::whereStatusId($status->id)
  2059. ->whereProfileId($request->user()->profile_id)
  2060. ->firstOrFail();
  2061. $bookmark->delete();
  2062. $resource = new Fractal\Resource\Item($status, new StatusTransformer());
  2063. $res = $this->fractal->createData($resource)->toArray();
  2064. return response()->json($res);
  2065. }
  2066. /**
  2067. * GET /api/v2/search
  2068. *
  2069. *
  2070. * @return array
  2071. */
  2072. public function searchV2(Request $request)
  2073. {
  2074. abort_if(!$request->user(), 403);
  2075. $this->validate($request, [
  2076. 'q' => 'required|string|min:1|max:80',
  2077. 'account_id' => 'nullable|string',
  2078. 'max_id' => 'nullable|string',
  2079. 'min_id' => 'nullable|string',
  2080. 'type' => 'nullable|in:accounts,hashtags,statuses',
  2081. 'exclude_unreviewed' => 'nullable',
  2082. 'resolve' => 'nullable',
  2083. 'limit' => 'nullable|integer|max:40',
  2084. 'offset' => 'nullable|integer',
  2085. 'following' => 'nullable'
  2086. ]);
  2087. return SearchApiV2Service::query($request);
  2088. }
  2089. /**
  2090. * GET /api/v1/discover/posts
  2091. *
  2092. *
  2093. * @return array
  2094. */
  2095. public function discoverPosts(Request $request)
  2096. {
  2097. abort_if(!$request->user(), 403);
  2098. $this->validate($request, [
  2099. 'limit' => 'integer|min:1|max:40'
  2100. ]);
  2101. $limit = $request->input('limit', 40);
  2102. $pid = $request->user()->profile_id;
  2103. $filters = UserFilterService::filters($pid);
  2104. $forYou = DiscoverService::getForYou();
  2105. $posts = $forYou->take(50)->map(function($post) {
  2106. return StatusService::get($post);
  2107. })
  2108. ->filter(function($post) use($filters) {
  2109. return $post &&
  2110. isset($post['account']) &&
  2111. isset($post['account']['id']) &&
  2112. !in_array($post['account']['id'], $filters);
  2113. })
  2114. ->take(12)
  2115. ->values();
  2116. return response()->json(compact('posts'));
  2117. }
  2118. }