ApiV1Controller.php 67 KB

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