ApiV1Controller.php 83 KB

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