ApiV1Controller.php 81 KB

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