1
0

ApiV1Controller.php 84 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230
  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, Storage, URL;
  10. use App\{
  11. Avatar,
  12. Bookmark,
  13. Collection,
  14. CollectionItem,
  15. DirectMessage,
  16. Follower,
  17. FollowRequest,
  18. Hashtag,
  19. Instance,
  20. Like,
  21. Media,
  22. Notification,
  23. Profile,
  24. Status,
  25. StatusHashtag,
  26. User,
  27. UserSetting,
  28. UserFilter,
  29. };
  30. use League\Fractal;
  31. use App\Transformer\Api\Mastodon\v1\{
  32. AccountTransformer,
  33. MediaTransformer,
  34. NotificationTransformer,
  35. StatusTransformer,
  36. };
  37. use App\Transformer\Api\{
  38. RelationshipTransformer,
  39. };
  40. use App\Http\Controllers\FollowerController;
  41. use League\Fractal\Serializer\ArraySerializer;
  42. use League\Fractal\Pagination\IlluminatePaginatorAdapter;
  43. use App\Http\Controllers\StatusController;
  44. use App\Jobs\AvatarPipeline\AvatarOptimize;
  45. use App\Jobs\CommentPipeline\CommentPipeline;
  46. use App\Jobs\LikePipeline\LikePipeline;
  47. use App\Jobs\SharePipeline\SharePipeline;
  48. use App\Jobs\SharePipeline\UndoSharePipeline;
  49. use App\Jobs\StatusPipeline\NewStatusPipeline;
  50. use App\Jobs\StatusPipeline\StatusDelete;
  51. use App\Jobs\FollowPipeline\FollowPipeline;
  52. use App\Jobs\ImageOptimizePipeline\ImageOptimize;
  53. use App\Jobs\VideoPipeline\{
  54. VideoOptimize,
  55. VideoPostProcess,
  56. VideoThumbnail
  57. };
  58. use App\Services\{
  59. AccountService,
  60. CollectionService,
  61. FollowerService,
  62. InstanceService,
  63. LikeService,
  64. NetworkTimelineService,
  65. NotificationService,
  66. MediaPathService,
  67. ProfileStatusService,
  68. PublicTimelineService,
  69. ReblogService,
  70. RelationshipService,
  71. SearchApiV2Service,
  72. StatusService,
  73. MediaBlocklistService,
  74. SnowflakeService,
  75. UserFilterService
  76. };
  77. use App\Util\Lexer\Autolink;
  78. use App\Util\Lexer\PrettyNumber;
  79. use App\Util\Localization\Localization;
  80. use App\Util\Media\License;
  81. use App\Jobs\MediaPipeline\MediaSyncLicensePipeline;
  82. use App\Services\DiscoverService;
  83. use App\Services\CustomEmojiService;
  84. use App\Services\MarkerService;
  85. use App\Models\Conversation;
  86. use App\Jobs\FollowPipeline\FollowAcceptPipeline;
  87. use App\Jobs\FollowPipeline\FollowRejectPipeline;
  88. class ApiV1Controller extends Controller
  89. {
  90. protected $fractal;
  91. const PF_API_ENTITY_KEY = "_pe";
  92. public function __construct()
  93. {
  94. $this->fractal = new Fractal\Manager();
  95. $this->fractal->setSerializer(new ArraySerializer());
  96. }
  97. public function json($res, $code = 200, $headers = [])
  98. {
  99. return response()->json($res, $code, $headers, JSON_UNESCAPED_SLASHES);
  100. }
  101. public function getWebsocketConfig()
  102. {
  103. return config('broadcasting.default') === 'pusher' ? [
  104. 'host' => config('broadcasting.connections.pusher.options.host'),
  105. 'port' => config('broadcasting.connections.pusher.options.port'),
  106. 'key' => config('broadcasting.connections.pusher.key'),
  107. 'cluster' => config('broadcasting.connections.pusher.options.cluster')
  108. ] : [];
  109. }
  110. public function getApp(Request $request)
  111. {
  112. if(!$request->user()) {
  113. return response('', 403);
  114. }
  115. $client = $request->user()->token()->client;
  116. $res = [
  117. 'name' => $client->name,
  118. 'website' => null,
  119. 'vapid_key' => null
  120. ];
  121. return $this->json($res);
  122. }
  123. public function apps(Request $request)
  124. {
  125. abort_if(!config_cache('pixelfed.oauth_enabled'), 404);
  126. $this->validate($request, [
  127. 'client_name' => 'required',
  128. 'redirect_uris' => 'required'
  129. ]);
  130. $uris = implode(',', explode('\n', $request->redirect_uris));
  131. $client = Passport::client()->forceFill([
  132. 'user_id' => null,
  133. 'name' => e($request->client_name),
  134. 'secret' => Str::random(40),
  135. 'redirect' => $uris,
  136. 'personal_access_client' => false,
  137. 'password_client' => false,
  138. 'revoked' => false,
  139. ]);
  140. $client->save();
  141. $res = [
  142. 'id' => (string) $client->id,
  143. 'name' => $client->name,
  144. 'website' => null,
  145. 'redirect_uri' => $client->redirect,
  146. 'client_id' => (string) $client->id,
  147. 'client_secret' => $client->secret,
  148. 'vapid_key' => null
  149. ];
  150. return $this->json($res, 200, [
  151. 'Access-Control-Allow-Origin' => '*'
  152. ]);
  153. }
  154. /**
  155. * GET /api/v1/accounts/verify_credentials
  156. *
  157. *
  158. * @return \App\Transformer\Api\AccountTransformer
  159. */
  160. public function verifyCredentials(Request $request)
  161. {
  162. $user = $request->user();
  163. abort_if(!$user, 403);
  164. abort_if($user->status != null, 403);
  165. $res = $request->has(self::PF_API_ENTITY_KEY) ? AccountService::get($user->profile_id) : AccountService::getMastodon($user->profile_id);
  166. $res['source'] = [
  167. 'privacy' => $res['locked'] ? 'private' : 'public',
  168. 'sensitive' => false,
  169. 'language' => $user->language ?? 'en',
  170. 'note' => strip_tags($res['note']),
  171. 'fields' => []
  172. ];
  173. return $this->json($res);
  174. }
  175. /**
  176. * GET /api/v1/accounts/{id}
  177. *
  178. * @param integer $id
  179. *
  180. * @return \App\Transformer\Api\AccountTransformer
  181. */
  182. public function accountById(Request $request, $id)
  183. {
  184. $res = $request->has(self::PF_API_ENTITY_KEY) ? AccountService::get($id, true) : AccountService::getMastodon($id, true);
  185. if(!$res) {
  186. return response()->json(['error' => 'Record not found'], 404);
  187. }
  188. return $this->json($res);
  189. }
  190. /**
  191. * PATCH /api/v1/accounts/update_credentials
  192. *
  193. * @return \App\Transformer\Api\AccountTransformer
  194. */
  195. public function accountUpdateCredentials(Request $request)
  196. {
  197. abort_if(!$request->user(), 403);
  198. $this->validate($request, [
  199. 'avatar' => 'sometimes|mimetypes:image/jpeg,image/png|min:10|max:' . config('pixelfed.max_avatar_size'),
  200. 'display_name' => 'nullable|string|max:30',
  201. 'note' => 'nullable|string|max:200',
  202. 'locked' => 'nullable',
  203. 'website' => 'nullable|string|max:120',
  204. // 'source.privacy' => 'nullable|in:unlisted,public,private',
  205. // 'source.sensitive' => 'nullable|boolean'
  206. ], [
  207. 'required' => 'The :attribute field is required.',
  208. 'avatar.mimetypes' => 'The file must be in jpeg or png format',
  209. 'avatar.max' => 'The :attribute exceeds the file size limit of ' . PrettyNumber::size(config('pixelfed.max_avatar_size'), true, false),
  210. ]);
  211. $user = $request->user();
  212. $profile = $user->profile;
  213. $settings = $user->settings;
  214. $changes = false;
  215. $other = array_merge(AccountService::defaultSettings()['other'], $settings->other ?? []);
  216. $syncLicenses = false;
  217. $licenseChanged = false;
  218. $composeSettings = array_merge(AccountService::defaultSettings()['compose_settings'], $settings->compose_settings ?? []);
  219. if($request->has('avatar')) {
  220. $av = Avatar::whereProfileId($profile->id)->first();
  221. if($av) {
  222. $currentAvatar = storage_path('app/'.$av->media_path);
  223. $file = $request->file('avatar');
  224. $path = "public/avatars/{$profile->id}";
  225. $name = strtolower(str_random(6)). '.' . $file->guessExtension();
  226. $request->file('avatar')->storeAs($path, $name);
  227. $av->media_path = "{$path}/{$name}";
  228. $av->save();
  229. Cache::forget("avatar:{$profile->id}");
  230. Cache::forget('user:account:id:'.$user->id);
  231. AvatarOptimize::dispatch($user->profile, $currentAvatar);
  232. }
  233. $changes = true;
  234. }
  235. if($request->has('source[language]')) {
  236. $lang = $request->input('source[language]');
  237. if(in_array($lang, Localization::languages())) {
  238. $user->language = $lang;
  239. $changes = true;
  240. $other['language'] = $lang;
  241. }
  242. }
  243. if($request->has('website')) {
  244. $website = $request->input('website');
  245. if($website != $profile->website) {
  246. if($website) {
  247. if(!strpos($website, '.')) {
  248. $website = null;
  249. }
  250. if($website && !strpos($website, '://')) {
  251. $website = 'https://' . $website;
  252. }
  253. $host = parse_url($website, PHP_URL_HOST);
  254. $bannedInstances = InstanceService::getBannedDomains();
  255. if(in_array($host, $bannedInstances)) {
  256. $website = null;
  257. }
  258. }
  259. $profile->website = $website ? $website : null;
  260. $changes = true;
  261. }
  262. }
  263. if($request->has('display_name')) {
  264. $displayName = $request->input('display_name');
  265. if($displayName !== $user->name) {
  266. $user->name = $displayName;
  267. $profile->name = $displayName;
  268. $changes = true;
  269. }
  270. }
  271. if($request->has('note')) {
  272. $note = $request->input('note');
  273. if($note !== strip_tags($profile->bio)) {
  274. $profile->bio = Autolink::create()->autolink(strip_tags($note));
  275. $changes = true;
  276. }
  277. }
  278. if($request->has('locked')) {
  279. $locked = $request->input('locked') == 'true';
  280. if($profile->is_private != $locked) {
  281. $profile->is_private = $locked;
  282. $changes = true;
  283. }
  284. }
  285. if($request->has('reduce_motion')) {
  286. $reduced = $request->input('reduce_motion');
  287. if($settings->reduce_motion != $reduced) {
  288. $settings->reduce_motion = $reduced;
  289. $changes = true;
  290. }
  291. }
  292. if($request->has('high_contrast_mode')) {
  293. $contrast = $request->input('high_contrast_mode');
  294. if($settings->high_contrast_mode != $contrast) {
  295. $settings->high_contrast_mode = $contrast;
  296. $changes = true;
  297. }
  298. }
  299. if($request->has('video_autoplay')) {
  300. $autoplay = $request->input('video_autoplay');
  301. if($settings->video_autoplay != $autoplay) {
  302. $settings->video_autoplay = $autoplay;
  303. $changes = true;
  304. }
  305. }
  306. if($request->has('license')) {
  307. $license = $request->input('license');
  308. abort_if(!in_array($license, License::keys()), 422, 'Invalid media license id');
  309. $syncLicenses = $request->input('sync_licenses') == true;
  310. abort_if($syncLicenses && Cache::get('pf:settings:mls_recently:'.$user->id) == 2, 422, 'You can only sync licenses twice per 24 hours');
  311. if($composeSettings['default_license'] != $license) {
  312. $composeSettings['default_license'] = $license;
  313. $licenseChanged = true;
  314. $changes = true;
  315. }
  316. }
  317. if($request->has('media_descriptions')) {
  318. $md = $request->input('media_descriptions') == true;
  319. if($composeSettings['media_descriptions'] != $md) {
  320. $composeSettings['media_descriptions'] = $md;
  321. $changes = true;
  322. }
  323. }
  324. if($request->has('crawlable')) {
  325. $crawlable = $request->input('crawlable');
  326. if($settings->crawlable != $crawlable) {
  327. $settings->crawlable = $crawlable;
  328. $changes = true;
  329. }
  330. }
  331. if($request->has('show_profile_follower_count')) {
  332. $show_profile_follower_count = $request->input('show_profile_follower_count');
  333. if($settings->show_profile_follower_count != $show_profile_follower_count) {
  334. $settings->show_profile_follower_count = $show_profile_follower_count;
  335. $changes = true;
  336. }
  337. }
  338. if($request->has('show_profile_following_count')) {
  339. $show_profile_following_count = $request->input('show_profile_following_count');
  340. if($settings->show_profile_following_count != $show_profile_following_count) {
  341. $settings->show_profile_following_count = $show_profile_following_count;
  342. $changes = true;
  343. }
  344. }
  345. if($request->has('public_dm')) {
  346. $public_dm = $request->input('public_dm');
  347. if($settings->public_dm != $public_dm) {
  348. $settings->public_dm = $public_dm;
  349. $changes = true;
  350. }
  351. }
  352. if($request->has('source[privacy]')) {
  353. $scope = $request->input('source[privacy]');
  354. if(in_array($scope, ['public', 'private', 'unlisted'])) {
  355. if($composeSettings['default_scope'] != $scope) {
  356. $composeSettings['default_scope'] = $profile->is_private ? 'private' : $scope;
  357. $changes = true;
  358. }
  359. }
  360. }
  361. if($request->has('disable_embeds')) {
  362. $disabledEmbeds = $request->input('disable_embeds');
  363. if($other['disable_embeds'] != $disabledEmbeds) {
  364. $other['disable_embeds'] = $disabledEmbeds;
  365. $changes = true;
  366. }
  367. }
  368. if($changes) {
  369. $settings->other = $other;
  370. $settings->compose_settings = $composeSettings;
  371. $settings->save();
  372. $user->save();
  373. $profile->save();
  374. Cache::forget('profile:settings:' . $profile->id);
  375. Cache::forget('user:account:id:' . $profile->user_id);
  376. Cache::forget('profile:follower_count:' . $profile->id);
  377. Cache::forget('profile:following_count:' . $profile->id);
  378. Cache::forget('profile:embed:' . $profile->id);
  379. Cache::forget('profile:compose:settings:' . $user->id);
  380. Cache::forget('profile:view:'.$user->username);
  381. AccountService::del($user->profile_id);
  382. }
  383. if($syncLicenses && $licenseChanged) {
  384. $key = 'pf:settings:mls_recently:'.$user->id;
  385. $val = Cache::has($key) ? 2 : 1;
  386. Cache::put($key, $val, 86400);
  387. MediaSyncLicensePipeline::dispatch($user->id, $request->input('license'));
  388. }
  389. if($request->has(self::PF_API_ENTITY_KEY)) {
  390. $res = AccountService::get($user->profile_id, true);
  391. } else {
  392. $res = AccountService::getMastodon($user->profile_id, true);
  393. $res['bio'] = strip_tags($res['note']);
  394. $res = array_merge($res, $other);
  395. }
  396. return $this->json($res);
  397. }
  398. /**
  399. * GET /api/v1/accounts/{id}/followers
  400. *
  401. * @param integer $id
  402. *
  403. * @return \App\Transformer\Api\AccountTransformer
  404. */
  405. public function accountFollowersById(Request $request, $id)
  406. {
  407. abort_if(!$request->user(), 403);
  408. $account = AccountService::get($id);
  409. abort_if(!$account, 404);
  410. $pid = $request->user()->profile_id;
  411. if(intval($pid) !== intval($account['id'])) {
  412. if($account['locked']) {
  413. if(!FollowerService::follows($pid, $account['id'])) {
  414. return [];
  415. }
  416. }
  417. if(AccountService::hiddenFollowers($id)) {
  418. return [];
  419. }
  420. if($request->has('page') && $request->page >= 5) {
  421. return [];
  422. }
  423. }
  424. $res = DB::table('followers')
  425. ->select('id', 'profile_id', 'following_id')
  426. ->whereFollowingId($account['id'])
  427. ->orderByDesc('id')
  428. ->simplePaginate(10)
  429. ->map(function($follower) {
  430. return AccountService::getMastodon($follower->profile_id);
  431. })
  432. ->filter(function($account) {
  433. return $account && isset($account['id']);
  434. })
  435. ->values()
  436. ->toArray();
  437. return $this->json($res);
  438. }
  439. /**
  440. * GET /api/v1/accounts/{id}/following
  441. *
  442. * @param integer $id
  443. *
  444. * @return \App\Transformer\Api\AccountTransformer
  445. */
  446. public function accountFollowingById(Request $request, $id)
  447. {
  448. abort_if(!$request->user(), 403);
  449. $account = AccountService::get($id);
  450. abort_if(!$account, 404);
  451. $pid = $request->user()->profile_id;
  452. if(intval($pid) !== intval($account['id'])) {
  453. if($account['locked']) {
  454. if(!FollowerService::follows($pid, $account['id'])) {
  455. return [];
  456. }
  457. }
  458. if(AccountService::hiddenFollowing($id)) {
  459. return [];
  460. }
  461. if($request->has('page') && $request->page >= 5) {
  462. return [];
  463. }
  464. }
  465. $res = DB::table('followers')
  466. ->select('id', 'profile_id', 'following_id')
  467. ->whereProfileId($account['id'])
  468. ->orderByDesc('id')
  469. ->simplePaginate(10)
  470. ->map(function($follower) {
  471. return AccountService::get($follower->following_id);
  472. })
  473. ->filter(function($account) {
  474. return $account && isset($account['id']);
  475. })
  476. ->values()
  477. ->toArray();
  478. return $this->json($res);
  479. }
  480. /**
  481. * GET /api/v1/accounts/{id}/statuses
  482. *
  483. * @param integer $id
  484. *
  485. * @return \App\Transformer\Api\StatusTransformer
  486. */
  487. public function accountStatusesById(Request $request, $id)
  488. {
  489. $user = $request->user();
  490. $this->validate($request, [
  491. 'only_media' => 'nullable',
  492. 'media_type' => 'sometimes|string|in:photo,video',
  493. 'pinned' => 'nullable',
  494. 'exclude_replies' => 'nullable',
  495. 'max_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  496. 'since_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  497. 'min_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  498. 'limit' => 'nullable|integer|min:1|max:100'
  499. ]);
  500. $napi = $request->has(self::PF_API_ENTITY_KEY);
  501. $profile = $napi ? AccountService::get($id, true) : AccountService::getMastodon($id, true);
  502. if(!$profile || !isset($profile['id']) || !$user) {
  503. return $this->json(['error' => 'Account not found'], 404);
  504. }
  505. $limit = $request->limit ?? 20;
  506. $max_id = $request->max_id;
  507. $min_id = $request->min_id;
  508. if(!$max_id && !$min_id) {
  509. $min_id = 1;
  510. }
  511. $pid = $request->user()->profile_id;
  512. $scope = $request->only_media == true ?
  513. ['photo', 'photo:album', 'video', 'video:album'] :
  514. ['photo', 'photo:album', 'video', 'video:album', 'share', 'reply'];
  515. if($request->only_media && $request->has('media_type')) {
  516. $mt = $request->input('media_type');
  517. if($mt == 'video') {
  518. $scope = ['video', 'video:album'];
  519. }
  520. }
  521. if(intval($pid) === intval($profile['id'])) {
  522. $visibility = ['public', 'unlisted', 'private'];
  523. } else if($profile['locked']) {
  524. $following = FollowerService::follows($pid, $profile['id']);
  525. if(!$following) {
  526. return response('', 403);
  527. }
  528. $visibility = ['public', 'unlisted', 'private'];
  529. } else {
  530. $following = FollowerService::follows($pid, $profile['id']);
  531. $visibility = $following ? ['public', 'unlisted', 'private'] : ['public', 'unlisted'];
  532. }
  533. $dir = $min_id ? '>' : '<';
  534. $id = $min_id ?? $max_id;
  535. $res = Status::whereProfileId($profile['id'])
  536. ->whereNull('in_reply_to_id')
  537. ->whereNull('reblog_of_id')
  538. ->whereIn('type', $scope)
  539. ->where('id', $dir, $id)
  540. ->whereIn('scope', $visibility)
  541. ->limit($limit)
  542. ->orderByDesc('id')
  543. ->get()
  544. ->map(function($s) use($user, $napi, $profile) {
  545. $status = $napi ? StatusService::get($s->id, false) : StatusService::getMastodon($s->id, false);
  546. if($profile) {
  547. $status['account'] = $profile;
  548. }
  549. if($user && $status) {
  550. $status['favourited'] = (bool) LikeService::liked($user->profile_id, $s->id);
  551. }
  552. return $status;
  553. })
  554. ->filter(function($s) {
  555. return $s;
  556. })
  557. ->values();
  558. return $this->json($res);
  559. }
  560. /**
  561. * POST /api/v1/accounts/{id}/follow
  562. *
  563. * @param integer $id
  564. *
  565. * @return \App\Transformer\Api\RelationshipTransformer
  566. */
  567. public function accountFollowById(Request $request, $id)
  568. {
  569. abort_if(!$request->user(), 403);
  570. $user = $request->user();
  571. $target = Profile::where('id', '!=', $user->profile_id)
  572. ->whereNull('status')
  573. ->findOrFail($id);
  574. $private = (bool) $target->is_private;
  575. $remote = (bool) $target->domain;
  576. $blocked = UserFilter::whereUserId($target->id)
  577. ->whereFilterType('block')
  578. ->whereFilterableId($user->profile_id)
  579. ->whereFilterableType('App\Profile')
  580. ->exists();
  581. if($blocked == true) {
  582. abort(400, 'You cannot follow this user.');
  583. }
  584. $isFollowing = Follower::whereProfileId($user->profile_id)
  585. ->whereFollowingId($target->id)
  586. ->exists();
  587. // Following already, return empty relationship
  588. if($isFollowing == true) {
  589. $res = RelationshipService::get($user->profile_id, $target->id) ?? [];
  590. return $this->json($res);
  591. }
  592. // Rate limits, max 7500 followers per account
  593. if($user->profile->following_count && $user->profile->following_count >= Follower::MAX_FOLLOWING) {
  594. abort(400, 'You cannot follow more than ' . Follower::MAX_FOLLOWING . ' accounts');
  595. }
  596. if($private == true) {
  597. $follow = FollowRequest::firstOrCreate([
  598. 'follower_id' => $user->profile_id,
  599. 'following_id' => $target->id
  600. ]);
  601. if($remote == true && config('federation.activitypub.remoteFollow') == true) {
  602. (new FollowerController())->sendFollow($user->profile, $target);
  603. }
  604. } else {
  605. $follower = Follower::firstOrCreate([
  606. 'profile_id' => $user->profile_id,
  607. 'following_id' => $target->id
  608. ]);
  609. if($remote == true && config('federation.activitypub.remoteFollow') == true) {
  610. (new FollowerController())->sendFollow($user->profile, $target);
  611. }
  612. FollowPipeline::dispatch($follower);
  613. $target->increment('followers_count');
  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. if($user->profile->following_count) {
  664. $user->profile->decrement('following_count');
  665. }
  666. FollowRequest::whereFollowerId($user->profile_id)
  667. ->whereFollowingId($target->id)
  668. ->delete();
  669. Follower::whereProfileId($user->profile_id)
  670. ->whereFollowingId($target->id)
  671. ->delete();
  672. FollowerService::remove($user->profile_id, $target->id);
  673. $target->decrement('followers_count');
  674. if($remote == true && config('federation.activitypub.remoteFollow') == true) {
  675. (new FollowerController())->sendUndoFollow($user->profile, $target);
  676. }
  677. RelationshipService::refresh($user->profile_id, $target->id);
  678. Cache::forget('profile:following:'.$target->id);
  679. Cache::forget('profile:followers:'.$target->id);
  680. Cache::forget('profile:following:'.$user->profile_id);
  681. Cache::forget('profile:followers:'.$user->profile_id);
  682. Cache::forget('api:local:exp:rec:'.$user->profile_id);
  683. Cache::forget('user:account:id:'.$target->user_id);
  684. Cache::forget('user:account:id:'.$user->id);
  685. Cache::forget('profile:follower_count:'.$target->id);
  686. Cache::forget('profile:follower_count:'.$user->profile_id);
  687. Cache::forget('profile:following_count:'.$target->id);
  688. Cache::forget('profile:following_count:'.$user->profile_id);
  689. AccountService::del($user->profile_id);
  690. AccountService::del($target->id);
  691. $res = RelationshipService::get($user->profile_id, $target->id);
  692. return $this->json($res);
  693. }
  694. /**
  695. * GET /api/v1/accounts/relationships
  696. *
  697. * @param array|integer $id
  698. *
  699. * @return \App\Services\RelationshipService
  700. */
  701. public function accountRelationshipsById(Request $request)
  702. {
  703. abort_if(!$request->user(), 403);
  704. $this->validate($request, [
  705. 'id' => 'required|array|min:1|max:20',
  706. 'id.*' => 'required|integer|min:1|max:' . PHP_INT_MAX
  707. ]);
  708. $pid = $request->user()->profile_id ?? $request->user()->profile->id;
  709. $res = collect($request->input('id'))
  710. ->filter(function($id) use($pid) {
  711. return intval($id) !== intval($pid);
  712. })
  713. ->map(function($id) use($pid) {
  714. return RelationshipService::get($pid, $id);
  715. });
  716. return $this->json($res);
  717. }
  718. /**
  719. * GET /api/v1/accounts/search
  720. *
  721. *
  722. *
  723. * @return \App\Transformer\Api\AccountTransformer
  724. */
  725. public function accountSearch(Request $request)
  726. {
  727. abort_if(!$request->user(), 403);
  728. $this->validate($request, [
  729. 'q' => 'required|string|min:1|max:255',
  730. 'limit' => 'nullable|integer|min:1|max:40',
  731. 'resolve' => 'nullable'
  732. ]);
  733. $user = $request->user();
  734. $query = $request->input('q');
  735. $limit = $request->input('limit') ?? 20;
  736. $resolve = (bool) $request->input('resolve', false);
  737. $q = '%' . $query . '%';
  738. $profiles = Cache::remember('api:v1:accounts:search:' . sha1($query) . ':limit:' . $limit, 86400, function() use($q, $limit) {
  739. return Profile::whereNull('status')
  740. ->where('username', 'like', $q)
  741. ->orWhere('name', 'like', $q)
  742. ->limit($limit)
  743. ->pluck('id')
  744. ->map(function($id) {
  745. return AccountService::getMastodon($id);
  746. })
  747. ->filter(function($account) {
  748. return $account && isset($account['id']);
  749. });
  750. });
  751. return $this->json($profiles);
  752. }
  753. /**
  754. * GET /api/v1/blocks
  755. *
  756. *
  757. *
  758. * @return \App\Transformer\Api\AccountTransformer
  759. */
  760. public function accountBlocks(Request $request)
  761. {
  762. abort_if(!$request->user(), 403);
  763. $this->validate($request, [
  764. 'limit' => 'nullable|integer|min:1|max:40',
  765. 'page' => 'nullable|integer|min:1|max:10'
  766. ]);
  767. $user = $request->user();
  768. $limit = $request->input('limit') ?? 40;
  769. $blocked = UserFilter::select('filterable_id','filterable_type','filter_type','user_id')
  770. ->whereUserId($user->profile_id)
  771. ->whereFilterableType('App\Profile')
  772. ->whereFilterType('block')
  773. ->orderByDesc('id')
  774. ->simplePaginate($limit)
  775. ->pluck('filterable_id')
  776. ->map(function($id) {
  777. return AccountService::get($id, true);
  778. })
  779. ->filter(function($account) {
  780. return $account && isset($account['id']);
  781. })
  782. ->values();
  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)->onQueue('follow');
  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)->onQueue('follow');
  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' => config_cache('app.banner_image') ?? url(Storage::url('public/headers/default.jpg')),
  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. ->orderByDesc('id')
  1502. ->simplePaginate($limit)
  1503. ->pluck('filterable_id')
  1504. ->map(function($id) {
  1505. return AccountService::get($id, true);
  1506. })
  1507. ->filter(function($account) {
  1508. return $account && isset($account['id']);
  1509. })
  1510. ->values();
  1511. return $this->json($mutes);
  1512. }
  1513. /**
  1514. * POST /api/v1/accounts/{id}/mute
  1515. *
  1516. * @param integer $id
  1517. *
  1518. * @return RelationshipTransformer
  1519. */
  1520. public function accountMuteById(Request $request, $id)
  1521. {
  1522. abort_if(!$request->user(), 403);
  1523. $user = $request->user();
  1524. $pid = $user->profile_id;
  1525. if(intval($pid) === intval($id)) {
  1526. return $this->json(['error' => 'You cannot mute yourself'], 500);
  1527. }
  1528. $account = Profile::findOrFail($id);
  1529. $filter = UserFilter::firstOrCreate([
  1530. 'user_id' => $pid,
  1531. 'filterable_id' => $account->id,
  1532. 'filterable_type' => 'App\Profile',
  1533. 'filter_type' => 'mute',
  1534. ]);
  1535. Cache::forget("user:filter:list:$pid");
  1536. Cache::forget("feature:discover:posts:$pid");
  1537. Cache::forget("api:local:exp:rec:$pid");
  1538. RelationshipService::refresh($pid, $id);
  1539. $resource = new Fractal\Resource\Item($account, new RelationshipTransformer());
  1540. $res = $this->fractal->createData($resource)->toArray();
  1541. return $this->json($res);
  1542. }
  1543. /**
  1544. * POST /api/v1/accounts/{id}/unmute
  1545. *
  1546. * @param integer $id
  1547. *
  1548. * @return RelationshipTransformer
  1549. */
  1550. public function accountUnmuteById(Request $request, $id)
  1551. {
  1552. abort_if(!$request->user(), 403);
  1553. $user = $request->user();
  1554. $pid = $user->profile_id;
  1555. if(intval($pid) === intval($id)) {
  1556. return $this->json(['error' => 'You cannot unmute yourself'], 500);
  1557. }
  1558. $account = Profile::findOrFail($id);
  1559. $filter = UserFilter::whereUserId($pid)
  1560. ->whereFilterableId($account->id)
  1561. ->whereFilterableType('App\Profile')
  1562. ->whereFilterType('mute')
  1563. ->first();
  1564. if($filter) {
  1565. $filter->delete();
  1566. Cache::forget("user:filter:list:$pid");
  1567. Cache::forget("feature:discover:posts:$pid");
  1568. Cache::forget("api:local:exp:rec:$pid");
  1569. RelationshipService::refresh($pid, $id);
  1570. }
  1571. $resource = new Fractal\Resource\Item($account, new RelationshipTransformer());
  1572. $res = $this->fractal->createData($resource)->toArray();
  1573. return $this->json($res);
  1574. }
  1575. /**
  1576. * GET /api/v1/notifications
  1577. *
  1578. *
  1579. * @return NotificationTransformer
  1580. */
  1581. public function accountNotifications(Request $request)
  1582. {
  1583. abort_if(!$request->user(), 403);
  1584. $this->validate($request, [
  1585. 'limit' => 'nullable|integer|min:1|max:100',
  1586. 'min_id' => 'nullable|integer|min:1|max:'.PHP_INT_MAX,
  1587. 'max_id' => 'nullable|integer|min:1|max:'.PHP_INT_MAX,
  1588. 'since_id' => 'nullable|integer|min:1|max:'.PHP_INT_MAX,
  1589. ]);
  1590. $pid = $request->user()->profile_id;
  1591. $limit = $request->input('limit', 20);
  1592. $since = $request->input('since_id');
  1593. $min = $request->input('min_id');
  1594. $max = $request->input('max_id');
  1595. if(!$since && !$min && !$max) {
  1596. $min = 1;
  1597. }
  1598. $maxId = null;
  1599. $minId = null;
  1600. if($max) {
  1601. $res = NotificationService::getMaxMastodon($pid, $max, $limit);
  1602. $ids = NotificationService::getRankedMaxId($pid, $max, $limit);
  1603. if(!empty($ids)) {
  1604. $maxId = max($ids);
  1605. $minId = min($ids);
  1606. }
  1607. } else {
  1608. $res = NotificationService::getMinMastodon($pid, $min ?? $since, $limit);
  1609. $ids = NotificationService::getRankedMinId($pid, $min ?? $since, $limit);
  1610. if(!empty($ids)) {
  1611. $maxId = max($ids);
  1612. $minId = min($ids);
  1613. }
  1614. }
  1615. if(empty($res) && !Cache::has('pf:services:notifications:hasSynced:'.$pid)) {
  1616. Cache::put('pf:services:notifications:hasSynced:'.$pid, 1, 1209600);
  1617. NotificationService::warmCache($pid, 400, true);
  1618. }
  1619. $baseUrl = config('app.url') . '/api/v1/notifications?limit=' . $limit . '&';
  1620. if($minId == $maxId) {
  1621. $minId = null;
  1622. }
  1623. if($maxId) {
  1624. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next"';
  1625. }
  1626. if($minId) {
  1627. $link = '<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  1628. }
  1629. if($maxId && $minId) {
  1630. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next",<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  1631. }
  1632. $headers = isset($link) ? ['Link' => $link] : [];
  1633. return $this->json($res, 200, $headers);
  1634. }
  1635. /**
  1636. * GET /api/v1/timelines/home
  1637. *
  1638. *
  1639. * @return StatusTransformer
  1640. */
  1641. public function timelineHome(Request $request)
  1642. {
  1643. $this->validate($request,[
  1644. 'page' => 'nullable|integer|max:40',
  1645. 'min_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  1646. 'max_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  1647. 'limit' => 'nullable|integer|max:100'
  1648. ]);
  1649. $napi = $request->has(self::PF_API_ENTITY_KEY);
  1650. $page = $request->input('page');
  1651. $min = $request->input('min_id');
  1652. $max = $request->input('max_id');
  1653. $limit = $request->input('limit') ?? 20;
  1654. $pid = $request->user()->profile_id;
  1655. $following = Cache::remember('profile:following:'.$pid, now()->addMinutes(1440), function() use($pid) {
  1656. $following = Follower::whereProfileId($pid)->pluck('following_id');
  1657. return $following->push($pid)->toArray();
  1658. });
  1659. if($min || $max) {
  1660. $dir = $min ? '>' : '<';
  1661. $id = $min ?? $max;
  1662. $res = Status::select(
  1663. 'id',
  1664. 'profile_id',
  1665. 'type',
  1666. 'visibility',
  1667. 'created_at'
  1668. )
  1669. ->whereIn('type', ['photo', 'photo:album', 'video', 'video:album', 'photo:video:album'])
  1670. ->where('id', $dir, $id)
  1671. ->whereIn('profile_id', $following)
  1672. ->whereIn('visibility',['public', 'unlisted', 'private'])
  1673. ->latest()
  1674. ->take(($limit * 2))
  1675. ->get()
  1676. ->map(function($s) use($pid, $napi) {
  1677. $status = $napi ? StatusService::get($s['id'], false) : StatusService::getMastodon($s['id'], false);
  1678. if(!$status || !isset($status['account']) || !isset($status['account']['id'])) {
  1679. return false;
  1680. }
  1681. if($pid) {
  1682. $status['favourited'] = (bool) LikeService::liked($pid, $s['id']);
  1683. $status['reblogged'] = (bool) ReblogService::get($pid, $status['id']);
  1684. }
  1685. return $status;
  1686. })
  1687. ->filter(function($status) {
  1688. return $status && isset($status['account']);
  1689. })
  1690. ->take($limit)
  1691. ->values();
  1692. } else {
  1693. $res = Status::select(
  1694. 'id',
  1695. 'profile_id',
  1696. 'type',
  1697. 'visibility',
  1698. 'created_at'
  1699. )
  1700. ->whereIn('type', ['photo', 'photo:album', 'video', 'video:album', 'photo:video:album'])
  1701. ->whereIn('profile_id', $following)
  1702. ->whereIn('visibility',['public', 'unlisted', 'private'])
  1703. ->latest()
  1704. ->take(($limit * 2))
  1705. ->get()
  1706. ->map(function($s) use($pid, $napi) {
  1707. $status = $napi ? StatusService::get($s['id'], false) : StatusService::getMastodon($s['id'], false);
  1708. if(!$status || !isset($status['account']) || !isset($status['account']['id'])) {
  1709. return false;
  1710. }
  1711. if($pid) {
  1712. $status['favourited'] = (bool) LikeService::liked($pid, $s['id']);
  1713. $status['reblogged'] = (bool) ReblogService::get($pid, $status['id']);
  1714. }
  1715. return $status;
  1716. })
  1717. ->filter(function($status) {
  1718. return $status && isset($status['account']);
  1719. })
  1720. ->take($limit)
  1721. ->values();
  1722. }
  1723. $baseUrl = config('app.url') . '/api/v1/timelines/home?limit=' . $limit . '&';
  1724. $minId = $res->map(function($s) {
  1725. return ['id' => $s['id']];
  1726. })->min('id');
  1727. $maxId = $res->map(function($s) {
  1728. return ['id' => $s['id']];
  1729. })->max('id');
  1730. if($minId == $maxId) {
  1731. $minId = null;
  1732. }
  1733. if($maxId) {
  1734. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next"';
  1735. }
  1736. if($minId) {
  1737. $link = '<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  1738. }
  1739. if($maxId && $minId) {
  1740. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next",<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  1741. }
  1742. $headers = isset($link) ? ['Link' => $link] : [];
  1743. return $this->json($res->toArray(), 200, $headers);
  1744. }
  1745. /**
  1746. * GET /api/v1/timelines/public
  1747. *
  1748. *
  1749. * @return StatusTransformer
  1750. */
  1751. public function timelinePublic(Request $request)
  1752. {
  1753. $this->validate($request,[
  1754. 'min_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  1755. 'max_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  1756. 'limit' => 'nullable|integer|max:100',
  1757. 'remote' => 'sometimes',
  1758. 'local' => 'sometimes'
  1759. ]);
  1760. $napi = $request->has(self::PF_API_ENTITY_KEY);
  1761. $min = $request->input('min_id');
  1762. $max = $request->input('max_id');
  1763. $limit = $request->input('limit') ?? 20;
  1764. $user = $request->user();
  1765. $remote = ($request->has('remote') && $request->input('remote') == true) || ($request->filled('local') && $request->input('local') != true);
  1766. $filtered = $user ? UserFilterService::filters($user->profile_id) : [];
  1767. if((!$request->has('local') || $remote) && config('instance.timeline.network.cached')) {
  1768. Cache::remember('api:v1:timelines:network:cache_check', 10368000, function() {
  1769. if(NetworkTimelineService::count() == 0) {
  1770. NetworkTimelineService::warmCache(true, config('instance.timeline.network.cache_dropoff'));
  1771. }
  1772. });
  1773. if ($max) {
  1774. $feed = NetworkTimelineService::getRankedMaxId($max, $limit + 5);
  1775. } else if ($min) {
  1776. $feed = NetworkTimelineService::getRankedMinId($min, $limit + 5);
  1777. } else {
  1778. $feed = NetworkTimelineService::get(0, $limit + 5);
  1779. }
  1780. } else {
  1781. Cache::remember('api:v1:timelines:public:cache_check', 10368000, function() {
  1782. if(PublicTimelineService::count() == 0) {
  1783. PublicTimelineService::warmCache(true, 400);
  1784. }
  1785. });
  1786. if ($max) {
  1787. $feed = PublicTimelineService::getRankedMaxId($max, $limit + 5);
  1788. } else if ($min) {
  1789. $feed = PublicTimelineService::getRankedMinId($min, $limit + 5);
  1790. } else {
  1791. $feed = PublicTimelineService::get(0, $limit + 5);
  1792. }
  1793. }
  1794. $res = collect($feed)
  1795. ->filter(function($k) use($min, $max) {
  1796. if(!$min && !$max) {
  1797. return true;
  1798. }
  1799. if($min) {
  1800. return $min != $k;
  1801. }
  1802. if($max) {
  1803. return $max != $k;
  1804. }
  1805. })
  1806. ->map(function($k) use($user, $napi) {
  1807. $status = $napi ? StatusService::get($k) : StatusService::getMastodon($k);
  1808. if(!$status || !isset($status['account']) || !isset($status['account']['id'])) {
  1809. return false;
  1810. }
  1811. if($user) {
  1812. $status['favourited'] = (bool) LikeService::liked($user->profile_id, $k);
  1813. $status['reblogged'] = (bool) ReblogService::get($user->profile_id, $status['id']);
  1814. }
  1815. return $status;
  1816. })
  1817. ->filter(function($s) use($filtered) {
  1818. return $s && isset($s['account']) && in_array($s['account']['id'], $filtered) == false;
  1819. })
  1820. ->take($limit)
  1821. ->values();
  1822. $baseUrl = config('app.url') . '/api/v1/timelines/public?limit=' . $limit . '&';
  1823. if($remote) {
  1824. $baseUrl .= 'remote=1&';
  1825. }
  1826. $minId = $res->map(function($s) {
  1827. return ['id' => $s['id']];
  1828. })->min('id');
  1829. $maxId = $res->map(function($s) {
  1830. return ['id' => $s['id']];
  1831. })->max('id');
  1832. if($minId == $maxId) {
  1833. $minId = null;
  1834. }
  1835. if($maxId) {
  1836. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next"';
  1837. }
  1838. if($minId) {
  1839. $link = '<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  1840. }
  1841. if($maxId && $minId) {
  1842. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next",<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  1843. }
  1844. $headers = isset($link) ? ['Link' => $link] : [];
  1845. return $this->json($res->toArray(), 200, $headers);
  1846. }
  1847. /**
  1848. * GET /api/v1/conversations
  1849. *
  1850. * Not implemented
  1851. *
  1852. * @return array
  1853. */
  1854. public function conversations(Request $request)
  1855. {
  1856. abort_if(!$request->user(), 403);
  1857. $this->validate($request, [
  1858. 'limit' => 'min:1|max:40',
  1859. 'scope' => 'nullable|in:inbox,sent,requests'
  1860. ]);
  1861. $limit = $request->input('limit', 20);
  1862. $scope = $request->input('scope', 'inbox');
  1863. $pid = $request->user()->profile_id;
  1864. if(config('database.default') == 'pgsql') {
  1865. $dms = DirectMessage::when($scope === 'inbox', function($q, $scope) use($pid) {
  1866. return $q->whereIsHidden(false)->where('to_id', $pid)->orWhere('from_id', $pid);
  1867. })
  1868. ->when($scope === 'sent', function($q, $scope) use($pid) {
  1869. return $q->whereFromId($pid)->groupBy(['to_id', 'id']);
  1870. })
  1871. ->when($scope === 'requests', function($q, $scope) use($pid) {
  1872. return $q->whereToId($pid)->whereIsHidden(true);
  1873. });
  1874. } else {
  1875. $dms = Conversation::when($scope === 'inbox', function($q, $scope) use($pid) {
  1876. return $q->whereIsHidden(false)
  1877. ->where('to_id', $pid)
  1878. ->orWhere('from_id', $pid)
  1879. ->orderByDesc('status_id')
  1880. ->groupBy(['to_id', 'from_id']);
  1881. })
  1882. ->when($scope === 'sent', function($q, $scope) use($pid) {
  1883. return $q->whereFromId($pid)->groupBy('to_id');
  1884. })
  1885. ->when($scope === 'requests', function($q, $scope) use($pid) {
  1886. return $q->whereToId($pid)->whereIsHidden(true);
  1887. });
  1888. }
  1889. $dms = $dms->orderByDesc('status_id')
  1890. ->simplePaginate($limit)
  1891. ->map(function($dm) use($pid) {
  1892. $from = $pid == $dm->to_id ? $dm->from_id : $dm->to_id;
  1893. $res = [
  1894. 'id' => $dm->id,
  1895. 'unread' => false,
  1896. 'accounts' => [
  1897. AccountService::getMastodon($from)
  1898. ],
  1899. 'last_status' => StatusService::getDirectMessage($dm->status_id)
  1900. ];
  1901. return $res;
  1902. })
  1903. ->filter(function($dm) {
  1904. return isset($dm['accounts']) && count($dm['accounts']);
  1905. })
  1906. ->unique(function($item, $key) {
  1907. return $item['accounts'][0]['id'];
  1908. })
  1909. ->values();
  1910. return $this->json($dms);
  1911. }
  1912. /**
  1913. * GET /api/v1/statuses/{id}
  1914. *
  1915. * @param integer $id
  1916. *
  1917. * @return StatusTransformer
  1918. */
  1919. public function statusById(Request $request, $id)
  1920. {
  1921. abort_if(!$request->user(), 403);
  1922. $user = $request->user();
  1923. $res = $request->has(self::PF_API_ENTITY_KEY) ? StatusService::get($id, false) : StatusService::getMastodon($id, false);
  1924. if(!$res || !isset($res['visibility'])) {
  1925. abort(404);
  1926. }
  1927. $scope = $res['visibility'];
  1928. if(!in_array($scope, ['public', 'unlisted'])) {
  1929. if($scope === 'private') {
  1930. if(intval($res['account']['id']) !== intval($user->profile_id)) {
  1931. abort_unless(FollowerService::follows($user->profile_id, $res['account']['id']), 403);
  1932. }
  1933. } else {
  1934. abort(400, 'Invalid request');
  1935. }
  1936. }
  1937. $res['favourited'] = LikeService::liked($user->profile_id, $res['id']);
  1938. $res['reblogged'] = ReblogService::get($user->profile_id, $res['id']);
  1939. return $this->json($res);
  1940. }
  1941. /**
  1942. * GET /api/v1/statuses/{id}/context
  1943. *
  1944. * @param integer $id
  1945. *
  1946. * @return StatusTransformer
  1947. */
  1948. public function statusContext(Request $request, $id)
  1949. {
  1950. abort_if(!$request->user(), 403);
  1951. $user = $request->user();
  1952. $pid = $user->profile_id;
  1953. $status = StatusService::getMastodon($id, false);
  1954. if(!$status || !isset($status['account'])) {
  1955. return response('', 404);
  1956. }
  1957. if(intval($status['account']['id']) !== intval($user->profile_id)) {
  1958. if($status['visibility'] == 'private') {
  1959. if(!FollowerService::follows($user->profile_id, $status['account']['id'])) {
  1960. return response('', 404);
  1961. }
  1962. } else {
  1963. if(!in_array($status['visibility'], ['public','unlisted'])) {
  1964. return response('', 404);
  1965. }
  1966. }
  1967. }
  1968. $ancestors = [];
  1969. $descendants = [];
  1970. if($status['in_reply_to_id']) {
  1971. $ancestors[] = StatusService::getMastodon($status['in_reply_to_id'], false);
  1972. }
  1973. if($status['replies_count']) {
  1974. $descendants = DB::table('statuses')
  1975. ->where('in_reply_to_id', $id)
  1976. ->limit(20)
  1977. ->pluck('id')
  1978. ->map(function($sid) {
  1979. return StatusService::getMastodon($sid, false);
  1980. })
  1981. ->filter(function($post) {
  1982. return $post && isset($post['account']);
  1983. })
  1984. ->map(function($status) use($pid) {
  1985. $status['favourited'] = LikeService::liked($pid, $status['id']);
  1986. $status['reblogged'] = ReblogService::get($pid, $status['id']);
  1987. return $status;
  1988. })
  1989. ->values();
  1990. }
  1991. $res = [
  1992. 'ancestors' => $ancestors,
  1993. 'descendants' => $descendants
  1994. ];
  1995. return $this->json($res);
  1996. }
  1997. /**
  1998. * GET /api/v1/statuses/{id}/card
  1999. *
  2000. * @param integer $id
  2001. *
  2002. * @return StatusTransformer
  2003. */
  2004. public function statusCard(Request $request, $id)
  2005. {
  2006. abort_if(!$request->user(), 403);
  2007. $res = [];
  2008. return response()->json($res);
  2009. }
  2010. /**
  2011. * GET /api/v1/statuses/{id}/reblogged_by
  2012. *
  2013. * @param integer $id
  2014. *
  2015. * @return AccountTransformer
  2016. */
  2017. public function statusRebloggedBy(Request $request, $id)
  2018. {
  2019. abort_if(!$request->user(), 403);
  2020. $this->validate($request, [
  2021. 'page' => 'nullable|integer|min:1|max:40',
  2022. 'limit' => 'nullable|integer|min:1|max:100'
  2023. ]);
  2024. $limit = $request->input('limit') ?? 40;
  2025. $user = $request->user();
  2026. $status = Status::findOrFail($id);
  2027. if(intval($status->profile_id) !== intval($user->profile_id)) {
  2028. if($status->scope == 'private') {
  2029. abort_if(!FollowerService::follows($user->profile_id, $status->profile_id), 403);
  2030. } else {
  2031. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  2032. }
  2033. }
  2034. $page = $request->input('page', 1);
  2035. $start = $page == 1 ? 0 : (($page * $limit) - $limit);
  2036. $end = $start + $limit - 1;
  2037. $ids = ReblogService::getPostReblogs($id, $start, $end);
  2038. if(empty($ids)) {
  2039. return [];
  2040. }
  2041. $res = collect($ids)
  2042. ->map(function($id) {
  2043. $status = StatusService::get($id);
  2044. if($status) {
  2045. return AccountService::get($status['account']['id']);
  2046. }
  2047. return;
  2048. })
  2049. ->filter(function($account) {
  2050. return $account && isset($account['id']);
  2051. })
  2052. ->values();
  2053. $url = $request->url();
  2054. $page = $request->input('page', 1);
  2055. $next = $page < 40 ? $page + 1 : 40;
  2056. $prev = $page > 1 ? $page - 1 : 1;
  2057. $links = '<'.$url.'?page='.$next.'&limit='.$limit.'>; rel="next", <'.$url.'?page='.$prev.'&limit='.$limit.'>; rel="prev"';
  2058. return $this->json($res, 200, ['Link' => $links]);
  2059. }
  2060. /**
  2061. * GET /api/v1/statuses/{id}/favourited_by
  2062. *
  2063. * @param integer $id
  2064. *
  2065. * @return AccountTransformer
  2066. */
  2067. public function statusFavouritedBy(Request $request, $id)
  2068. {
  2069. abort_if(!$request->user(), 403);
  2070. $this->validate($request, [
  2071. 'page' => 'nullable|integer|min:1|max:40',
  2072. 'limit' => 'nullable|integer|min:1|max:100'
  2073. ]);
  2074. $page = $request->input('page', 1);
  2075. $limit = $request->input('limit') ?? 40;
  2076. $user = $request->user();
  2077. $status = Status::findOrFail($id);
  2078. $offset = $page == 1 ? 0 : ($page * $limit - $limit);
  2079. if($offset > 100) {
  2080. if($user->profile_id != $status->profile_id) {
  2081. return [];
  2082. }
  2083. }
  2084. if(intval($status->profile_id) !== intval($user->profile_id)) {
  2085. if($status->scope == 'private') {
  2086. abort_if(!$status->profile->followedBy($user->profile), 403);
  2087. } else {
  2088. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  2089. }
  2090. }
  2091. $res = DB::table('likes')
  2092. ->select('likes.id', 'likes.profile_id', 'likes.status_id', 'followers.created_at')
  2093. ->leftJoin('followers', function($join) use($user, $status) {
  2094. return $join->on('likes.profile_id', '=', 'followers.following_id')
  2095. ->where('followers.profile_id', $user->profile_id)
  2096. ->where('likes.status_id', $status->id);
  2097. })
  2098. ->whereStatusId($status->id)
  2099. ->orderByDesc('followers.created_at')
  2100. ->offset($offset)
  2101. ->limit($limit)
  2102. ->get()
  2103. ->map(function($like) {
  2104. $account = AccountService::getMastodon($like->profile_id, true);
  2105. $account['follows'] = isset($like->created_at);
  2106. return $account;
  2107. })
  2108. ->filter(function($account) use($user) {
  2109. return $account && isset($account['id']);
  2110. })
  2111. ->values();
  2112. $url = $request->url();
  2113. $page = $request->input('page', 1);
  2114. $next = $page < 40 ? $page + 1 : 40;
  2115. $prev = $page > 1 ? $page - 1 : 1;
  2116. $links = '<'.$url.'?page='.$next.'&limit='.$limit.'>; rel="next", <'.$url.'?page='.$prev.'&limit='.$limit.'>; rel="prev"';
  2117. return $this->json($res, 200, ['Link' => $links]);
  2118. }
  2119. /**
  2120. * POST /api/v1/statuses
  2121. *
  2122. *
  2123. * @return StatusTransformer
  2124. */
  2125. public function statusCreate(Request $request)
  2126. {
  2127. abort_if(!$request->user(), 403);
  2128. $this->validate($request, [
  2129. 'status' => 'nullable|string',
  2130. 'in_reply_to_id' => 'nullable',
  2131. 'media_ids' => 'sometimes|array|max:' . config_cache('pixelfed.max_album_length'),
  2132. 'sensitive' => 'nullable',
  2133. 'visibility' => 'string|in:private,unlisted,public',
  2134. 'spoiler_text' => 'sometimes|max:140',
  2135. 'place_id' => 'sometimes|integer|min:1|max:128769',
  2136. 'collection_ids' => 'sometimes|array|max:3',
  2137. 'comments_disabled' => 'sometimes|boolean',
  2138. ]);
  2139. if(config('costar.enabled') == true) {
  2140. $blockedKeywords = config('costar.keyword.block');
  2141. if($blockedKeywords !== null && $request->status) {
  2142. $keywords = config('costar.keyword.block');
  2143. foreach($keywords as $kw) {
  2144. if(Str::contains($request->status, $kw) == true) {
  2145. abort(400, 'Invalid object. Contains banned keyword.');
  2146. }
  2147. }
  2148. }
  2149. }
  2150. if(!$request->filled('media_ids') && !$request->filled('in_reply_to_id')) {
  2151. abort(403, 'Empty statuses are not allowed');
  2152. }
  2153. $ids = $request->input('media_ids');
  2154. $in_reply_to_id = $request->input('in_reply_to_id');
  2155. $user = $request->user();
  2156. $profile = $user->profile;
  2157. $limitKey = 'compose:rate-limit:store:' . $user->id;
  2158. $limitTtl = now()->addMinutes(15);
  2159. $limitReached = Cache::remember($limitKey, $limitTtl, function() use($user) {
  2160. $dailyLimit = Status::whereProfileId($user->profile_id)
  2161. ->whereNull('in_reply_to_id')
  2162. ->whereNull('reblog_of_id')
  2163. ->where('created_at', '>', now()->subDays(1))
  2164. ->count();
  2165. return $dailyLimit >= 100;
  2166. });
  2167. abort_if($limitReached == true, 429);
  2168. $visibility = $profile->is_private ? 'private' : (
  2169. $profile->unlisted == true &&
  2170. $request->input('visibility', 'public') == 'public' ?
  2171. 'unlisted' :
  2172. $request->input('visibility', 'public'));
  2173. if($user->last_active_at == null) {
  2174. return [];
  2175. }
  2176. $content = strip_tags($request->input('status'));
  2177. $rendered = Autolink::create()->autolink($content);
  2178. $cw = $user->profile->cw == true ? true : $request->input('sensitive', false);
  2179. $spoilerText = $cw && $request->filled('spoiler_text') ? $request->input('spoiler_text') : null;
  2180. if($in_reply_to_id) {
  2181. $parent = Status::findOrFail($in_reply_to_id);
  2182. if($parent->comments_disabled) {
  2183. return $this->json("Comments have been disabled on this post", 422);
  2184. }
  2185. $blocks = UserFilterService::blocks($parent->profile_id);
  2186. abort_if(in_array($profile->id, $blocks), 422, 'Cannot reply to this post at this time.');
  2187. $status = new Status;
  2188. $status->caption = $content;
  2189. $status->rendered = $rendered;
  2190. $status->scope = $visibility;
  2191. $status->visibility = $visibility;
  2192. $status->profile_id = $user->profile_id;
  2193. $status->is_nsfw = $cw;
  2194. $status->cw_summary = $spoilerText;
  2195. $status->in_reply_to_id = $parent->id;
  2196. $status->in_reply_to_profile_id = $parent->profile_id;
  2197. $status->save();
  2198. StatusService::del($parent->id);
  2199. Cache::forget('status:replies:all:' . $parent->id);
  2200. }
  2201. if($ids) {
  2202. if(Media::whereUserId($user->id)
  2203. ->whereNull('status_id')
  2204. ->find($ids)
  2205. ->count() == 0
  2206. ) {
  2207. abort(400, 'Invalid media_ids');
  2208. }
  2209. if(!$in_reply_to_id) {
  2210. $status = new Status;
  2211. $status->caption = $content;
  2212. $status->rendered = $rendered;
  2213. $status->profile_id = $user->profile_id;
  2214. $status->scope = 'draft';
  2215. $status->is_nsfw = $cw;
  2216. $status->cw_summary = $spoilerText;
  2217. if($request->has('place_id')) {
  2218. $status->place_id = $request->input('place_id');
  2219. }
  2220. $status->save();
  2221. }
  2222. $mimes = [];
  2223. foreach($ids as $k => $v) {
  2224. if($k + 1 > config_cache('pixelfed.max_album_length')) {
  2225. continue;
  2226. }
  2227. $m = Media::whereUserId($user->id)->whereNull('status_id')->findOrFail($v);
  2228. if($m->profile_id !== $user->profile_id || $m->status_id) {
  2229. abort(403, 'Invalid media id');
  2230. }
  2231. $m->status_id = $status->id;
  2232. $m->save();
  2233. array_push($mimes, $m->mime);
  2234. }
  2235. if(empty($mimes)) {
  2236. $status->delete();
  2237. abort(400, 'Invalid media ids');
  2238. }
  2239. if($request->has('comments_disabled') && $request->input('comments_disabled')) {
  2240. $status->comments_disabled = true;
  2241. }
  2242. $status->scope = $visibility;
  2243. $status->visibility = $visibility;
  2244. $status->type = StatusController::mimeTypeCheck($mimes);
  2245. $status->save();
  2246. }
  2247. if(!$status) {
  2248. abort(500, 'An error occured.');
  2249. }
  2250. NewStatusPipeline::dispatch($status);
  2251. if($status->in_reply_to_id) {
  2252. CommentPipeline::dispatch($parent, $status);
  2253. }
  2254. Cache::forget('user:account:id:'.$user->id);
  2255. Cache::forget('_api:statuses:recent_9:'.$user->profile_id);
  2256. Cache::forget('profile:status_count:'.$user->profile_id);
  2257. Cache::forget($user->storageUsedKey());
  2258. Cache::forget('profile:embed:' . $status->profile_id);
  2259. Cache::forget($limitKey);
  2260. if($request->has('collection_ids') && $ids) {
  2261. $collections = Collection::whereProfileId($user->profile_id)
  2262. ->find($request->input('collection_ids'))
  2263. ->each(function($collection) use($status) {
  2264. $count = $collection->items()->count();
  2265. $item = CollectionItem::firstOrCreate([
  2266. 'collection_id' => $collection->id,
  2267. 'object_type' => 'App\Status',
  2268. 'object_id' => $status->id
  2269. ],[
  2270. 'order' => $count,
  2271. ]);
  2272. CollectionService::addItem(
  2273. $collection->id,
  2274. $status->id,
  2275. $count
  2276. );
  2277. $collection->updated_at = now();
  2278. $collection->save();
  2279. CollectionService::setCollection($collection->id, $collection);
  2280. });
  2281. }
  2282. $res = StatusService::getMastodon($status->id, false);
  2283. $res['favourited'] = false;
  2284. $res['language'] = 'en';
  2285. $res['bookmarked'] = false;
  2286. $res['card'] = null;
  2287. return $this->json($res);
  2288. }
  2289. /**
  2290. * DELETE /api/v1/statuses
  2291. *
  2292. * @param integer $id
  2293. *
  2294. * @return null
  2295. */
  2296. public function statusDelete(Request $request, $id)
  2297. {
  2298. abort_if(!$request->user(), 403);
  2299. $status = Status::whereProfileId($request->user()->profile->id)
  2300. ->findOrFail($id);
  2301. $resource = new Fractal\Resource\Item($status, new StatusTransformer());
  2302. Cache::forget('profile:status_count:'.$status->profile_id);
  2303. StatusDelete::dispatch($status);
  2304. $res = $this->fractal->createData($resource)->toArray();
  2305. $res['text'] = $res['content'];
  2306. unset($res['content']);
  2307. return $this->json($res);
  2308. }
  2309. /**
  2310. * POST /api/v1/statuses/{id}/reblog
  2311. *
  2312. * @param integer $id
  2313. *
  2314. * @return StatusTransformer
  2315. */
  2316. public function statusShare(Request $request, $id)
  2317. {
  2318. abort_if(!$request->user(), 403);
  2319. $user = $request->user();
  2320. $status = Status::whereScope('public')->findOrFail($id);
  2321. if(intval($status->profile_id) !== intval($user->profile_id)) {
  2322. if($status->scope == 'private') {
  2323. abort_if(!FollowerService::follows($user->profile_id, $status->profile_id), 403);
  2324. } else {
  2325. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  2326. }
  2327. $blocks = UserFilterService::blocks($status->profile_id);
  2328. if($blocks && in_array($user->profile_id, $blocks)) {
  2329. abort(422);
  2330. }
  2331. }
  2332. $share = Status::firstOrCreate([
  2333. 'profile_id' => $user->profile_id,
  2334. 'reblog_of_id' => $status->id,
  2335. 'type' => 'share',
  2336. 'in_reply_to_profile_id' => $status->profile_id,
  2337. 'scope' => 'public',
  2338. 'visibility' => 'public'
  2339. ]);
  2340. if($share->wasRecentlyCreated == true) {
  2341. SharePipeline::dispatch($share);
  2342. }
  2343. StatusService::del($status->id);
  2344. ReblogService::add($user->profile_id, $status->id);
  2345. $res = StatusService::getMastodon($status->id);
  2346. $res['reblogged'] = true;
  2347. return $this->json($res);
  2348. }
  2349. /**
  2350. * POST /api/v1/statuses/{id}/unreblog
  2351. *
  2352. * @param integer $id
  2353. *
  2354. * @return StatusTransformer
  2355. */
  2356. public function statusUnshare(Request $request, $id)
  2357. {
  2358. abort_if(!$request->user(), 403);
  2359. $user = $request->user();
  2360. $status = Status::whereScope('public')->findOrFail($id);
  2361. if(intval($status->profile_id) !== intval($user->profile_id)) {
  2362. if($status->scope == 'private') {
  2363. abort_if(!FollowerService::follows($user->profile_id, $status->profile_id), 403);
  2364. } else {
  2365. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  2366. }
  2367. }
  2368. $reblog = Status::whereProfileId($user->profile_id)
  2369. ->whereReblogOfId($status->id)
  2370. ->first();
  2371. if(!$reblog) {
  2372. $res = StatusService::getMastodon($status->id);
  2373. $res['reblogged'] = false;
  2374. return $this->json($res);
  2375. }
  2376. UndoSharePipeline::dispatch($reblog);
  2377. ReblogService::del($user->profile_id, $status->id);
  2378. $res = StatusService::getMastodon($status->id);
  2379. $res['reblogged'] = false;
  2380. return $this->json($res);
  2381. }
  2382. /**
  2383. * GET /api/v1/timelines/tag/{hashtag}
  2384. *
  2385. * @param string $hashtag
  2386. *
  2387. * @return StatusTransformer
  2388. */
  2389. public function timelineHashtag(Request $request, $hashtag)
  2390. {
  2391. $this->validate($request,[
  2392. 'page' => 'nullable|integer|max:40',
  2393. 'min_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  2394. 'max_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  2395. 'limit' => 'nullable|integer|max:100'
  2396. ]);
  2397. $tag = Hashtag::whereName($hashtag)
  2398. ->orWhere('slug', $hashtag)
  2399. ->first();
  2400. if(!$tag) {
  2401. return response()->json([]);
  2402. }
  2403. $min = $request->input('min_id');
  2404. $max = $request->input('max_id');
  2405. $limit = $request->input('limit', 20);
  2406. if(!$min && !$max) {
  2407. $id = 1;
  2408. $dir = '>';
  2409. } else {
  2410. $dir = $min ? '>' : '<';
  2411. $id = $min ?? $max;
  2412. }
  2413. $res = StatusHashtag::whereHashtagId($tag->id)
  2414. ->whereStatusVisibility('public')
  2415. ->where('status_id', $dir, $id)
  2416. ->latest()
  2417. ->limit($limit)
  2418. ->pluck('status_id')
  2419. ->map(function ($i) {
  2420. if($i) {
  2421. return StatusService::getMastodon($i);
  2422. }
  2423. })
  2424. ->filter(function($i) {
  2425. return $i && isset($i['account']);
  2426. })
  2427. ->values()
  2428. ->toArray();
  2429. return $this->json($res);
  2430. }
  2431. /**
  2432. * GET /api/v1/bookmarks
  2433. *
  2434. *
  2435. *
  2436. * @return StatusTransformer
  2437. */
  2438. public function bookmarks(Request $request)
  2439. {
  2440. abort_if(!$request->user(), 403);
  2441. $this->validate($request, [
  2442. 'limit' => 'nullable|integer|min:1|max:40',
  2443. 'max_id' => 'nullable|integer|min:0',
  2444. 'since_id' => 'nullable|integer|min:0',
  2445. 'min_id' => 'nullable|integer|min:0'
  2446. ]);
  2447. $pid = $request->user()->profile_id;
  2448. $limit = $request->input('limit') ?? 20;
  2449. $max_id = $request->input('max_id');
  2450. $since_id = $request->input('since_id');
  2451. $min_id = $request->input('min_id');
  2452. $dir = $min_id ? '>' : '<';
  2453. $id = $min_id ?? $max_id;
  2454. if($id) {
  2455. $bookmarks = Bookmark::whereProfileId($pid)
  2456. ->where('status_id', $dir, $id)
  2457. ->limit($limit)
  2458. ->pluck('status_id');
  2459. } else {
  2460. $bookmarks = Bookmark::whereProfileId($pid)
  2461. ->latest()
  2462. ->limit($limit)
  2463. ->pluck('status_id');
  2464. }
  2465. $res = [];
  2466. foreach($bookmarks as $id) {
  2467. $res[] = \App\Services\StatusService::getMastodon($id);
  2468. }
  2469. return $this->json($res);
  2470. }
  2471. /**
  2472. * POST /api/v1/statuses/{id}/bookmark
  2473. *
  2474. *
  2475. *
  2476. * @return StatusTransformer
  2477. */
  2478. public function bookmarkStatus(Request $request, $id)
  2479. {
  2480. abort_if(!$request->user(), 403);
  2481. $status = Status::whereNull('uri')
  2482. ->whereScope('public')
  2483. ->findOrFail($id);
  2484. Bookmark::firstOrCreate([
  2485. 'status_id' => $status->id,
  2486. 'profile_id' => $request->user()->profile_id
  2487. ]);
  2488. $res = StatusService::getMastodon($status->id);
  2489. return $this->json($res);
  2490. }
  2491. /**
  2492. * POST /api/v1/statuses/{id}/unbookmark
  2493. *
  2494. *
  2495. *
  2496. * @return StatusTransformer
  2497. */
  2498. public function unbookmarkStatus(Request $request, $id)
  2499. {
  2500. abort_if(!$request->user(), 403);
  2501. $status = Status::whereNull('uri')
  2502. ->whereScope('public')
  2503. ->findOrFail($id);
  2504. $bookmark = Bookmark::whereStatusId($status->id)
  2505. ->whereProfileId($request->user()->profile_id)
  2506. ->firstOrFail();
  2507. $bookmark->delete();
  2508. $res = StatusService::getMastodon($status->id);
  2509. return $this->json($res);
  2510. }
  2511. /**
  2512. * GET /api/v2/search
  2513. *
  2514. *
  2515. * @return array
  2516. */
  2517. public function searchV2(Request $request)
  2518. {
  2519. abort_if(!$request->user(), 403);
  2520. $this->validate($request, [
  2521. 'q' => 'required|string|min:1|max:100',
  2522. 'account_id' => 'nullable|string',
  2523. 'max_id' => 'nullable|string',
  2524. 'min_id' => 'nullable|string',
  2525. 'type' => 'nullable|in:accounts,hashtags,statuses',
  2526. 'exclude_unreviewed' => 'nullable',
  2527. 'resolve' => 'nullable',
  2528. 'limit' => 'nullable|integer|max:40',
  2529. 'offset' => 'nullable|integer',
  2530. 'following' => 'nullable'
  2531. ]);
  2532. return $this->json(SearchApiV2Service::query($request, true));
  2533. }
  2534. /**
  2535. * GET /api/v1/discover/posts
  2536. *
  2537. *
  2538. * @return array
  2539. */
  2540. public function discoverPosts(Request $request)
  2541. {
  2542. abort_if(!$request->user(), 403);
  2543. $this->validate($request, [
  2544. 'limit' => 'integer|min:1|max:40'
  2545. ]);
  2546. $limit = $request->input('limit', 40);
  2547. $pid = $request->user()->profile_id;
  2548. $filters = UserFilterService::filters($pid);
  2549. $forYou = DiscoverService::getForYou();
  2550. $posts = $forYou->take(50)->map(function($post) {
  2551. return StatusService::getMastodon($post);
  2552. })
  2553. ->filter(function($post) use($filters) {
  2554. return $post &&
  2555. isset($post['account']) &&
  2556. isset($post['account']['id']) &&
  2557. !in_array($post['account']['id'], $filters);
  2558. })
  2559. ->take(12)
  2560. ->values();
  2561. return $this->json(compact('posts'));
  2562. }
  2563. /**
  2564. * GET /api/v2/statuses/{id}/replies
  2565. *
  2566. *
  2567. * @return array
  2568. */
  2569. public function statusReplies(Request $request, $id)
  2570. {
  2571. abort_if(!$request->user(), 403);
  2572. $this->validate($request, [
  2573. 'limit' => 'int|min:1|max:10',
  2574. 'sort' => 'in:all,newest,popular'
  2575. ]);
  2576. $limit = $request->input('limit', 3);
  2577. $pid = $request->user()->profile_id;
  2578. $status = StatusService::getMastodon($id, false);
  2579. abort_if(!$status, 404);
  2580. if($status['visibility'] == 'private') {
  2581. if($pid != $status['account']['id']) {
  2582. abort_unless(FollowerService::follows($pid, $status['account']['id']), 404);
  2583. }
  2584. }
  2585. $sortBy = $request->input('sort', 'all');
  2586. if($sortBy == 'all' && isset($status['replies_count']) && $status['replies_count'] && $request->has('refresh_cache')) {
  2587. if(!Cache::has('status:replies:all-rc:' . $id)) {
  2588. Cache::forget('status:replies:all:' . $id);
  2589. Cache::put('status:replies:all-rc:' . $id, true, 300);
  2590. }
  2591. }
  2592. if($sortBy == 'all' && !$request->has('cursor')) {
  2593. $ids = Cache::remember('status:replies:all:' . $id, 3600, function() use($id) {
  2594. return DB::table('statuses')
  2595. ->where('in_reply_to_id', $id)
  2596. ->orderBy('id')
  2597. ->cursorPaginate(3);
  2598. });
  2599. } else {
  2600. $ids = DB::table('statuses')
  2601. ->where('in_reply_to_id', $id)
  2602. ->when($sortBy, function($q, $sortBy) {
  2603. if($sortBy === 'all') {
  2604. return $q->orderBy('id');
  2605. }
  2606. if($sortBy === 'newest') {
  2607. return $q->orderByDesc('created_at');
  2608. }
  2609. if($sortBy === 'popular') {
  2610. return $q->orderByDesc('likes_count');
  2611. }
  2612. })
  2613. ->cursorPaginate($limit);
  2614. }
  2615. $data = $ids->map(function($post) use($pid) {
  2616. $status = StatusService::get($post->id, false);
  2617. if(!$status || !isset($status['id'])) {
  2618. return false;
  2619. }
  2620. $status['favourited'] = LikeService::liked($pid, $post->id);
  2621. return $status;
  2622. })
  2623. ->map(function($post) {
  2624. if(isset($post['account']) && isset($post['account']['id'])) {
  2625. $account = AccountService::get($post['account']['id'], true);
  2626. $post['account'] = $account;
  2627. }
  2628. return $post;
  2629. })
  2630. ->filter(function($post) {
  2631. return $post && isset($post['id']) && isset($post['account']) && isset($post['account']['id']);
  2632. })
  2633. ->values();
  2634. $res = [
  2635. 'data' => $data,
  2636. 'next' => $ids->nextPageUrl()
  2637. ];
  2638. return $this->json($res);
  2639. }
  2640. /**
  2641. * GET /api/v2/statuses/{id}/state
  2642. *
  2643. *
  2644. * @return array
  2645. */
  2646. public function statusState(Request $request, $id)
  2647. {
  2648. abort_if(!$request->user(), 403);
  2649. $status = Status::findOrFail($id);
  2650. $pid = $request->user()->profile_id;
  2651. abort_if(!in_array($status->scope, ['public', 'unlisted', 'private']), 404);
  2652. return $this->json(StatusService::getState($status->id, $pid));
  2653. }
  2654. /**
  2655. * GET /api/v1.1/discover/accounts/popular
  2656. *
  2657. *
  2658. * @return array
  2659. */
  2660. public function discoverAccountsPopular(Request $request)
  2661. {
  2662. abort_if(!$request->user(), 403);
  2663. $pid = $request->user()->profile_id;
  2664. $ids = Cache::remember('api:v1.1:discover:accounts:popular', 86400, function() {
  2665. return DB::table('profiles')
  2666. ->where('is_private', false)
  2667. ->whereNull('status')
  2668. ->orderByDesc('profiles.followers_count')
  2669. ->limit(20)
  2670. ->get();
  2671. });
  2672. $ids = $ids->map(function($profile) {
  2673. return AccountService::get($profile->id, true);
  2674. })
  2675. ->filter(function($profile) use($pid) {
  2676. return $profile && isset($profile['id']);
  2677. })
  2678. ->filter(function($profile) use($pid) {
  2679. return $profile['id'] != $pid;
  2680. })
  2681. ->map(function($profile) {
  2682. $ids = collect(ProfileStatusService::get($profile['id'], 0, 9))
  2683. ->map(function($id) {
  2684. return StatusService::get($id, true);
  2685. })
  2686. ->filter(function($post) {
  2687. return $post && isset($post['id']);
  2688. })
  2689. ->take(3);
  2690. $profile['recent_posts'] = $ids;
  2691. return $profile;
  2692. })
  2693. ->take(6)
  2694. ->values();
  2695. return $this->json($ids);
  2696. }
  2697. /**
  2698. * GET /api/v1/preferences
  2699. *
  2700. *
  2701. * @return array
  2702. */
  2703. public function getPreferences(Request $request)
  2704. {
  2705. abort_if(!$request->user(), 403);
  2706. $pid = $request->user()->profile_id;
  2707. $account = AccountService::get($pid);
  2708. return $this->json([
  2709. 'posting:default:visibility' => $account['locked'] ? 'private' : 'public',
  2710. 'posting:default:sensitive' => false,
  2711. 'posting:default:language' => null,
  2712. 'reading:expand:media' => 'default',
  2713. 'reading:expand:spoilers' => false
  2714. ]);
  2715. }
  2716. /**
  2717. * GET /api/v1/trends
  2718. *
  2719. *
  2720. * @return array
  2721. */
  2722. public function getTrends(Request $request)
  2723. {
  2724. abort_if(!$request->user(), 403);
  2725. return $this->json([]);
  2726. }
  2727. /**
  2728. * GET /api/v1/announcements
  2729. *
  2730. *
  2731. * @return array
  2732. */
  2733. public function getAnnouncements(Request $request)
  2734. {
  2735. abort_if(!$request->user(), 403);
  2736. return $this->json([]);
  2737. }
  2738. /**
  2739. * GET /api/v1/markers
  2740. *
  2741. *
  2742. * @return array
  2743. */
  2744. public function getMarkers(Request $request)
  2745. {
  2746. abort_if(!$request->user(), 403);
  2747. $type = $request->input('timeline');
  2748. if(is_array($type)) {
  2749. $type = $type[0];
  2750. }
  2751. if(!$type || !in_array($type, ['home', 'notifications'])) {
  2752. return $this->json([]);
  2753. }
  2754. $pid = $request->user()->profile_id;
  2755. return $this->json(MarkerService::get($pid, $type));
  2756. }
  2757. /**
  2758. * POST /api/v1/markers
  2759. *
  2760. *
  2761. * @return array
  2762. */
  2763. public function setMarkers(Request $request)
  2764. {
  2765. abort_if(!$request->user(), 403);
  2766. $pid = $request->user()->profile_id;
  2767. $home = $request->input('home.last_read_id');
  2768. $notifications = $request->input('notifications.last_read_id');
  2769. if($home) {
  2770. return $this->json(MarkerService::set($pid, 'home', $home));
  2771. }
  2772. if($notifications) {
  2773. return $this->json(MarkerService::set($pid, 'notifications', $notifications));
  2774. }
  2775. return $this->json([]);
  2776. }
  2777. }