1
0

ApiV1Controller.php 65 KB

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