ApiV1Controller.php 85 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239
  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() >= Follower::MAX_FOLLOWING) {
  594. abort(400, 'You cannot follow more than ' . Follower::MAX_FOLLOWING . ' accounts');
  595. }
  596. // Rate limits, follow 30 accounts per hour max
  597. if($user->profile->following()->where('followers.created_at', '>', now()->subHour())->count() >= Follower::FOLLOW_PER_HOUR) {
  598. abort(400, 'You can only follow ' . Follower::FOLLOW_PER_HOUR . ' users per hour');
  599. }
  600. if($private == true) {
  601. $follow = FollowRequest::firstOrCreate([
  602. 'follower_id' => $user->profile_id,
  603. 'following_id' => $target->id
  604. ]);
  605. if($remote == true && config('federation.activitypub.remoteFollow') == true) {
  606. (new FollowerController())->sendFollow($user->profile, $target);
  607. }
  608. } else {
  609. $follower = Follower::firstOrCreate([
  610. 'profile_id' => $user->profile_id,
  611. 'following_id' => $target->id
  612. ]);
  613. if($remote == true && config('federation.activitypub.remoteFollow') == true) {
  614. (new FollowerController())->sendFollow($user->profile, $target);
  615. }
  616. FollowPipeline::dispatch($follower);
  617. $target->increment('followers_count');
  618. }
  619. RelationshipService::refresh($user->profile_id, $target->id);
  620. Cache::forget('profile:following:'.$target->id);
  621. Cache::forget('profile:followers:'.$target->id);
  622. Cache::forget('profile:following:'.$user->profile_id);
  623. Cache::forget('profile:followers:'.$user->profile_id);
  624. Cache::forget('api:local:exp:rec:'.$user->profile_id);
  625. Cache::forget('user:account:id:'.$target->user_id);
  626. Cache::forget('user:account:id:'.$user->id);
  627. Cache::forget('profile:follower_count:'.$target->id);
  628. Cache::forget('profile:follower_count:'.$user->profile_id);
  629. Cache::forget('profile:following_count:'.$target->id);
  630. Cache::forget('profile:following_count:'.$user->profile_id);
  631. AccountService::del($user->profile_id);
  632. AccountService::del($target->id);
  633. $res = RelationshipService::get($user->profile_id, $target->id);
  634. return $this->json($res);
  635. }
  636. /**
  637. * POST /api/v1/accounts/{id}/unfollow
  638. *
  639. * @param integer $id
  640. *
  641. * @return \App\Transformer\Api\RelationshipTransformer
  642. */
  643. public function accountUnfollowById(Request $request, $id)
  644. {
  645. abort_if(!$request->user(), 403);
  646. $user = $request->user();
  647. $target = Profile::where('id', '!=', $user->profile_id)
  648. ->whereNull('status')
  649. ->findOrFail($id);
  650. $private = (bool) $target->is_private;
  651. $remote = (bool) $target->domain;
  652. $isFollowing = Follower::whereProfileId($user->profile_id)
  653. ->whereFollowingId($target->id)
  654. ->exists();
  655. if($isFollowing == false) {
  656. $followRequest = FollowRequest::whereFollowerId($user->profile_id)
  657. ->whereFollowingId($target->id)
  658. ->first();
  659. if($followRequest) {
  660. $followRequest->delete();
  661. RelationshipService::refresh($target->id, $user->profile_id);
  662. }
  663. $resource = new Fractal\Resource\Item($target, new RelationshipTransformer());
  664. $res = $this->fractal->createData($resource)->toArray();
  665. return $this->json($res);
  666. }
  667. // Rate limits, follow 30 accounts per hour max
  668. if($user->profile->following()->where('followers.updated_at', '>', now()->subHour())->count() >= Follower::FOLLOW_PER_HOUR) {
  669. abort(400, 'You can only follow or unfollow ' . Follower::FOLLOW_PER_HOUR . ' users per hour');
  670. }
  671. if($user->profile->following_count) {
  672. $user->profile->decrement('following_count');
  673. }
  674. FollowRequest::whereFollowerId($user->profile_id)
  675. ->whereFollowingId($target->id)
  676. ->delete();
  677. Follower::whereProfileId($user->profile_id)
  678. ->whereFollowingId($target->id)
  679. ->delete();
  680. FollowerService::remove($user->profile_id, $target->id);
  681. $target->decrement('followers_count');
  682. if($remote == true && config('federation.activitypub.remoteFollow') == true) {
  683. (new FollowerController())->sendUndoFollow($user->profile, $target);
  684. }
  685. RelationshipService::refresh($user->profile_id, $target->id);
  686. Cache::forget('profile:following:'.$target->id);
  687. Cache::forget('profile:followers:'.$target->id);
  688. Cache::forget('profile:following:'.$user->profile_id);
  689. Cache::forget('profile:followers:'.$user->profile_id);
  690. Cache::forget('api:local:exp:rec:'.$user->profile_id);
  691. Cache::forget('user:account:id:'.$target->user_id);
  692. Cache::forget('user:account:id:'.$user->id);
  693. Cache::forget('profile:follower_count:'.$target->id);
  694. Cache::forget('profile:follower_count:'.$user->profile_id);
  695. Cache::forget('profile:following_count:'.$target->id);
  696. Cache::forget('profile:following_count:'.$user->profile_id);
  697. AccountService::del($user->profile_id);
  698. AccountService::del($target->id);
  699. $res = RelationshipService::get($user->profile_id, $target->id);
  700. return $this->json($res);
  701. }
  702. /**
  703. * GET /api/v1/accounts/relationships
  704. *
  705. * @param array|integer $id
  706. *
  707. * @return \App\Services\RelationshipService
  708. */
  709. public function accountRelationshipsById(Request $request)
  710. {
  711. abort_if(!$request->user(), 403);
  712. $this->validate($request, [
  713. 'id' => 'required|array|min:1|max:20',
  714. 'id.*' => 'required|integer|min:1|max:' . PHP_INT_MAX
  715. ]);
  716. $pid = $request->user()->profile_id ?? $request->user()->profile->id;
  717. $res = collect($request->input('id'))
  718. ->filter(function($id) use($pid) {
  719. return intval($id) !== intval($pid);
  720. })
  721. ->map(function($id) use($pid) {
  722. return RelationshipService::get($pid, $id);
  723. });
  724. return $this->json($res);
  725. }
  726. /**
  727. * GET /api/v1/accounts/search
  728. *
  729. *
  730. *
  731. * @return \App\Transformer\Api\AccountTransformer
  732. */
  733. public function accountSearch(Request $request)
  734. {
  735. abort_if(!$request->user(), 403);
  736. $this->validate($request, [
  737. 'q' => 'required|string|min:1|max:255',
  738. 'limit' => 'nullable|integer|min:1|max:40',
  739. 'resolve' => 'nullable'
  740. ]);
  741. $user = $request->user();
  742. $query = $request->input('q');
  743. $limit = $request->input('limit') ?? 20;
  744. $resolve = (bool) $request->input('resolve', false);
  745. $q = '%' . $query . '%';
  746. $profiles = Cache::remember('api:v1:accounts:search:' . sha1($query) . ':limit:' . $limit, 86400, function() use($q, $limit) {
  747. return Profile::whereNull('status')
  748. ->where('username', 'like', $q)
  749. ->orWhere('name', 'like', $q)
  750. ->limit($limit)
  751. ->pluck('id')
  752. ->map(function($id) {
  753. return AccountService::getMastodon($id);
  754. })
  755. ->filter(function($account) {
  756. return $account && isset($account['id']);
  757. });
  758. });
  759. return $this->json($profiles);
  760. }
  761. /**
  762. * GET /api/v1/blocks
  763. *
  764. *
  765. *
  766. * @return \App\Transformer\Api\AccountTransformer
  767. */
  768. public function accountBlocks(Request $request)
  769. {
  770. abort_if(!$request->user(), 403);
  771. $this->validate($request, [
  772. 'limit' => 'nullable|integer|min:1|max:40',
  773. 'page' => 'nullable|integer|min:1|max:10'
  774. ]);
  775. $user = $request->user();
  776. $limit = $request->input('limit') ?? 40;
  777. $blocked = UserFilter::select('filterable_id','filterable_type','filter_type','user_id')
  778. ->whereUserId($user->profile_id)
  779. ->whereFilterableType('App\Profile')
  780. ->whereFilterType('block')
  781. ->orderByDesc('id')
  782. ->simplePaginate($limit)
  783. ->pluck('filterable_id')
  784. ->map(function($id) {
  785. return AccountService::get($id, true);
  786. })
  787. ->filter(function($account) {
  788. return $account && isset($account['id']);
  789. })
  790. ->values();
  791. return $this->json($blocked);
  792. }
  793. /**
  794. * POST /api/v1/accounts/{id}/block
  795. *
  796. * @param integer $id
  797. *
  798. * @return \App\Transformer\Api\RelationshipTransformer
  799. */
  800. public function accountBlockById(Request $request, $id)
  801. {
  802. abort_if(!$request->user(), 403);
  803. $user = $request->user();
  804. $pid = $user->profile_id ?? $user->profile->id;
  805. if(intval($id) === intval($pid)) {
  806. abort(400, 'You cannot block yourself');
  807. }
  808. $profile = Profile::findOrFail($id);
  809. if($profile->user->is_admin == true) {
  810. abort(400, 'You cannot block an admin');
  811. }
  812. Follower::whereProfileId($profile->id)->whereFollowingId($pid)->delete();
  813. Follower::whereProfileId($pid)->whereFollowingId($profile->id)->delete();
  814. Notification::whereProfileId($pid)->whereActorId($profile->id)->delete();
  815. $filter = UserFilter::firstOrCreate([
  816. 'user_id' => $pid,
  817. 'filterable_id' => $profile->id,
  818. 'filterable_type' => 'App\Profile',
  819. 'filter_type' => 'block',
  820. ]);
  821. Cache::forget("user:filter:list:$pid");
  822. Cache::forget("api:local:exp:rec:$pid");
  823. RelationshipService::refresh($pid, $id);
  824. $resource = new Fractal\Resource\Item($profile, new RelationshipTransformer());
  825. $res = $this->fractal->createData($resource)->toArray();
  826. return $this->json($res);
  827. }
  828. /**
  829. * POST /api/v1/accounts/{id}/unblock
  830. *
  831. * @param integer $id
  832. *
  833. * @return \App\Transformer\Api\RelationshipTransformer
  834. */
  835. public function accountUnblockById(Request $request, $id)
  836. {
  837. abort_if(!$request->user(), 403);
  838. $user = $request->user();
  839. $pid = $user->profile_id ?? $user->profile->id;
  840. if(intval($id) === intval($pid)) {
  841. abort(400, 'You cannot unblock yourself');
  842. }
  843. $profile = Profile::findOrFail($id);
  844. UserFilter::whereUserId($pid)
  845. ->whereFilterableId($profile->id)
  846. ->whereFilterableType('App\Profile')
  847. ->whereFilterType('block')
  848. ->delete();
  849. Cache::forget("user:filter:list:$pid");
  850. Cache::forget("api:local:exp:rec:$pid");
  851. RelationshipService::refresh($pid, $id);
  852. $resource = new Fractal\Resource\Item($profile, new RelationshipTransformer());
  853. $res = $this->fractal->createData($resource)->toArray();
  854. return $this->json($res);
  855. }
  856. /**
  857. * GET /api/v1/custom_emojis
  858. *
  859. * Return custom emoji
  860. *
  861. * @return array
  862. */
  863. public function customEmojis()
  864. {
  865. return response(CustomEmojiService::all())->header('Content-Type', 'application/json');
  866. }
  867. /**
  868. * GET /api/v1/domain_blocks
  869. *
  870. * Return empty array
  871. *
  872. * @return array
  873. */
  874. public function accountDomainBlocks(Request $request)
  875. {
  876. abort_if(!$request->user(), 403);
  877. return response()->json([]);
  878. }
  879. /**
  880. * GET /api/v1/endorsements
  881. *
  882. * Return empty array
  883. *
  884. * @return array
  885. */
  886. public function accountEndorsements(Request $request)
  887. {
  888. abort_if(!$request->user(), 403);
  889. return response()->json([]);
  890. }
  891. /**
  892. * GET /api/v1/favourites
  893. *
  894. * Returns collection of liked statuses
  895. *
  896. * @return \App\Transformer\Api\StatusTransformer
  897. */
  898. public function accountFavourites(Request $request)
  899. {
  900. abort_if(!$request->user(), 403);
  901. $this->validate($request, [
  902. 'limit' => 'sometimes|integer|min:1|max:20'
  903. ]);
  904. $user = $request->user();
  905. $maxId = $request->input('max_id');
  906. $minId = $request->input('min_id');
  907. $limit = $request->input('limit') ?? 10;
  908. $res = Like::whereProfileId($user->profile_id)
  909. ->when($maxId, function($q, $maxId) {
  910. return $q->where('id', '<', $maxId);
  911. })
  912. ->when($minId, function($q, $minId) {
  913. return $q->where('id', '>', $minId);
  914. })
  915. ->orderByDesc('id')
  916. ->limit($limit)
  917. ->get()
  918. ->map(function($like) {
  919. $status = StatusService::getMastodon($like['status_id'], false);
  920. $status['favourited'] = true;
  921. $status['like_id'] = $like->id;
  922. $status['liked_at'] = str_replace('+00:00', 'Z', $like->created_at->format(DATE_RFC3339_EXTENDED));
  923. return $status;
  924. })
  925. ->filter(function($status) {
  926. return $status && isset($status['id'], $status['like_id']);
  927. })
  928. ->values();
  929. if($res->count()) {
  930. $ids = $res->map(function($status) {
  931. return $status['like_id'];
  932. });
  933. $max = $ids->max();
  934. $min = $ids->min();
  935. $baseUrl = config('app.url') . '/api/v1/favourites?limit=' . $limit . '&';
  936. $link = '<'.$baseUrl.'max_id='.$max.'>; rel="next",<'.$baseUrl.'min_id='.$min.'>; rel="prev"';
  937. return $this->json($res, 200, ['Link' => $link]);
  938. } else {
  939. return $this->json($res);
  940. }
  941. }
  942. /**
  943. * POST /api/v1/statuses/{id}/favourite
  944. *
  945. * @param integer $id
  946. *
  947. * @return \App\Transformer\Api\StatusTransformer
  948. */
  949. public function statusFavouriteById(Request $request, $id)
  950. {
  951. abort_if(!$request->user(), 403);
  952. $user = $request->user();
  953. $status = StatusService::getMastodon($id, false);
  954. abort_unless($status, 400);
  955. $spid = $status['account']['id'];
  956. if(intval($spid) !== intval($user->profile_id)) {
  957. if($status['visibility'] == 'private') {
  958. abort_if(!FollowerService::follows($user->profile_id, $spid), 403);
  959. } else {
  960. abort_if(!in_array($status['visibility'], ['public','unlisted']), 403);
  961. }
  962. }
  963. abort_if(
  964. Like::whereProfileId($user->profile_id)
  965. ->where('created_at', '>', now()->subDay())
  966. ->count() >= Like::MAX_PER_DAY,
  967. 429
  968. );
  969. $blocks = UserFilterService::blocks($spid);
  970. if($blocks && in_array($user->profile_id, $blocks)) {
  971. abort(422);
  972. }
  973. $like = Like::firstOrCreate([
  974. 'profile_id' => $user->profile_id,
  975. 'status_id' => $status['id']
  976. ]);
  977. if($like->wasRecentlyCreated == true) {
  978. $like->status_profile_id = $spid;
  979. $like->is_comment = !empty($status['in_reply_to_id']);
  980. $like->save();
  981. Status::findOrFail($status['id'])->update([
  982. 'likes_count' => ($status['favourites_count'] ?? 0) + 1
  983. ]);
  984. LikePipeline::dispatch($like);
  985. }
  986. $status['favourited'] = true;
  987. $status['favourites_count'] = $status['favourites_count'] + 1;
  988. return $this->json($status);
  989. }
  990. /**
  991. * POST /api/v1/statuses/{id}/unfavourite
  992. *
  993. * @param integer $id
  994. *
  995. * @return \App\Transformer\Api\StatusTransformer
  996. */
  997. public function statusUnfavouriteById(Request $request, $id)
  998. {
  999. abort_if(!$request->user(), 403);
  1000. $user = $request->user();
  1001. $status = Status::findOrFail($id);
  1002. if(intval($status->profile_id) !== intval($user->profile_id)) {
  1003. if($status->scope == 'private') {
  1004. abort_if(!$status->profile->followedBy($user->profile), 403);
  1005. } else {
  1006. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  1007. }
  1008. }
  1009. $like = Like::whereProfileId($user->profile_id)
  1010. ->whereStatusId($status->id)
  1011. ->first();
  1012. if($like) {
  1013. $like->forceDelete();
  1014. $status->likes_count = $status->likes()->count();
  1015. $status->save();
  1016. }
  1017. StatusService::del($status->id);
  1018. $res = StatusService::getMastodon($status->id, false);
  1019. $res['favourited'] = false;
  1020. return $this->json($res);
  1021. }
  1022. /**
  1023. * GET /api/v1/filters
  1024. *
  1025. * Return empty response since we filter server side
  1026. *
  1027. * @return array
  1028. */
  1029. public function accountFilters(Request $request)
  1030. {
  1031. abort_if(!$request->user(), 403);
  1032. return response()->json([]);
  1033. }
  1034. /**
  1035. * GET /api/v1/follow_requests
  1036. *
  1037. * Return array of Accounts that have sent follow requests
  1038. *
  1039. * @return \App\Transformer\Api\AccountTransformer
  1040. */
  1041. public function accountFollowRequests(Request $request)
  1042. {
  1043. abort_if(!$request->user(), 403);
  1044. $this->validate($request, [
  1045. 'limit' => 'sometimes|integer|min:1|max:100'
  1046. ]);
  1047. $user = $request->user();
  1048. $res = FollowRequest::whereFollowingId($user->profile->id)
  1049. ->limit($request->input('limit', 40))
  1050. ->pluck('follower_id')
  1051. ->map(function($id) {
  1052. return AccountService::getMastodon($id, true);
  1053. })
  1054. ->filter(function($acct) {
  1055. return $acct && isset($acct['id']);
  1056. })
  1057. ->values();
  1058. return $this->json($res);
  1059. }
  1060. /**
  1061. * POST /api/v1/follow_requests/{id}/authorize
  1062. *
  1063. * @param integer $id
  1064. *
  1065. * @return null
  1066. */
  1067. public function accountFollowRequestAccept(Request $request, $id)
  1068. {
  1069. abort_if(!$request->user(), 403);
  1070. $pid = $request->user()->profile_id;
  1071. $target = AccountService::getMastodon($id);
  1072. if(!$target) {
  1073. return response()->json(['error' => 'Record not found'], 404);
  1074. }
  1075. $followRequest = FollowRequest::whereFollowingId($pid)->whereFollowerId($id)->first();
  1076. if(!$followRequest) {
  1077. return response()->json(['error' => 'Record not found'], 404);
  1078. }
  1079. $follower = $followRequest->follower;
  1080. $follow = new Follower();
  1081. $follow->profile_id = $follower->id;
  1082. $follow->following_id = $pid;
  1083. $follow->save();
  1084. $profile = Profile::findOrFail($pid);
  1085. $profile->followers_count++;
  1086. $profile->save();
  1087. AccountService::del($profile->id);
  1088. $profile = Profile::findOrFail($follower->id);
  1089. $profile->following_count++;
  1090. $profile->save();
  1091. AccountService::del($profile->id);
  1092. if($follower->domain != null && $follower->private_key === null) {
  1093. FollowAcceptPipeline::dispatch($followRequest);
  1094. } else {
  1095. FollowPipeline::dispatch($follow);
  1096. $followRequest->delete();
  1097. }
  1098. RelationshipService::refresh($pid, $id);
  1099. $res = RelationshipService::get($pid, $id);
  1100. $res['followed_by'] = true;
  1101. return $this->json($res);
  1102. }
  1103. /**
  1104. * POST /api/v1/follow_requests/{id}/reject
  1105. *
  1106. * @param integer $id
  1107. *
  1108. * @return null
  1109. */
  1110. public function accountFollowRequestReject(Request $request, $id)
  1111. {
  1112. abort_if(!$request->user(), 403);
  1113. $pid = $request->user()->profile_id;
  1114. $target = AccountService::getMastodon($id);
  1115. if(!$target) {
  1116. return response()->json(['error' => 'Record not found'], 404);
  1117. }
  1118. $followRequest = FollowRequest::whereFollowingId($pid)->whereFollowerId($id)->first();
  1119. if(!$followRequest) {
  1120. return response()->json(['error' => 'Record not found'], 404);
  1121. }
  1122. $follower = $followRequest->follower;
  1123. if($follower->domain != null && $follower->private_key === null) {
  1124. FollowRejectPipeline::dispatch($followRequest);
  1125. } else {
  1126. $followRequest->delete();
  1127. }
  1128. RelationshipService::refresh($pid, $id);
  1129. $res = RelationshipService::get($pid, $id);
  1130. return $this->json($res);
  1131. }
  1132. /**
  1133. * GET /api/v1/suggestions
  1134. *
  1135. * Return empty array as we don't support suggestions
  1136. *
  1137. * @return null
  1138. */
  1139. public function accountSuggestions(Request $request)
  1140. {
  1141. abort_if(!$request->user(), 403);
  1142. // todo
  1143. return response()->json([]);
  1144. }
  1145. /**
  1146. * GET /api/v1/instance
  1147. *
  1148. * Information about the server.
  1149. *
  1150. * @return Instance
  1151. */
  1152. public function instance(Request $request)
  1153. {
  1154. $res = Cache::remember('api:v1:instance-data-response-v1', 1800, function () {
  1155. $contact = Cache::remember('api:v1:instance-data:contact', 604800, function () {
  1156. $admin = User::whereIsAdmin(true)->first();
  1157. return $admin && isset($admin->profile_id) ?
  1158. AccountService::getMastodon($admin->profile_id, true) :
  1159. null;
  1160. });
  1161. $stats = Cache::remember('api:v1:instance-data:stats', 43200, function () {
  1162. return [
  1163. 'user_count' => User::count(),
  1164. 'status_count' => Status::whereNull('uri')->count(),
  1165. 'domain_count' => Instance::count(),
  1166. ];
  1167. });
  1168. $rules = Cache::remember('api:v1:instance-data:rules', 604800, function () {
  1169. return config_cache('app.rules') ?
  1170. collect(json_decode(config_cache('app.rules'), true))
  1171. ->map(function($rule, $key) {
  1172. $id = $key + 1;
  1173. return [
  1174. 'id' => "{$id}",
  1175. 'text' => $rule
  1176. ];
  1177. })
  1178. ->toArray() : [];
  1179. });
  1180. return [
  1181. 'uri' => config('pixelfed.domain.app'),
  1182. 'title' => config('app.name'),
  1183. 'short_description' => config_cache('app.short_description'),
  1184. 'description' => config_cache('app.description'),
  1185. 'email' => config('instance.email'),
  1186. 'version' => '2.7.2 (compatible; Pixelfed ' . config('pixelfed.version') .')',
  1187. 'urls' => [
  1188. 'streaming_api' => 'wss://' . config('pixelfed.domain.app')
  1189. ],
  1190. 'stats' => $stats,
  1191. 'thumbnail' => config_cache('app.banner_image') ?? url(Storage::url('public/headers/default.jpg')),
  1192. 'languages' => [config('app.locale')],
  1193. 'registrations' => (bool) config_cache('pixelfed.open_registration'),
  1194. 'approval_required' => false,
  1195. 'contact_account' => $contact,
  1196. 'rules' => $rules,
  1197. 'configuration' => [
  1198. 'media_attachments' => [
  1199. 'image_matrix_limit' => 16777216,
  1200. 'image_size_limit' => config('pixelfed.max_photo_size') * 1024,
  1201. 'supported_mime_types' => explode(',', config('pixelfed.media_types')),
  1202. 'video_frame_rate_limit' => 120,
  1203. 'video_matrix_limit' => 2304000,
  1204. 'video_size_limit' => config('pixelfed.max_photo_size') * 1024,
  1205. ],
  1206. 'polls' => [
  1207. 'max_characters_per_option' => 50,
  1208. 'max_expiration' => 2629746,
  1209. 'max_options' => 4,
  1210. 'min_expiration' => 300
  1211. ],
  1212. 'statuses' => [
  1213. 'characters_reserved_per_url' => 23,
  1214. 'max_characters' => (int) config('pixelfed.max_caption_length'),
  1215. 'max_media_attachments' => (int) config('pixelfed.max_album_length')
  1216. ]
  1217. ]
  1218. ];
  1219. });
  1220. return $this->json($res);
  1221. }
  1222. /**
  1223. * GET /api/v1/lists
  1224. *
  1225. * Return empty array as we don't support lists
  1226. *
  1227. * @return null
  1228. */
  1229. public function accountLists(Request $request)
  1230. {
  1231. abort_if(!$request->user(), 403);
  1232. return response()->json([]);
  1233. }
  1234. /**
  1235. * GET /api/v1/accounts/{id}/lists
  1236. *
  1237. * @param integer $id
  1238. *
  1239. * @return null
  1240. */
  1241. public function accountListsById(Request $request, $id)
  1242. {
  1243. abort_if(!$request->user(), 403);
  1244. return response()->json([]);
  1245. }
  1246. /**
  1247. * POST /api/v1/media
  1248. *
  1249. *
  1250. * @return MediaTransformer
  1251. */
  1252. public function mediaUpload(Request $request)
  1253. {
  1254. abort_if(!$request->user(), 403);
  1255. $this->validate($request, [
  1256. 'file.*' => function() {
  1257. return [
  1258. 'required',
  1259. 'mimetypes:' . config_cache('pixelfed.media_types'),
  1260. 'max:' . config_cache('pixelfed.max_photo_size'),
  1261. ];
  1262. },
  1263. 'filter_name' => 'nullable|string|max:24',
  1264. 'filter_class' => 'nullable|alpha_dash|max:24',
  1265. 'description' => 'nullable|string|max:' . config_cache('pixelfed.max_altext_length')
  1266. ]);
  1267. $user = $request->user();
  1268. if($user->last_active_at == null) {
  1269. return [];
  1270. }
  1271. if(empty($request->file('file'))) {
  1272. return response('', 422);
  1273. }
  1274. $limitKey = 'compose:rate-limit:media-upload:' . $user->id;
  1275. $limitTtl = now()->addMinutes(15);
  1276. $limitReached = Cache::remember($limitKey, $limitTtl, function() use($user) {
  1277. $dailyLimit = Media::whereUserId($user->id)->where('created_at', '>', now()->subDays(1))->count();
  1278. return $dailyLimit >= 250;
  1279. });
  1280. abort_if($limitReached == true, 429);
  1281. $profile = $user->profile;
  1282. if(config_cache('pixelfed.enforce_account_limit') == true) {
  1283. $size = Cache::remember($user->storageUsedKey(), now()->addDays(3), function() use($user) {
  1284. return Media::whereUserId($user->id)->sum('size') / 1000;
  1285. });
  1286. $limit = (int) config_cache('pixelfed.max_account_size');
  1287. if ($size >= $limit) {
  1288. abort(403, 'Account size limit reached.');
  1289. }
  1290. }
  1291. $filterClass = in_array($request->input('filter_class'), Filter::classes()) ? $request->input('filter_class') : null;
  1292. $filterName = in_array($request->input('filter_name'), Filter::names()) ? $request->input('filter_name') : null;
  1293. $photo = $request->file('file');
  1294. $mimes = explode(',', config_cache('pixelfed.media_types'));
  1295. if(in_array($photo->getMimeType(), $mimes) == false) {
  1296. abort(403, 'Invalid or unsupported mime type.');
  1297. }
  1298. $storagePath = MediaPathService::get($user, 2);
  1299. $path = $photo->store($storagePath);
  1300. $hash = \hash_file('sha256', $photo);
  1301. $license = null;
  1302. $mime = $photo->getMimeType();
  1303. // if($photo->getMimeType() == 'image/heic') {
  1304. // abort_if(config('image.driver') !== 'imagick', 422, 'Invalid media type');
  1305. // abort_if(!in_array('HEIC', \Imagick::queryformats()), 422, 'Unsupported media type');
  1306. // $oldPath = $path;
  1307. // $path = str_replace('.heic', '.jpg', $path);
  1308. // $mime = 'image/jpeg';
  1309. // \Image::make($photo)->save(storage_path("app/{$path}"));
  1310. // @unlink(storage_path("app/{$oldPath}"));
  1311. // }
  1312. $settings = UserSetting::whereUserId($user->id)->first();
  1313. if($settings && !empty($settings->compose_settings)) {
  1314. $compose = $settings->compose_settings;
  1315. if(isset($compose['default_license']) && $compose['default_license'] != 1) {
  1316. $license = $compose['default_license'];
  1317. }
  1318. }
  1319. abort_if(MediaBlocklistService::exists($hash) == true, 451);
  1320. $media = new Media();
  1321. $media->status_id = null;
  1322. $media->profile_id = $profile->id;
  1323. $media->user_id = $user->id;
  1324. $media->media_path = $path;
  1325. $media->original_sha256 = $hash;
  1326. $media->size = $photo->getSize();
  1327. $media->mime = $mime;
  1328. $media->caption = $request->input('description');
  1329. $media->filter_class = $filterClass;
  1330. $media->filter_name = $filterName;
  1331. if($license) {
  1332. $media->license = $license;
  1333. }
  1334. $media->save();
  1335. switch ($media->mime) {
  1336. case 'image/jpeg':
  1337. case 'image/png':
  1338. ImageOptimize::dispatch($media);
  1339. break;
  1340. case 'video/mp4':
  1341. VideoThumbnail::dispatch($media);
  1342. $preview_url = '/storage/no-preview.png';
  1343. $url = '/storage/no-preview.png';
  1344. break;
  1345. }
  1346. Cache::forget($limitKey);
  1347. $resource = new Fractal\Resource\Item($media, new MediaTransformer());
  1348. $res = $this->fractal->createData($resource)->toArray();
  1349. $res['preview_url'] = $media->url(). '?v=' . time();
  1350. $res['url'] = $media->url(). '?v=' . time();
  1351. return $this->json($res);
  1352. }
  1353. /**
  1354. * PUT /api/v1/media/{id}
  1355. *
  1356. * @param integer $id
  1357. *
  1358. * @return MediaTransformer
  1359. */
  1360. public function mediaUpdate(Request $request, $id)
  1361. {
  1362. abort_if(!$request->user(), 403);
  1363. $this->validate($request, [
  1364. 'description' => 'nullable|string|max:' . config_cache('pixelfed.max_altext_length')
  1365. ]);
  1366. $user = $request->user();
  1367. $media = Media::whereUserId($user->id)
  1368. ->whereNull('status_id')
  1369. ->findOrFail($id);
  1370. $media->caption = $request->input('description');
  1371. $media->save();
  1372. $resource = new Fractal\Resource\Item($media, new MediaTransformer());
  1373. $res = $this->fractal->createData($resource)->toArray();
  1374. return $this->json($res);
  1375. }
  1376. /**
  1377. * GET /api/v1/media/{id}
  1378. *
  1379. * @param integer $id
  1380. *
  1381. * @return MediaTransformer
  1382. */
  1383. public function mediaGet(Request $request, $id)
  1384. {
  1385. abort_if(!$request->user(), 403);
  1386. $user = $request->user();
  1387. $media = Media::whereUserId($user->id)
  1388. ->whereNull('status_id')
  1389. ->findOrFail($id);
  1390. $resource = new Fractal\Resource\Item($media, new MediaTransformer());
  1391. $res = $this->fractal->createData($resource)->toArray();
  1392. return $this->json($res);
  1393. }
  1394. /**
  1395. * POST /api/v2/media
  1396. *
  1397. *
  1398. * @return MediaTransformer
  1399. */
  1400. public function mediaUploadV2(Request $request)
  1401. {
  1402. abort_if(!$request->user(), 403);
  1403. $this->validate($request, [
  1404. 'file.*' => function() {
  1405. return [
  1406. 'required',
  1407. 'mimetypes:' . config_cache('pixelfed.media_types'),
  1408. 'max:' . config_cache('pixelfed.max_photo_size'),
  1409. ];
  1410. },
  1411. 'filter_name' => 'nullable|string|max:24',
  1412. 'filter_class' => 'nullable|alpha_dash|max:24',
  1413. 'description' => 'nullable|string|max:' . config_cache('pixelfed.max_altext_length')
  1414. ]);
  1415. $user = $request->user();
  1416. if($user->last_active_at == null) {
  1417. return [];
  1418. }
  1419. if(empty($request->file('file'))) {
  1420. return response('', 422);
  1421. }
  1422. $limitKey = 'compose:rate-limit:media-upload:' . $user->id;
  1423. $limitTtl = now()->addMinutes(15);
  1424. $limitReached = Cache::remember($limitKey, $limitTtl, function() use($user) {
  1425. $dailyLimit = Media::whereUserId($user->id)->where('created_at', '>', now()->subDays(1))->count();
  1426. return $dailyLimit >= 250;
  1427. });
  1428. abort_if($limitReached == true, 429);
  1429. $profile = $user->profile;
  1430. if(config_cache('pixelfed.enforce_account_limit') == true) {
  1431. $size = Cache::remember($user->storageUsedKey(), now()->addDays(3), function() use($user) {
  1432. return Media::whereUserId($user->id)->sum('size') / 1000;
  1433. });
  1434. $limit = (int) config_cache('pixelfed.max_account_size');
  1435. if ($size >= $limit) {
  1436. abort(403, 'Account size limit reached.');
  1437. }
  1438. }
  1439. $filterClass = in_array($request->input('filter_class'), Filter::classes()) ? $request->input('filter_class') : null;
  1440. $filterName = in_array($request->input('filter_name'), Filter::names()) ? $request->input('filter_name') : null;
  1441. $photo = $request->file('file');
  1442. $mimes = explode(',', config_cache('pixelfed.media_types'));
  1443. if(in_array($photo->getMimeType(), $mimes) == false) {
  1444. abort(403, 'Invalid or unsupported mime type.');
  1445. }
  1446. $storagePath = MediaPathService::get($user, 2);
  1447. $path = $photo->store($storagePath);
  1448. $hash = \hash_file('sha256', $photo);
  1449. $license = null;
  1450. $mime = $photo->getMimeType();
  1451. $settings = UserSetting::whereUserId($user->id)->first();
  1452. if($settings && !empty($settings->compose_settings)) {
  1453. $compose = $settings->compose_settings;
  1454. if(isset($compose['default_license']) && $compose['default_license'] != 1) {
  1455. $license = $compose['default_license'];
  1456. }
  1457. }
  1458. abort_if(MediaBlocklistService::exists($hash) == true, 451);
  1459. $media = new Media();
  1460. $media->status_id = null;
  1461. $media->profile_id = $profile->id;
  1462. $media->user_id = $user->id;
  1463. $media->media_path = $path;
  1464. $media->original_sha256 = $hash;
  1465. $media->size = $photo->getSize();
  1466. $media->mime = $mime;
  1467. $media->caption = $request->input('description');
  1468. $media->filter_class = $filterClass;
  1469. $media->filter_name = $filterName;
  1470. if($license) {
  1471. $media->license = $license;
  1472. }
  1473. $media->save();
  1474. switch ($media->mime) {
  1475. case 'image/jpeg':
  1476. case 'image/png':
  1477. ImageOptimize::dispatch($media);
  1478. break;
  1479. case 'video/mp4':
  1480. VideoThumbnail::dispatch($media);
  1481. $preview_url = '/storage/no-preview.png';
  1482. $url = '/storage/no-preview.png';
  1483. break;
  1484. }
  1485. Cache::forget($limitKey);
  1486. $resource = new Fractal\Resource\Item($media, new MediaTransformer());
  1487. $res = $this->fractal->createData($resource)->toArray();
  1488. $res['preview_url'] = $media->url(). '?v=' . time();
  1489. $res['url'] = null;
  1490. return $this->json($res, 202);
  1491. }
  1492. /**
  1493. * GET /api/v1/mutes
  1494. *
  1495. *
  1496. * @return AccountTransformer
  1497. */
  1498. public function accountMutes(Request $request)
  1499. {
  1500. abort_if(!$request->user(), 403);
  1501. $this->validate($request, [
  1502. 'limit' => 'nullable|integer|min:1|max:40'
  1503. ]);
  1504. $user = $request->user();
  1505. $limit = $request->input('limit', 40);
  1506. $mutes = UserFilter::whereUserId($user->profile_id)
  1507. ->whereFilterableType('App\Profile')
  1508. ->whereFilterType('mute')
  1509. ->orderByDesc('id')
  1510. ->simplePaginate($limit)
  1511. ->pluck('filterable_id')
  1512. ->map(function($id) {
  1513. return AccountService::get($id, true);
  1514. })
  1515. ->filter(function($account) {
  1516. return $account && isset($account['id']);
  1517. })
  1518. ->values();
  1519. return $this->json($mutes);
  1520. }
  1521. /**
  1522. * POST /api/v1/accounts/{id}/mute
  1523. *
  1524. * @param integer $id
  1525. *
  1526. * @return RelationshipTransformer
  1527. */
  1528. public function accountMuteById(Request $request, $id)
  1529. {
  1530. abort_if(!$request->user(), 403);
  1531. $user = $request->user();
  1532. $pid = $user->profile_id;
  1533. if(intval($pid) === intval($id)) {
  1534. return $this->json(['error' => 'You cannot mute yourself'], 500);
  1535. }
  1536. $account = Profile::findOrFail($id);
  1537. $filter = UserFilter::firstOrCreate([
  1538. 'user_id' => $pid,
  1539. 'filterable_id' => $account->id,
  1540. 'filterable_type' => 'App\Profile',
  1541. 'filter_type' => 'mute',
  1542. ]);
  1543. Cache::forget("user:filter:list:$pid");
  1544. Cache::forget("feature:discover:posts:$pid");
  1545. Cache::forget("api:local:exp:rec:$pid");
  1546. RelationshipService::refresh($pid, $id);
  1547. $resource = new Fractal\Resource\Item($account, new RelationshipTransformer());
  1548. $res = $this->fractal->createData($resource)->toArray();
  1549. return $this->json($res);
  1550. }
  1551. /**
  1552. * POST /api/v1/accounts/{id}/unmute
  1553. *
  1554. * @param integer $id
  1555. *
  1556. * @return RelationshipTransformer
  1557. */
  1558. public function accountUnmuteById(Request $request, $id)
  1559. {
  1560. abort_if(!$request->user(), 403);
  1561. $user = $request->user();
  1562. $pid = $user->profile_id;
  1563. if(intval($pid) === intval($id)) {
  1564. return $this->json(['error' => 'You cannot unmute yourself'], 500);
  1565. }
  1566. $account = Profile::findOrFail($id);
  1567. $filter = UserFilter::whereUserId($pid)
  1568. ->whereFilterableId($account->id)
  1569. ->whereFilterableType('App\Profile')
  1570. ->whereFilterType('mute')
  1571. ->first();
  1572. if($filter) {
  1573. $filter->delete();
  1574. Cache::forget("user:filter:list:$pid");
  1575. Cache::forget("feature:discover:posts:$pid");
  1576. Cache::forget("api:local:exp:rec:$pid");
  1577. RelationshipService::refresh($pid, $id);
  1578. }
  1579. $resource = new Fractal\Resource\Item($account, new RelationshipTransformer());
  1580. $res = $this->fractal->createData($resource)->toArray();
  1581. return $this->json($res);
  1582. }
  1583. /**
  1584. * GET /api/v1/notifications
  1585. *
  1586. *
  1587. * @return NotificationTransformer
  1588. */
  1589. public function accountNotifications(Request $request)
  1590. {
  1591. abort_if(!$request->user(), 403);
  1592. $this->validate($request, [
  1593. 'limit' => 'nullable|integer|min:1|max:100',
  1594. 'min_id' => 'nullable|integer|min:1|max:'.PHP_INT_MAX,
  1595. 'max_id' => 'nullable|integer|min:1|max:'.PHP_INT_MAX,
  1596. 'since_id' => 'nullable|integer|min:1|max:'.PHP_INT_MAX,
  1597. ]);
  1598. $pid = $request->user()->profile_id;
  1599. $limit = $request->input('limit', 20);
  1600. $since = $request->input('since_id');
  1601. $min = $request->input('min_id');
  1602. $max = $request->input('max_id');
  1603. if(!$since && !$min && !$max) {
  1604. $min = 1;
  1605. }
  1606. $maxId = null;
  1607. $minId = null;
  1608. if($max) {
  1609. $res = NotificationService::getMaxMastodon($pid, $max, $limit);
  1610. $ids = NotificationService::getRankedMaxId($pid, $max, $limit);
  1611. if(!empty($ids)) {
  1612. $maxId = max($ids);
  1613. $minId = min($ids);
  1614. }
  1615. } else {
  1616. $res = NotificationService::getMinMastodon($pid, $min ?? $since, $limit);
  1617. $ids = NotificationService::getRankedMinId($pid, $min ?? $since, $limit);
  1618. if(!empty($ids)) {
  1619. $maxId = max($ids);
  1620. $minId = min($ids);
  1621. }
  1622. }
  1623. if(empty($res) && !Cache::has('pf:services:notifications:hasSynced:'.$pid)) {
  1624. Cache::put('pf:services:notifications:hasSynced:'.$pid, 1, 1209600);
  1625. NotificationService::warmCache($pid, 400, true);
  1626. }
  1627. $baseUrl = config('app.url') . '/api/v1/notifications?limit=' . $limit . '&';
  1628. if($minId == $maxId) {
  1629. $minId = null;
  1630. }
  1631. if($maxId) {
  1632. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next"';
  1633. }
  1634. if($minId) {
  1635. $link = '<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  1636. }
  1637. if($maxId && $minId) {
  1638. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next",<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  1639. }
  1640. $headers = isset($link) ? ['Link' => $link] : [];
  1641. return $this->json($res, 200, $headers);
  1642. }
  1643. /**
  1644. * GET /api/v1/timelines/home
  1645. *
  1646. *
  1647. * @return StatusTransformer
  1648. */
  1649. public function timelineHome(Request $request)
  1650. {
  1651. $this->validate($request,[
  1652. 'page' => 'nullable|integer|max:40',
  1653. 'min_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  1654. 'max_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  1655. 'limit' => 'nullable|integer|max:100'
  1656. ]);
  1657. $napi = $request->has(self::PF_API_ENTITY_KEY);
  1658. $page = $request->input('page');
  1659. $min = $request->input('min_id');
  1660. $max = $request->input('max_id');
  1661. $limit = $request->input('limit') ?? 20;
  1662. $pid = $request->user()->profile_id;
  1663. $following = Cache::remember('profile:following:'.$pid, now()->addMinutes(1440), function() use($pid) {
  1664. $following = Follower::whereProfileId($pid)->pluck('following_id');
  1665. return $following->push($pid)->toArray();
  1666. });
  1667. if($min || $max) {
  1668. $dir = $min ? '>' : '<';
  1669. $id = $min ?? $max;
  1670. $res = Status::select(
  1671. 'id',
  1672. 'profile_id',
  1673. 'type',
  1674. 'visibility',
  1675. 'created_at'
  1676. )
  1677. ->whereIn('type', ['photo', 'photo:album', 'video', 'video:album', 'photo:video:album'])
  1678. ->where('id', $dir, $id)
  1679. ->whereIn('profile_id', $following)
  1680. ->whereIn('visibility',['public', 'unlisted', 'private'])
  1681. ->latest()
  1682. ->take(($limit * 2))
  1683. ->get()
  1684. ->map(function($s) use($pid, $napi) {
  1685. $status = $napi ? StatusService::get($s['id'], false) : StatusService::getMastodon($s['id'], false);
  1686. if(!$status || !isset($status['account']) || !isset($status['account']['id'])) {
  1687. return false;
  1688. }
  1689. if($pid) {
  1690. $status['favourited'] = (bool) LikeService::liked($pid, $s['id']);
  1691. $status['reblogged'] = (bool) ReblogService::get($pid, $status['id']);
  1692. }
  1693. return $status;
  1694. })
  1695. ->filter(function($status) {
  1696. return $status && isset($status['account']);
  1697. })
  1698. ->take($limit)
  1699. ->values();
  1700. } else {
  1701. $res = Status::select(
  1702. 'id',
  1703. 'profile_id',
  1704. 'type',
  1705. 'visibility',
  1706. 'created_at'
  1707. )
  1708. ->whereIn('type', ['photo', 'photo:album', 'video', 'video:album', 'photo:video:album'])
  1709. ->whereIn('profile_id', $following)
  1710. ->whereIn('visibility',['public', 'unlisted', 'private'])
  1711. ->latest()
  1712. ->take(($limit * 2))
  1713. ->get()
  1714. ->map(function($s) use($pid, $napi) {
  1715. $status = $napi ? StatusService::get($s['id'], false) : StatusService::getMastodon($s['id'], false);
  1716. if(!$status || !isset($status['account']) || !isset($status['account']['id'])) {
  1717. return false;
  1718. }
  1719. if($pid) {
  1720. $status['favourited'] = (bool) LikeService::liked($pid, $s['id']);
  1721. $status['reblogged'] = (bool) ReblogService::get($pid, $status['id']);
  1722. }
  1723. return $status;
  1724. })
  1725. ->filter(function($status) {
  1726. return $status && isset($status['account']);
  1727. })
  1728. ->take($limit)
  1729. ->values();
  1730. }
  1731. $baseUrl = config('app.url') . '/api/v1/timelines/home?limit=' . $limit . '&';
  1732. $minId = $res->map(function($s) {
  1733. return ['id' => $s['id']];
  1734. })->min('id');
  1735. $maxId = $res->map(function($s) {
  1736. return ['id' => $s['id']];
  1737. })->max('id');
  1738. if($minId == $maxId) {
  1739. $minId = null;
  1740. }
  1741. if($maxId) {
  1742. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next"';
  1743. }
  1744. if($minId) {
  1745. $link = '<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  1746. }
  1747. if($maxId && $minId) {
  1748. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next",<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  1749. }
  1750. $headers = isset($link) ? ['Link' => $link] : [];
  1751. return $this->json($res->toArray(), 200, $headers);
  1752. }
  1753. /**
  1754. * GET /api/v1/timelines/public
  1755. *
  1756. *
  1757. * @return StatusTransformer
  1758. */
  1759. public function timelinePublic(Request $request)
  1760. {
  1761. $this->validate($request,[
  1762. 'min_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  1763. 'max_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  1764. 'limit' => 'nullable|integer|max:100',
  1765. 'remote' => 'sometimes',
  1766. 'local' => 'sometimes'
  1767. ]);
  1768. $napi = $request->has(self::PF_API_ENTITY_KEY);
  1769. $min = $request->input('min_id');
  1770. $max = $request->input('max_id');
  1771. $limit = $request->input('limit') ?? 20;
  1772. $user = $request->user();
  1773. $remote = ($request->has('remote') && $request->input('remote') == true) || ($request->filled('local') && $request->input('local') != true);
  1774. $filtered = $user ? UserFilterService::filters($user->profile_id) : [];
  1775. if((!$request->has('local') || $remote) && config('instance.timeline.network.cached')) {
  1776. Cache::remember('api:v1:timelines:network:cache_check', 10368000, function() {
  1777. if(NetworkTimelineService::count() == 0) {
  1778. NetworkTimelineService::warmCache(true, config('instance.timeline.network.cache_dropoff'));
  1779. }
  1780. });
  1781. if ($max) {
  1782. $feed = NetworkTimelineService::getRankedMaxId($max, $limit + 5);
  1783. } else if ($min) {
  1784. $feed = NetworkTimelineService::getRankedMinId($min, $limit + 5);
  1785. } else {
  1786. $feed = NetworkTimelineService::get(0, $limit + 5);
  1787. }
  1788. } else {
  1789. Cache::remember('api:v1:timelines:public:cache_check', 10368000, function() {
  1790. if(PublicTimelineService::count() == 0) {
  1791. PublicTimelineService::warmCache(true, 400);
  1792. }
  1793. });
  1794. if ($max) {
  1795. $feed = PublicTimelineService::getRankedMaxId($max, $limit + 5);
  1796. } else if ($min) {
  1797. $feed = PublicTimelineService::getRankedMinId($min, $limit + 5);
  1798. } else {
  1799. $feed = PublicTimelineService::get(0, $limit + 5);
  1800. }
  1801. }
  1802. $res = collect($feed)
  1803. ->filter(function($k) use($min, $max) {
  1804. if(!$min && !$max) {
  1805. return true;
  1806. }
  1807. if($min) {
  1808. return $min != $k;
  1809. }
  1810. if($max) {
  1811. return $max != $k;
  1812. }
  1813. })
  1814. ->map(function($k) use($user, $napi) {
  1815. $status = $napi ? StatusService::get($k) : StatusService::getMastodon($k);
  1816. if(!$status || !isset($status['account']) || !isset($status['account']['id'])) {
  1817. return false;
  1818. }
  1819. if($user) {
  1820. $status['favourited'] = (bool) LikeService::liked($user->profile_id, $k);
  1821. $status['reblogged'] = (bool) ReblogService::get($user->profile_id, $status['id']);
  1822. }
  1823. return $status;
  1824. })
  1825. ->filter(function($s) use($filtered) {
  1826. return $s && isset($s['account']) && in_array($s['account']['id'], $filtered) == false;
  1827. })
  1828. ->take($limit)
  1829. ->values();
  1830. $baseUrl = config('app.url') . '/api/v1/timelines/public?limit=' . $limit . '&';
  1831. if($remote) {
  1832. $baseUrl .= 'remote=1&';
  1833. }
  1834. $minId = $res->map(function($s) {
  1835. return ['id' => $s['id']];
  1836. })->min('id');
  1837. $maxId = $res->map(function($s) {
  1838. return ['id' => $s['id']];
  1839. })->max('id');
  1840. if($minId == $maxId) {
  1841. $minId = null;
  1842. }
  1843. if($maxId) {
  1844. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next"';
  1845. }
  1846. if($minId) {
  1847. $link = '<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  1848. }
  1849. if($maxId && $minId) {
  1850. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next",<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  1851. }
  1852. $headers = isset($link) ? ['Link' => $link] : [];
  1853. return $this->json($res->toArray(), 200, $headers);
  1854. }
  1855. /**
  1856. * GET /api/v1/conversations
  1857. *
  1858. * Not implemented
  1859. *
  1860. * @return array
  1861. */
  1862. public function conversations(Request $request)
  1863. {
  1864. abort_if(!$request->user(), 403);
  1865. $this->validate($request, [
  1866. 'limit' => 'min:1|max:40',
  1867. 'scope' => 'nullable|in:inbox,sent,requests'
  1868. ]);
  1869. $limit = $request->input('limit', 20);
  1870. $scope = $request->input('scope', 'inbox');
  1871. $pid = $request->user()->profile_id;
  1872. if(config('database.default') == 'pgsql') {
  1873. $dms = DirectMessage::when($scope === 'inbox', function($q, $scope) use($pid) {
  1874. return $q->whereIsHidden(false)->where('to_id', $pid)->orWhere('from_id', $pid);
  1875. })
  1876. ->when($scope === 'sent', function($q, $scope) use($pid) {
  1877. return $q->whereFromId($pid)->groupBy(['to_id', 'id']);
  1878. })
  1879. ->when($scope === 'requests', function($q, $scope) use($pid) {
  1880. return $q->whereToId($pid)->whereIsHidden(true);
  1881. });
  1882. } else {
  1883. $dms = Conversation::when($scope === 'inbox', function($q, $scope) use($pid) {
  1884. return $q->whereIsHidden(false)
  1885. ->where('to_id', $pid)
  1886. ->orWhere('from_id', $pid)
  1887. ->orderByDesc('status_id')
  1888. ->groupBy(['to_id', 'from_id']);
  1889. })
  1890. ->when($scope === 'sent', function($q, $scope) use($pid) {
  1891. return $q->whereFromId($pid)->groupBy('to_id');
  1892. })
  1893. ->when($scope === 'requests', function($q, $scope) use($pid) {
  1894. return $q->whereToId($pid)->whereIsHidden(true);
  1895. });
  1896. }
  1897. $dms = $dms->orderByDesc('status_id')
  1898. ->simplePaginate($limit)
  1899. ->map(function($dm) use($pid) {
  1900. $from = $pid == $dm->to_id ? $dm->from_id : $dm->to_id;
  1901. $res = [
  1902. 'id' => $dm->id,
  1903. 'unread' => false,
  1904. 'accounts' => [
  1905. AccountService::getMastodon($from)
  1906. ],
  1907. 'last_status' => StatusService::getDirectMessage($dm->status_id)
  1908. ];
  1909. return $res;
  1910. })
  1911. ->filter(function($dm) {
  1912. return isset($dm['accounts']) && count($dm['accounts']);
  1913. })
  1914. ->unique(function($item, $key) {
  1915. return $item['accounts'][0]['id'];
  1916. })
  1917. ->values();
  1918. return $this->json($dms);
  1919. }
  1920. /**
  1921. * GET /api/v1/statuses/{id}
  1922. *
  1923. * @param integer $id
  1924. *
  1925. * @return StatusTransformer
  1926. */
  1927. public function statusById(Request $request, $id)
  1928. {
  1929. abort_if(!$request->user(), 403);
  1930. $user = $request->user();
  1931. $res = $request->has(self::PF_API_ENTITY_KEY) ? StatusService::get($id, false) : StatusService::getMastodon($id, false);
  1932. if(!$res || !isset($res['visibility'])) {
  1933. abort(404);
  1934. }
  1935. $scope = $res['visibility'];
  1936. if(!in_array($scope, ['public', 'unlisted'])) {
  1937. if($scope === 'private') {
  1938. if(intval($res['account']['id']) !== intval($user->profile_id)) {
  1939. abort_unless(FollowerService::follows($user->profile_id, $res['account']['id']), 403);
  1940. }
  1941. } else {
  1942. abort(400, 'Invalid request');
  1943. }
  1944. }
  1945. $res['favourited'] = LikeService::liked($user->profile_id, $res['id']);
  1946. $res['reblogged'] = ReblogService::get($user->profile_id, $res['id']);
  1947. return $this->json($res);
  1948. }
  1949. /**
  1950. * GET /api/v1/statuses/{id}/context
  1951. *
  1952. * @param integer $id
  1953. *
  1954. * @return StatusTransformer
  1955. */
  1956. public function statusContext(Request $request, $id)
  1957. {
  1958. abort_if(!$request->user(), 403);
  1959. $user = $request->user();
  1960. $pid = $user->profile_id;
  1961. $status = StatusService::getMastodon($id, false);
  1962. if(!$status || !isset($status['account'])) {
  1963. return response('', 404);
  1964. }
  1965. if(intval($status['account']['id']) !== intval($user->profile_id)) {
  1966. if($status['visibility'] == 'private') {
  1967. if(!FollowerService::follows($user->profile_id, $status['account']['id'])) {
  1968. return response('', 404);
  1969. }
  1970. } else {
  1971. if(!in_array($status['visibility'], ['public','unlisted'])) {
  1972. return response('', 404);
  1973. }
  1974. }
  1975. }
  1976. $ancestors = [];
  1977. $descendants = [];
  1978. if($status['in_reply_to_id']) {
  1979. $ancestors[] = StatusService::getMastodon($status['in_reply_to_id'], false);
  1980. }
  1981. if($status['replies_count']) {
  1982. $descendants = DB::table('statuses')
  1983. ->where('in_reply_to_id', $id)
  1984. ->limit(20)
  1985. ->pluck('id')
  1986. ->map(function($sid) {
  1987. return StatusService::getMastodon($sid, false);
  1988. })
  1989. ->filter(function($post) {
  1990. return $post && isset($post['account']);
  1991. })
  1992. ->map(function($status) use($pid) {
  1993. $status['favourited'] = LikeService::liked($pid, $status['id']);
  1994. $status['reblogged'] = ReblogService::get($pid, $status['id']);
  1995. return $status;
  1996. })
  1997. ->values();
  1998. }
  1999. $res = [
  2000. 'ancestors' => $ancestors,
  2001. 'descendants' => $descendants
  2002. ];
  2003. return $this->json($res);
  2004. }
  2005. /**
  2006. * GET /api/v1/statuses/{id}/card
  2007. *
  2008. * @param integer $id
  2009. *
  2010. * @return StatusTransformer
  2011. */
  2012. public function statusCard(Request $request, $id)
  2013. {
  2014. abort_if(!$request->user(), 403);
  2015. $res = [];
  2016. return response()->json($res);
  2017. }
  2018. /**
  2019. * GET /api/v1/statuses/{id}/reblogged_by
  2020. *
  2021. * @param integer $id
  2022. *
  2023. * @return AccountTransformer
  2024. */
  2025. public function statusRebloggedBy(Request $request, $id)
  2026. {
  2027. abort_if(!$request->user(), 403);
  2028. $this->validate($request, [
  2029. 'page' => 'nullable|integer|min:1|max:40',
  2030. 'limit' => 'nullable|integer|min:1|max:100'
  2031. ]);
  2032. $limit = $request->input('limit') ?? 40;
  2033. $user = $request->user();
  2034. $status = Status::findOrFail($id);
  2035. if(intval($status->profile_id) !== intval($user->profile_id)) {
  2036. if($status->scope == 'private') {
  2037. abort_if(!FollowerService::follows($user->profile_id, $status->profile_id), 403);
  2038. } else {
  2039. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  2040. }
  2041. }
  2042. $page = $request->input('page', 1);
  2043. $start = $page == 1 ? 0 : (($page * $limit) - $limit);
  2044. $end = $start + $limit - 1;
  2045. $ids = ReblogService::getPostReblogs($id, $start, $end);
  2046. if(empty($ids)) {
  2047. return [];
  2048. }
  2049. $res = collect($ids)
  2050. ->map(function($id) {
  2051. $status = StatusService::get($id);
  2052. if($status) {
  2053. return AccountService::get($status['account']['id']);
  2054. }
  2055. return;
  2056. })
  2057. ->filter(function($account) {
  2058. return $account && isset($account['id']);
  2059. })
  2060. ->values();
  2061. $url = $request->url();
  2062. $page = $request->input('page', 1);
  2063. $next = $page < 40 ? $page + 1 : 40;
  2064. $prev = $page > 1 ? $page - 1 : 1;
  2065. $links = '<'.$url.'?page='.$next.'&limit='.$limit.'>; rel="next", <'.$url.'?page='.$prev.'&limit='.$limit.'>; rel="prev"';
  2066. return $this->json($res, 200, ['Link' => $links]);
  2067. }
  2068. /**
  2069. * GET /api/v1/statuses/{id}/favourited_by
  2070. *
  2071. * @param integer $id
  2072. *
  2073. * @return AccountTransformer
  2074. */
  2075. public function statusFavouritedBy(Request $request, $id)
  2076. {
  2077. abort_if(!$request->user(), 403);
  2078. $this->validate($request, [
  2079. 'page' => 'nullable|integer|min:1|max:40',
  2080. 'limit' => 'nullable|integer|min:1|max:100'
  2081. ]);
  2082. $page = $request->input('page', 1);
  2083. $limit = $request->input('limit') ?? 40;
  2084. $user = $request->user();
  2085. $status = Status::findOrFail($id);
  2086. $offset = $page == 1 ? 0 : ($page * $limit - $limit);
  2087. if($offset > 100) {
  2088. if($user->profile_id != $status->profile_id) {
  2089. return [];
  2090. }
  2091. }
  2092. if(intval($status->profile_id) !== intval($user->profile_id)) {
  2093. if($status->scope == 'private') {
  2094. abort_if(!$status->profile->followedBy($user->profile), 403);
  2095. } else {
  2096. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  2097. }
  2098. }
  2099. $res = DB::table('likes')
  2100. ->select('likes.id', 'likes.profile_id', 'likes.status_id', 'followers.created_at')
  2101. ->leftJoin('followers', function($join) use($user, $status) {
  2102. return $join->on('likes.profile_id', '=', 'followers.following_id')
  2103. ->where('followers.profile_id', $user->profile_id)
  2104. ->where('likes.status_id', $status->id);
  2105. })
  2106. ->whereStatusId($status->id)
  2107. ->orderByDesc('followers.created_at')
  2108. ->offset($offset)
  2109. ->limit($limit)
  2110. ->get()
  2111. ->map(function($like) {
  2112. $account = AccountService::getMastodon($like->profile_id, true);
  2113. $account['follows'] = isset($like->created_at);
  2114. return $account;
  2115. })
  2116. ->filter(function($account) use($user) {
  2117. return $account && isset($account['id']);
  2118. })
  2119. ->values();
  2120. $url = $request->url();
  2121. $page = $request->input('page', 1);
  2122. $next = $page < 40 ? $page + 1 : 40;
  2123. $prev = $page > 1 ? $page - 1 : 1;
  2124. $links = '<'.$url.'?page='.$next.'&limit='.$limit.'>; rel="next", <'.$url.'?page='.$prev.'&limit='.$limit.'>; rel="prev"';
  2125. return $this->json($res, 200, ['Link' => $links]);
  2126. }
  2127. /**
  2128. * POST /api/v1/statuses
  2129. *
  2130. *
  2131. * @return StatusTransformer
  2132. */
  2133. public function statusCreate(Request $request)
  2134. {
  2135. abort_if(!$request->user(), 403);
  2136. $this->validate($request, [
  2137. 'status' => 'nullable|string',
  2138. 'in_reply_to_id' => 'nullable',
  2139. 'media_ids' => 'sometimes|array|max:' . config_cache('pixelfed.max_album_length'),
  2140. 'sensitive' => 'nullable',
  2141. 'visibility' => 'string|in:private,unlisted,public',
  2142. 'spoiler_text' => 'sometimes|max:140',
  2143. 'place_id' => 'sometimes|integer|min:1|max:128769',
  2144. 'collection_ids' => 'sometimes|array|max:3',
  2145. 'comments_disabled' => 'sometimes|boolean',
  2146. ]);
  2147. if(config('costar.enabled') == true) {
  2148. $blockedKeywords = config('costar.keyword.block');
  2149. if($blockedKeywords !== null && $request->status) {
  2150. $keywords = config('costar.keyword.block');
  2151. foreach($keywords as $kw) {
  2152. if(Str::contains($request->status, $kw) == true) {
  2153. abort(400, 'Invalid object. Contains banned keyword.');
  2154. }
  2155. }
  2156. }
  2157. }
  2158. if(!$request->filled('media_ids') && !$request->filled('in_reply_to_id')) {
  2159. abort(403, 'Empty statuses are not allowed');
  2160. }
  2161. $ids = $request->input('media_ids');
  2162. $in_reply_to_id = $request->input('in_reply_to_id');
  2163. $user = $request->user();
  2164. $profile = $user->profile;
  2165. $limitKey = 'compose:rate-limit:store:' . $user->id;
  2166. $limitTtl = now()->addMinutes(15);
  2167. $limitReached = Cache::remember($limitKey, $limitTtl, function() use($user) {
  2168. $dailyLimit = Status::whereProfileId($user->profile_id)
  2169. ->whereNull('in_reply_to_id')
  2170. ->whereNull('reblog_of_id')
  2171. ->where('created_at', '>', now()->subDays(1))
  2172. ->count();
  2173. return $dailyLimit >= 100;
  2174. });
  2175. abort_if($limitReached == true, 429);
  2176. $visibility = $profile->is_private ? 'private' : (
  2177. $profile->unlisted == true &&
  2178. $request->input('visibility', 'public') == 'public' ?
  2179. 'unlisted' :
  2180. $request->input('visibility', 'public'));
  2181. if($user->last_active_at == null) {
  2182. return [];
  2183. }
  2184. $content = strip_tags($request->input('status'));
  2185. $rendered = Autolink::create()->autolink($content);
  2186. $cw = $user->profile->cw == true ? true : $request->input('sensitive', false);
  2187. $spoilerText = $cw && $request->filled('spoiler_text') ? $request->input('spoiler_text') : null;
  2188. if($in_reply_to_id) {
  2189. $parent = Status::findOrFail($in_reply_to_id);
  2190. if($parent->comments_disabled) {
  2191. return $this->json("Comments have been disabled on this post", 422);
  2192. }
  2193. $blocks = UserFilterService::blocks($parent->profile_id);
  2194. abort_if(in_array($profile->id, $blocks), 422, 'Cannot reply to this post at this time.');
  2195. $status = new Status;
  2196. $status->caption = $content;
  2197. $status->rendered = $rendered;
  2198. $status->scope = $visibility;
  2199. $status->visibility = $visibility;
  2200. $status->profile_id = $user->profile_id;
  2201. $status->is_nsfw = $cw;
  2202. $status->cw_summary = $spoilerText;
  2203. $status->in_reply_to_id = $parent->id;
  2204. $status->in_reply_to_profile_id = $parent->profile_id;
  2205. $status->save();
  2206. StatusService::del($parent->id);
  2207. Cache::forget('status:replies:all:' . $parent->id);
  2208. }
  2209. if($ids) {
  2210. if(Media::whereUserId($user->id)
  2211. ->whereNull('status_id')
  2212. ->find($ids)
  2213. ->count() == 0
  2214. ) {
  2215. abort(400, 'Invalid media_ids');
  2216. }
  2217. if(!$in_reply_to_id) {
  2218. $status = new Status;
  2219. $status->caption = $content;
  2220. $status->rendered = $rendered;
  2221. $status->profile_id = $user->profile_id;
  2222. $status->scope = 'draft';
  2223. $status->is_nsfw = $cw;
  2224. $status->cw_summary = $spoilerText;
  2225. if($request->has('place_id')) {
  2226. $status->place_id = $request->input('place_id');
  2227. }
  2228. $status->save();
  2229. }
  2230. $mimes = [];
  2231. foreach($ids as $k => $v) {
  2232. if($k + 1 > config_cache('pixelfed.max_album_length')) {
  2233. continue;
  2234. }
  2235. $m = Media::whereUserId($user->id)->whereNull('status_id')->findOrFail($v);
  2236. if($m->profile_id !== $user->profile_id || $m->status_id) {
  2237. abort(403, 'Invalid media id');
  2238. }
  2239. $m->status_id = $status->id;
  2240. $m->save();
  2241. array_push($mimes, $m->mime);
  2242. }
  2243. if(empty($mimes)) {
  2244. $status->delete();
  2245. abort(400, 'Invalid media ids');
  2246. }
  2247. if($request->has('comments_disabled') && $request->input('comments_disabled')) {
  2248. $status->comments_disabled = true;
  2249. }
  2250. $status->scope = $visibility;
  2251. $status->visibility = $visibility;
  2252. $status->type = StatusController::mimeTypeCheck($mimes);
  2253. $status->save();
  2254. }
  2255. if(!$status) {
  2256. abort(500, 'An error occured.');
  2257. }
  2258. NewStatusPipeline::dispatch($status);
  2259. if($status->in_reply_to_id) {
  2260. CommentPipeline::dispatch($parent, $status);
  2261. }
  2262. Cache::forget('user:account:id:'.$user->id);
  2263. Cache::forget('_api:statuses:recent_9:'.$user->profile_id);
  2264. Cache::forget('profile:status_count:'.$user->profile_id);
  2265. Cache::forget($user->storageUsedKey());
  2266. Cache::forget('profile:embed:' . $status->profile_id);
  2267. Cache::forget($limitKey);
  2268. if($request->has('collection_ids') && $ids) {
  2269. $collections = Collection::whereProfileId($user->profile_id)
  2270. ->find($request->input('collection_ids'))
  2271. ->each(function($collection) use($status) {
  2272. $count = $collection->items()->count();
  2273. $item = CollectionItem::firstOrCreate([
  2274. 'collection_id' => $collection->id,
  2275. 'object_type' => 'App\Status',
  2276. 'object_id' => $status->id
  2277. ],[
  2278. 'order' => $count,
  2279. ]);
  2280. CollectionService::addItem(
  2281. $collection->id,
  2282. $status->id,
  2283. $count
  2284. );
  2285. $collection->updated_at = now();
  2286. $collection->save();
  2287. CollectionService::setCollection($collection->id, $collection);
  2288. });
  2289. }
  2290. $res = StatusService::getMastodon($status->id, false);
  2291. $res['favourited'] = false;
  2292. $res['language'] = 'en';
  2293. $res['bookmarked'] = false;
  2294. $res['card'] = null;
  2295. return $this->json($res);
  2296. }
  2297. /**
  2298. * DELETE /api/v1/statuses
  2299. *
  2300. * @param integer $id
  2301. *
  2302. * @return null
  2303. */
  2304. public function statusDelete(Request $request, $id)
  2305. {
  2306. abort_if(!$request->user(), 403);
  2307. $status = Status::whereProfileId($request->user()->profile->id)
  2308. ->findOrFail($id);
  2309. $resource = new Fractal\Resource\Item($status, new StatusTransformer());
  2310. Cache::forget('profile:status_count:'.$status->profile_id);
  2311. StatusDelete::dispatch($status);
  2312. $res = $this->fractal->createData($resource)->toArray();
  2313. $res['text'] = $res['content'];
  2314. unset($res['content']);
  2315. return $this->json($res);
  2316. }
  2317. /**
  2318. * POST /api/v1/statuses/{id}/reblog
  2319. *
  2320. * @param integer $id
  2321. *
  2322. * @return StatusTransformer
  2323. */
  2324. public function statusShare(Request $request, $id)
  2325. {
  2326. abort_if(!$request->user(), 403);
  2327. $user = $request->user();
  2328. $status = Status::whereScope('public')->findOrFail($id);
  2329. if(intval($status->profile_id) !== intval($user->profile_id)) {
  2330. if($status->scope == 'private') {
  2331. abort_if(!FollowerService::follows($user->profile_id, $status->profile_id), 403);
  2332. } else {
  2333. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  2334. }
  2335. $blocks = UserFilterService::blocks($status->profile_id);
  2336. if($blocks && in_array($user->profile_id, $blocks)) {
  2337. abort(422);
  2338. }
  2339. }
  2340. $share = Status::firstOrCreate([
  2341. 'profile_id' => $user->profile_id,
  2342. 'reblog_of_id' => $status->id,
  2343. 'type' => 'share',
  2344. 'in_reply_to_profile_id' => $status->profile_id,
  2345. 'scope' => 'public',
  2346. 'visibility' => 'public'
  2347. ]);
  2348. if($share->wasRecentlyCreated == true) {
  2349. SharePipeline::dispatch($share);
  2350. }
  2351. StatusService::del($status->id);
  2352. ReblogService::add($user->profile_id, $status->id);
  2353. $res = StatusService::getMastodon($status->id);
  2354. $res['reblogged'] = true;
  2355. return $this->json($res);
  2356. }
  2357. /**
  2358. * POST /api/v1/statuses/{id}/unreblog
  2359. *
  2360. * @param integer $id
  2361. *
  2362. * @return StatusTransformer
  2363. */
  2364. public function statusUnshare(Request $request, $id)
  2365. {
  2366. abort_if(!$request->user(), 403);
  2367. $user = $request->user();
  2368. $status = Status::whereScope('public')->findOrFail($id);
  2369. if(intval($status->profile_id) !== intval($user->profile_id)) {
  2370. if($status->scope == 'private') {
  2371. abort_if(!FollowerService::follows($user->profile_id, $status->profile_id), 403);
  2372. } else {
  2373. abort_if(!in_array($status->scope, ['public','unlisted']), 403);
  2374. }
  2375. }
  2376. $reblog = Status::whereProfileId($user->profile_id)
  2377. ->whereReblogOfId($status->id)
  2378. ->first();
  2379. if(!$reblog) {
  2380. $res = StatusService::getMastodon($status->id);
  2381. $res['reblogged'] = false;
  2382. return $this->json($res);
  2383. }
  2384. UndoSharePipeline::dispatch($reblog);
  2385. ReblogService::del($user->profile_id, $status->id);
  2386. $res = StatusService::getMastodon($status->id);
  2387. $res['reblogged'] = false;
  2388. return $this->json($res);
  2389. }
  2390. /**
  2391. * GET /api/v1/timelines/tag/{hashtag}
  2392. *
  2393. * @param string $hashtag
  2394. *
  2395. * @return StatusTransformer
  2396. */
  2397. public function timelineHashtag(Request $request, $hashtag)
  2398. {
  2399. $this->validate($request,[
  2400. 'page' => 'nullable|integer|max:40',
  2401. 'min_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  2402. 'max_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  2403. 'limit' => 'nullable|integer|max:100'
  2404. ]);
  2405. $tag = Hashtag::whereName($hashtag)
  2406. ->orWhere('slug', $hashtag)
  2407. ->first();
  2408. if(!$tag) {
  2409. return response()->json([]);
  2410. }
  2411. $min = $request->input('min_id');
  2412. $max = $request->input('max_id');
  2413. $limit = $request->input('limit', 20);
  2414. if(!$min && !$max) {
  2415. $id = 1;
  2416. $dir = '>';
  2417. } else {
  2418. $dir = $min ? '>' : '<';
  2419. $id = $min ?? $max;
  2420. }
  2421. $res = StatusHashtag::whereHashtagId($tag->id)
  2422. ->whereStatusVisibility('public')
  2423. ->where('status_id', $dir, $id)
  2424. ->latest()
  2425. ->limit($limit)
  2426. ->pluck('status_id')
  2427. ->map(function ($i) {
  2428. if($i) {
  2429. return StatusService::getMastodon($i);
  2430. }
  2431. })
  2432. ->filter(function($i) {
  2433. return $i && isset($i['account']);
  2434. })
  2435. ->values()
  2436. ->toArray();
  2437. return $this->json($res);
  2438. }
  2439. /**
  2440. * GET /api/v1/bookmarks
  2441. *
  2442. *
  2443. *
  2444. * @return StatusTransformer
  2445. */
  2446. public function bookmarks(Request $request)
  2447. {
  2448. abort_if(!$request->user(), 403);
  2449. $this->validate($request, [
  2450. 'limit' => 'nullable|integer|min:1|max:40',
  2451. 'max_id' => 'nullable|integer|min:0',
  2452. 'since_id' => 'nullable|integer|min:0',
  2453. 'min_id' => 'nullable|integer|min:0'
  2454. ]);
  2455. $pid = $request->user()->profile_id;
  2456. $limit = $request->input('limit') ?? 20;
  2457. $max_id = $request->input('max_id');
  2458. $since_id = $request->input('since_id');
  2459. $min_id = $request->input('min_id');
  2460. $dir = $min_id ? '>' : '<';
  2461. $id = $min_id ?? $max_id;
  2462. if($id) {
  2463. $bookmarks = Bookmark::whereProfileId($pid)
  2464. ->where('status_id', $dir, $id)
  2465. ->limit($limit)
  2466. ->pluck('status_id');
  2467. } else {
  2468. $bookmarks = Bookmark::whereProfileId($pid)
  2469. ->latest()
  2470. ->limit($limit)
  2471. ->pluck('status_id');
  2472. }
  2473. $res = [];
  2474. foreach($bookmarks as $id) {
  2475. $res[] = \App\Services\StatusService::getMastodon($id);
  2476. }
  2477. return $this->json($res);
  2478. }
  2479. /**
  2480. * POST /api/v1/statuses/{id}/bookmark
  2481. *
  2482. *
  2483. *
  2484. * @return StatusTransformer
  2485. */
  2486. public function bookmarkStatus(Request $request, $id)
  2487. {
  2488. abort_if(!$request->user(), 403);
  2489. $status = Status::whereNull('uri')
  2490. ->whereScope('public')
  2491. ->findOrFail($id);
  2492. Bookmark::firstOrCreate([
  2493. 'status_id' => $status->id,
  2494. 'profile_id' => $request->user()->profile_id
  2495. ]);
  2496. $res = StatusService::getMastodon($status->id);
  2497. return $this->json($res);
  2498. }
  2499. /**
  2500. * POST /api/v1/statuses/{id}/unbookmark
  2501. *
  2502. *
  2503. *
  2504. * @return StatusTransformer
  2505. */
  2506. public function unbookmarkStatus(Request $request, $id)
  2507. {
  2508. abort_if(!$request->user(), 403);
  2509. $status = Status::whereNull('uri')
  2510. ->whereScope('public')
  2511. ->findOrFail($id);
  2512. $bookmark = Bookmark::whereStatusId($status->id)
  2513. ->whereProfileId($request->user()->profile_id)
  2514. ->firstOrFail();
  2515. $bookmark->delete();
  2516. $res = StatusService::getMastodon($status->id);
  2517. return $this->json($res);
  2518. }
  2519. /**
  2520. * GET /api/v2/search
  2521. *
  2522. *
  2523. * @return array
  2524. */
  2525. public function searchV2(Request $request)
  2526. {
  2527. abort_if(!$request->user(), 403);
  2528. $this->validate($request, [
  2529. 'q' => 'required|string|min:1|max:100',
  2530. 'account_id' => 'nullable|string',
  2531. 'max_id' => 'nullable|string',
  2532. 'min_id' => 'nullable|string',
  2533. 'type' => 'nullable|in:accounts,hashtags,statuses',
  2534. 'exclude_unreviewed' => 'nullable',
  2535. 'resolve' => 'nullable',
  2536. 'limit' => 'nullable|integer|max:40',
  2537. 'offset' => 'nullable|integer',
  2538. 'following' => 'nullable'
  2539. ]);
  2540. return $this->json(SearchApiV2Service::query($request, true));
  2541. }
  2542. /**
  2543. * GET /api/v1/discover/posts
  2544. *
  2545. *
  2546. * @return array
  2547. */
  2548. public function discoverPosts(Request $request)
  2549. {
  2550. abort_if(!$request->user(), 403);
  2551. $this->validate($request, [
  2552. 'limit' => 'integer|min:1|max:40'
  2553. ]);
  2554. $limit = $request->input('limit', 40);
  2555. $pid = $request->user()->profile_id;
  2556. $filters = UserFilterService::filters($pid);
  2557. $forYou = DiscoverService::getForYou();
  2558. $posts = $forYou->take(50)->map(function($post) {
  2559. return StatusService::getMastodon($post);
  2560. })
  2561. ->filter(function($post) use($filters) {
  2562. return $post &&
  2563. isset($post['account']) &&
  2564. isset($post['account']['id']) &&
  2565. !in_array($post['account']['id'], $filters);
  2566. })
  2567. ->take(12)
  2568. ->values();
  2569. return $this->json(compact('posts'));
  2570. }
  2571. /**
  2572. * GET /api/v2/statuses/{id}/replies
  2573. *
  2574. *
  2575. * @return array
  2576. */
  2577. public function statusReplies(Request $request, $id)
  2578. {
  2579. abort_if(!$request->user(), 403);
  2580. $this->validate($request, [
  2581. 'limit' => 'int|min:1|max:10',
  2582. 'sort' => 'in:all,newest,popular'
  2583. ]);
  2584. $limit = $request->input('limit', 3);
  2585. $pid = $request->user()->profile_id;
  2586. $status = StatusService::getMastodon($id, false);
  2587. abort_if(!$status, 404);
  2588. if($status['visibility'] == 'private') {
  2589. if($pid != $status['account']['id']) {
  2590. abort_unless(FollowerService::follows($pid, $status['account']['id']), 404);
  2591. }
  2592. }
  2593. $sortBy = $request->input('sort', 'all');
  2594. if($sortBy == 'all' && isset($status['replies_count']) && $status['replies_count'] && $request->has('refresh_cache')) {
  2595. if(!Cache::has('status:replies:all-rc:' . $id)) {
  2596. Cache::forget('status:replies:all:' . $id);
  2597. Cache::put('status:replies:all-rc:' . $id, true, 300);
  2598. }
  2599. }
  2600. if($sortBy == 'all' && !$request->has('cursor')) {
  2601. $ids = Cache::remember('status:replies:all:' . $id, 3600, function() use($id) {
  2602. return DB::table('statuses')
  2603. ->where('in_reply_to_id', $id)
  2604. ->orderBy('id')
  2605. ->cursorPaginate(3);
  2606. });
  2607. } else {
  2608. $ids = DB::table('statuses')
  2609. ->where('in_reply_to_id', $id)
  2610. ->when($sortBy, function($q, $sortBy) {
  2611. if($sortBy === 'all') {
  2612. return $q->orderBy('id');
  2613. }
  2614. if($sortBy === 'newest') {
  2615. return $q->orderByDesc('created_at');
  2616. }
  2617. if($sortBy === 'popular') {
  2618. return $q->orderByDesc('likes_count');
  2619. }
  2620. })
  2621. ->cursorPaginate($limit);
  2622. }
  2623. $data = $ids->map(function($post) use($pid) {
  2624. $status = StatusService::get($post->id, false);
  2625. if(!$status || !isset($status['id'])) {
  2626. return false;
  2627. }
  2628. $status['favourited'] = LikeService::liked($pid, $post->id);
  2629. return $status;
  2630. })
  2631. ->map(function($post) {
  2632. if(isset($post['account']) && isset($post['account']['id'])) {
  2633. $account = AccountService::get($post['account']['id'], true);
  2634. $post['account'] = $account;
  2635. }
  2636. return $post;
  2637. })
  2638. ->filter(function($post) {
  2639. return $post && isset($post['id']) && isset($post['account']) && isset($post['account']['id']);
  2640. })
  2641. ->values();
  2642. $res = [
  2643. 'data' => $data,
  2644. 'next' => $ids->nextPageUrl()
  2645. ];
  2646. return $this->json($res);
  2647. }
  2648. /**
  2649. * GET /api/v2/statuses/{id}/state
  2650. *
  2651. *
  2652. * @return array
  2653. */
  2654. public function statusState(Request $request, $id)
  2655. {
  2656. abort_if(!$request->user(), 403);
  2657. $status = Status::findOrFail($id);
  2658. $pid = $request->user()->profile_id;
  2659. abort_if(!in_array($status->scope, ['public', 'unlisted', 'private']), 404);
  2660. return $this->json(StatusService::getState($status->id, $pid));
  2661. }
  2662. /**
  2663. * GET /api/v1.1/discover/accounts/popular
  2664. *
  2665. *
  2666. * @return array
  2667. */
  2668. public function discoverAccountsPopular(Request $request)
  2669. {
  2670. abort_if(!$request->user(), 403);
  2671. $pid = $request->user()->profile_id;
  2672. $ids = Cache::remember('api:v1.1:discover:accounts:popular', 86400, function() {
  2673. return DB::table('profiles')
  2674. ->where('is_private', false)
  2675. ->whereNull('status')
  2676. ->orderByDesc('profiles.followers_count')
  2677. ->limit(20)
  2678. ->get();
  2679. });
  2680. $ids = $ids->map(function($profile) {
  2681. return AccountService::get($profile->id, true);
  2682. })
  2683. ->filter(function($profile) use($pid) {
  2684. return $profile && isset($profile['id']);
  2685. })
  2686. ->filter(function($profile) use($pid) {
  2687. return $profile['id'] != $pid;
  2688. })
  2689. ->map(function($profile) {
  2690. $ids = collect(ProfileStatusService::get($profile['id'], 0, 9))
  2691. ->map(function($id) {
  2692. return StatusService::get($id, true);
  2693. })
  2694. ->filter(function($post) {
  2695. return $post && isset($post['id']);
  2696. })
  2697. ->take(3);
  2698. $profile['recent_posts'] = $ids;
  2699. return $profile;
  2700. })
  2701. ->take(6)
  2702. ->values();
  2703. return $this->json($ids);
  2704. }
  2705. /**
  2706. * GET /api/v1/preferences
  2707. *
  2708. *
  2709. * @return array
  2710. */
  2711. public function getPreferences(Request $request)
  2712. {
  2713. abort_if(!$request->user(), 403);
  2714. $pid = $request->user()->profile_id;
  2715. $account = AccountService::get($pid);
  2716. return $this->json([
  2717. 'posting:default:visibility' => $account['locked'] ? 'private' : 'public',
  2718. 'posting:default:sensitive' => false,
  2719. 'posting:default:language' => null,
  2720. 'reading:expand:media' => 'default',
  2721. 'reading:expand:spoilers' => false
  2722. ]);
  2723. }
  2724. /**
  2725. * GET /api/v1/trends
  2726. *
  2727. *
  2728. * @return array
  2729. */
  2730. public function getTrends(Request $request)
  2731. {
  2732. abort_if(!$request->user(), 403);
  2733. return $this->json([]);
  2734. }
  2735. /**
  2736. * GET /api/v1/announcements
  2737. *
  2738. *
  2739. * @return array
  2740. */
  2741. public function getAnnouncements(Request $request)
  2742. {
  2743. abort_if(!$request->user(), 403);
  2744. return $this->json([]);
  2745. }
  2746. /**
  2747. * GET /api/v1/markers
  2748. *
  2749. *
  2750. * @return array
  2751. */
  2752. public function getMarkers(Request $request)
  2753. {
  2754. abort_if(!$request->user(), 403);
  2755. $type = $request->input('timeline');
  2756. if(is_array($type)) {
  2757. $type = $type[0];
  2758. }
  2759. if(!$type || !in_array($type, ['home', 'notifications'])) {
  2760. return $this->json([]);
  2761. }
  2762. $pid = $request->user()->profile_id;
  2763. return $this->json(MarkerService::get($pid, $type));
  2764. }
  2765. /**
  2766. * POST /api/v1/markers
  2767. *
  2768. *
  2769. * @return array
  2770. */
  2771. public function setMarkers(Request $request)
  2772. {
  2773. abort_if(!$request->user(), 403);
  2774. $pid = $request->user()->profile_id;
  2775. $home = $request->input('home.last_read_id');
  2776. $notifications = $request->input('notifications.last_read_id');
  2777. if($home) {
  2778. return $this->json(MarkerService::set($pid, 'home', $home));
  2779. }
  2780. if($notifications) {
  2781. return $this->json(MarkerService::set($pid, 'notifications', $notifications));
  2782. }
  2783. return $this->json([]);
  2784. }
  2785. }