ApiV1Controller.php 67 KB

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