ApiV1Controller.php 148 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295
  1. <?php
  2. namespace App\Http\Controllers\Api;
  3. use App\Avatar;
  4. use App\Bookmark;
  5. use App\Collection;
  6. use App\CollectionItem;
  7. use App\DirectMessage;
  8. use App\Follower;
  9. use App\FollowRequest;
  10. use App\Hashtag;
  11. use App\Http\Controllers\AccountController;
  12. use App\Http\Controllers\Controller;
  13. use App\Http\Controllers\FollowerController;
  14. use App\Http\Controllers\StatusController;
  15. use App\Instance;
  16. use App\Jobs\AvatarPipeline\AvatarOptimize;
  17. use App\Jobs\CommentPipeline\CommentPipeline;
  18. use App\Jobs\FollowPipeline\FollowAcceptPipeline;
  19. use App\Jobs\FollowPipeline\FollowPipeline;
  20. use App\Jobs\FollowPipeline\FollowRejectPipeline;
  21. use App\Jobs\FollowPipeline\UnfollowPipeline;
  22. use App\Jobs\HomeFeedPipeline\FeedWarmCachePipeline;
  23. use App\Jobs\ImageOptimizePipeline\ImageOptimize;
  24. use App\Jobs\LikePipeline\LikePipeline;
  25. use App\Jobs\MediaPipeline\MediaDeletePipeline;
  26. use App\Jobs\MediaPipeline\MediaSyncLicensePipeline;
  27. use App\Jobs\SharePipeline\SharePipeline;
  28. use App\Jobs\SharePipeline\UndoSharePipeline;
  29. use App\Jobs\StatusPipeline\NewStatusPipeline;
  30. use App\Jobs\StatusPipeline\StatusDelete;
  31. use App\Jobs\VideoPipeline\VideoThumbnail;
  32. use App\Like;
  33. use App\Media;
  34. use App\Models\Conversation;
  35. use App\Notification;
  36. use App\Profile;
  37. use App\Services\AccountService;
  38. use App\Services\AdminShadowFilterService;
  39. use App\Services\BookmarkService;
  40. use App\Services\BouncerService;
  41. use App\Services\CollectionService;
  42. use App\Services\CustomEmojiService;
  43. use App\Services\DiscoverService;
  44. use App\Services\FollowerService;
  45. use App\Services\HomeTimelineService;
  46. use App\Services\InstanceService;
  47. use App\Services\LikeService;
  48. use App\Services\MarkerService;
  49. use App\Services\MediaBlocklistService;
  50. use App\Services\MediaPathService;
  51. use App\Services\MediaService;
  52. use App\Services\NetworkTimelineService;
  53. use App\Services\NotificationService;
  54. use App\Services\PublicTimelineService;
  55. use App\Services\ReblogService;
  56. use App\Services\RelationshipService;
  57. use App\Services\SnowflakeService;
  58. use App\Services\StatusService;
  59. use App\Services\UserFilterService;
  60. use App\Services\UserRoleService;
  61. use App\Status;
  62. use App\StatusHashtag;
  63. use App\Transformer\Api\Mastodon\v1\AccountTransformer;
  64. use App\Transformer\Api\Mastodon\v1\MediaTransformer;
  65. use App\Transformer\Api\Mastodon\v1\NotificationTransformer;
  66. use App\Transformer\Api\Mastodon\v1\StatusTransformer;
  67. use App\Transformer\Api\{
  68. RelationshipTransformer,
  69. };
  70. use App\User;
  71. use App\UserFilter;
  72. use App\UserSetting;
  73. use App\Util\Lexer\Autolink;
  74. use App\Util\Lexer\PrettyNumber;
  75. use App\Util\Localization\Localization;
  76. use App\Util\Media\Filter;
  77. use App\Util\Media\License;
  78. use Cache;
  79. use Carbon\Carbon;
  80. use DB;
  81. use Illuminate\Http\Request;
  82. use Illuminate\Support\Facades\RateLimiter;
  83. use Illuminate\Support\Str;
  84. use Laravel\Passport\Passport;
  85. use League\Fractal;
  86. use League\Fractal\Serializer\ArraySerializer;
  87. use Purify;
  88. use Storage;
  89. class ApiV1Controller extends Controller
  90. {
  91. protected $fractal;
  92. const PF_API_ENTITY_KEY = '_pe';
  93. public function __construct()
  94. {
  95. $this->fractal = new Fractal\Manager();
  96. $this->fractal->setSerializer(new ArraySerializer());
  97. }
  98. public function json($res, $code = 200, $headers = [])
  99. {
  100. return response()->json($res, $code, $headers, JSON_UNESCAPED_SLASHES);
  101. }
  102. /**
  103. * GET /api/v1/apps/verify_credentials
  104. */
  105. public function getApp(Request $request)
  106. {
  107. // FIXME: /api/v1/apps/verify_credentials should be accessible with any
  108. // valid Access Token, not just a user's access token (i.e., client
  109. // credentails grant flow access tokens)
  110. abort_if(! $request->user() || ! $request->user()->token(), 403);
  111. $client = $request->user()->token()->client;
  112. $res = [
  113. 'name' => $client->name,
  114. 'website' => null,
  115. 'vapid_key' => null,
  116. ];
  117. return $this->json($res);
  118. }
  119. /**
  120. * POST /api/v1/apps
  121. */
  122. public function apps(Request $request)
  123. {
  124. abort_if(! (bool) config_cache('pixelfed.oauth_enabled'), 404);
  125. $this->validate($request, [
  126. 'client_name' => 'required',
  127. 'redirect_uris' => 'required',
  128. ]);
  129. $uris = implode(',', explode('\n', $request->redirect_uris));
  130. $client = Passport::client()->forceFill([
  131. 'user_id' => null,
  132. 'name' => e($request->client_name),
  133. 'secret' => Str::random(40),
  134. 'redirect' => $uris,
  135. 'personal_access_client' => false,
  136. 'password_client' => false,
  137. 'revoked' => false,
  138. ]);
  139. $client->save();
  140. $res = [
  141. 'id' => (string) $client->id,
  142. 'name' => $client->name,
  143. 'website' => null,
  144. 'redirect_uri' => $client->redirect,
  145. 'client_id' => (string) $client->id,
  146. 'client_secret' => $client->secret,
  147. 'vapid_key' => null,
  148. ];
  149. return $this->json($res, 200, [
  150. 'Access-Control-Allow-Origin' => '*',
  151. ]);
  152. }
  153. /**
  154. * GET /api/v1/accounts/verify_credentials
  155. *
  156. *
  157. * @return \App\Transformer\Api\AccountTransformer
  158. */
  159. public function verifyCredentials(Request $request)
  160. {
  161. abort_if(! $request->user() || ! $request->user()->token(), 403);
  162. abort_unless($request->user()->tokenCan('read'), 403);
  163. $user = $request->user();
  164. abort_if($user->status != null, 403);
  165. AccountService::setLastActive($user->id);
  166. $res = $request->has(self::PF_API_ENTITY_KEY) ? AccountService::get($user->profile_id) : AccountService::getMastodon($user->profile_id);
  167. $res['source'] = [
  168. 'privacy' => $res['locked'] ? 'private' : 'public',
  169. 'sensitive' => false,
  170. 'language' => $user->language ?? 'en',
  171. 'note' => strip_tags($res['note']),
  172. 'fields' => [],
  173. ];
  174. if ($request->has(self::PF_API_ENTITY_KEY)) {
  175. $res['settings'] = AccountService::getAccountSettings($user->profile_id);
  176. }
  177. return $this->json($res);
  178. }
  179. /**
  180. * GET /api/v1/accounts/{id}
  181. *
  182. * @param int $id
  183. * @return \App\Transformer\Api\AccountTransformer
  184. */
  185. public function accountById(Request $request, $id)
  186. {
  187. abort_if(! $request->user() || ! $request->user()->token(), 403);
  188. abort_unless($request->user()->tokenCan('read'), 403);
  189. $withInstanceMeta = $request->has('_wim');
  190. $res = $request->has(self::PF_API_ENTITY_KEY) ? AccountService::get($id, true) : AccountService::getMastodon($id, true);
  191. if (! $res) {
  192. return response()->json(['error' => 'Record not found'], 404);
  193. }
  194. if ($res && strpos($res['acct'], '@') != -1) {
  195. $domain = parse_url($res['url'], PHP_URL_HOST);
  196. abort_if(in_array($domain, InstanceService::getBannedDomains()), 404);
  197. }
  198. return $this->json($res);
  199. }
  200. /**
  201. * PATCH /api/v1/accounts/update_credentials
  202. *
  203. * @return \App\Transformer\Api\AccountTransformer
  204. */
  205. public function accountUpdateCredentials(Request $request)
  206. {
  207. abort_if(! $request->user() || ! $request->user()->token(), 403);
  208. abort_unless($request->user()->tokenCan('write'), 403);
  209. if (config('pixelfed.bouncer.cloud_ips.ban_api')) {
  210. abort_if(BouncerService::checkIp($request->ip()), 404);
  211. }
  212. $this->validate($request, [
  213. 'avatar' => 'sometimes|mimetypes:image/jpeg,image/png|max:'.config('pixelfed.max_avatar_size'),
  214. 'display_name' => 'nullable|string|max:30',
  215. 'note' => 'nullable|string|max:200',
  216. 'locked' => 'nullable',
  217. 'website' => 'nullable|string|max:120',
  218. // 'source.privacy' => 'nullable|in:unlisted,public,private',
  219. // 'source.sensitive' => 'nullable|boolean'
  220. ], [
  221. 'required' => 'The :attribute field is required.',
  222. 'avatar.mimetypes' => 'The file must be in jpeg or png format',
  223. 'avatar.max' => 'The :attribute exceeds the file size limit of '.PrettyNumber::size(config('pixelfed.max_avatar_size'), true, false),
  224. ]);
  225. $user = $request->user();
  226. AccountService::setLastActive($user->id);
  227. $profile = $user->profile;
  228. $settings = $user->settings;
  229. $changes = false;
  230. $other = array_merge(AccountService::defaultSettings()['other'], $settings->other ?? []);
  231. $syncLicenses = false;
  232. $licenseChanged = false;
  233. $composeSettings = array_merge(AccountService::defaultSettings()['compose_settings'], $settings->compose_settings ?? []);
  234. if ($request->has('avatar')) {
  235. $av = Avatar::whereProfileId($profile->id)->first();
  236. if ($av) {
  237. $currentAvatar = storage_path('app/'.$av->media_path);
  238. $file = $request->file('avatar');
  239. $path = "public/avatars/{$profile->id}";
  240. $name = strtolower(str_random(6)).'.'.$file->guessExtension();
  241. $request->file('avatar')->storePubliclyAs($path, $name);
  242. $av->media_path = "{$path}/{$name}";
  243. $av->save();
  244. Cache::forget("avatar:{$profile->id}");
  245. Cache::forget('user:account:id:'.$user->id);
  246. AvatarOptimize::dispatch($user->profile, $currentAvatar);
  247. }
  248. $changes = true;
  249. }
  250. if ($request->has('source[language]')) {
  251. $lang = $request->input('source[language]');
  252. if (in_array($lang, Localization::languages())) {
  253. $user->language = $lang;
  254. $changes = true;
  255. $other['language'] = $lang;
  256. }
  257. }
  258. if ($request->has('website')) {
  259. $website = $request->input('website');
  260. if ($website != $profile->website) {
  261. if ($website) {
  262. if (! strpos($website, '.')) {
  263. $website = null;
  264. }
  265. if ($website && ! strpos($website, '://')) {
  266. $website = 'https://'.$website;
  267. }
  268. $host = parse_url($website, PHP_URL_HOST);
  269. $bannedInstances = InstanceService::getBannedDomains();
  270. if (in_array($host, $bannedInstances)) {
  271. $website = null;
  272. }
  273. }
  274. $profile->website = $website ? $website : null;
  275. $changes = true;
  276. }
  277. }
  278. if ($request->has('display_name')) {
  279. $displayName = $request->input('display_name');
  280. if ($displayName !== $user->name) {
  281. $user->name = $displayName;
  282. $profile->name = $displayName;
  283. $changes = true;
  284. }
  285. }
  286. if ($request->has('note')) {
  287. $note = $request->input('note');
  288. if ($note !== strip_tags($profile->bio)) {
  289. $profile->bio = Autolink::create()->autolink(strip_tags($note));
  290. $changes = true;
  291. }
  292. }
  293. if ($request->has('locked')) {
  294. $locked = $request->boolean('locked');
  295. if ($profile->is_private != $locked) {
  296. $profile->is_private = $locked;
  297. $changes = true;
  298. }
  299. }
  300. if ($request->has('reduce_motion')) {
  301. $reduced = $request->boolean('reduce_motion');
  302. if ($settings->reduce_motion != $reduced) {
  303. $settings->reduce_motion = $reduced;
  304. $changes = true;
  305. }
  306. }
  307. if ($request->has('high_contrast_mode')) {
  308. $contrast = $request->boolean('high_contrast_mode');
  309. if ($settings->high_contrast_mode != $contrast) {
  310. $settings->high_contrast_mode = $contrast;
  311. $changes = true;
  312. }
  313. }
  314. if ($request->has('video_autoplay')) {
  315. $autoplay = $request->boolean('video_autoplay');
  316. if ($settings->video_autoplay != $autoplay) {
  317. $settings->video_autoplay = $autoplay;
  318. $changes = true;
  319. }
  320. }
  321. if ($request->has('license')) {
  322. $license = $request->input('license');
  323. abort_if(! in_array($license, License::keys()), 422, 'Invalid media license id');
  324. $syncLicenses = $request->input('sync_licenses') == true;
  325. abort_if($syncLicenses && Cache::get('pf:settings:mls_recently:'.$user->id) == 2, 422, 'You can only sync licenses twice per 24 hours');
  326. if ($composeSettings['default_license'] != $license) {
  327. $composeSettings['default_license'] = $license;
  328. $licenseChanged = true;
  329. $changes = true;
  330. }
  331. }
  332. if ($request->has('media_descriptions')) {
  333. $md = $request->boolean('media_descriptions');
  334. if ($composeSettings['media_descriptions'] != $md) {
  335. $composeSettings['media_descriptions'] = $md;
  336. $changes = true;
  337. }
  338. }
  339. if ($request->has('crawlable')) {
  340. $crawlable = $request->boolean('crawlable');
  341. if ($settings->crawlable != $crawlable) {
  342. $settings->crawlable = $crawlable;
  343. $changes = true;
  344. }
  345. }
  346. if ($request->has('show_profile_follower_count')) {
  347. $show_profile_follower_count = $request->boolean('show_profile_follower_count');
  348. if ($settings->show_profile_follower_count != $show_profile_follower_count) {
  349. $settings->show_profile_follower_count = $show_profile_follower_count;
  350. $changes = true;
  351. Cache::forget('pf:acct-trans:hideFollowers:'.$profile->id);
  352. }
  353. }
  354. if ($request->has('show_profile_following_count')) {
  355. $show_profile_following_count = $request->boolean('show_profile_following_count');
  356. if ($settings->show_profile_following_count != $show_profile_following_count) {
  357. $settings->show_profile_following_count = $show_profile_following_count;
  358. $changes = true;
  359. Cache::forget('pf:acct-trans:hideFollowing:'.$profile->id);
  360. }
  361. }
  362. if ($request->has('public_dm')) {
  363. $public_dm = $request->boolean('public_dm');
  364. if ($settings->public_dm != $public_dm) {
  365. $settings->public_dm = $public_dm;
  366. $changes = true;
  367. }
  368. }
  369. if ($request->has('source[privacy]')) {
  370. $scope = $request->input('source[privacy]');
  371. if (in_array($scope, ['public', 'private', 'unlisted'])) {
  372. if ($composeSettings['default_scope'] != $scope) {
  373. $composeSettings['default_scope'] = $profile->is_private ? 'private' : $scope;
  374. $changes = true;
  375. }
  376. }
  377. }
  378. if ($request->has('disable_embeds')) {
  379. $disabledEmbeds = $request->boolean('disable_embeds');
  380. if ($other['disable_embeds'] != $disabledEmbeds) {
  381. $other['disable_embeds'] = $disabledEmbeds;
  382. $changes = true;
  383. }
  384. }
  385. if ($changes) {
  386. $settings->other = $other;
  387. $settings->compose_settings = $composeSettings;
  388. $settings->save();
  389. $user->save();
  390. $profile->save();
  391. Cache::forget('profile:settings:'.$profile->id);
  392. Cache::forget('user:account:id:'.$profile->user_id);
  393. Cache::forget('profile:follower_count:'.$profile->id);
  394. Cache::forget('profile:following_count:'.$profile->id);
  395. Cache::forget('profile:embed:'.$profile->id);
  396. Cache::forget('profile:compose:settings:'.$user->id);
  397. Cache::forget('profile:view:'.$profile->username);
  398. Cache::forget('profile:atom:enabled:'.$profile->id);
  399. Cache::forget('pfc:cached-user:wt:'.strtolower($profile->username));
  400. Cache::forget('pfc:cached-user:wot:'.strtolower($profile->username));
  401. Cache::forget('pf:acct:settings:hidden-followers:'.$profile->id);
  402. Cache::forget('pf:acct:settings:hidden-following:'.$profile->id);
  403. Cache::forget('pf:acct-trans:hideFollowing:'.$profile->id);
  404. Cache::forget('pf:acct-trans:hideFollowers:'.$profile->id);
  405. AccountService::del($user->profile_id);
  406. AccountService::forgetAccountSettings($profile->id);
  407. }
  408. if ($syncLicenses && $licenseChanged) {
  409. $key = 'pf:settings:mls_recently:'.$user->id;
  410. $val = Cache::has($key) ? 2 : 1;
  411. Cache::put($key, $val, 86400);
  412. MediaSyncLicensePipeline::dispatch($user->id, $request->input('license'));
  413. }
  414. if ($request->has(self::PF_API_ENTITY_KEY)) {
  415. $res = AccountService::get($user->profile_id, true);
  416. } else {
  417. $res = AccountService::getMastodon($user->profile_id, true);
  418. $res['bio'] = strip_tags($res['note']);
  419. $res = array_merge($res, $other);
  420. }
  421. return $this->json($res);
  422. }
  423. /**
  424. * GET /api/v1/accounts/{id}/followers
  425. *
  426. * @param int $id
  427. * @return \App\Transformer\Api\AccountTransformer
  428. */
  429. public function accountFollowersById(Request $request, $id)
  430. {
  431. abort_if(! $request->user() || ! $request->user()->token(), 403);
  432. abort_unless($request->user()->tokenCan('read'), 403);
  433. $account = AccountService::get($id);
  434. abort_if(! $account, 404);
  435. $pid = $request->user()->profile_id;
  436. $this->validate($request, [
  437. 'limit' => 'sometimes|integer|min:1',
  438. ]);
  439. $limit = $request->input('limit', 10);
  440. if ($limit > 80) {
  441. $limit = 80;
  442. }
  443. $napi = $request->has(self::PF_API_ENTITY_KEY);
  444. if ($account && strpos($account['acct'], '@') != -1) {
  445. $domain = parse_url($account['url'], PHP_URL_HOST);
  446. abort_if(in_array($domain, InstanceService::getBannedDomains()), 404);
  447. }
  448. if (intval($pid) !== intval($account['id'])) {
  449. if ($account['locked']) {
  450. if (! FollowerService::follows($pid, $account['id'])) {
  451. return [];
  452. }
  453. }
  454. if (AccountService::hiddenFollowers($id)) {
  455. return [];
  456. }
  457. if ($request->has('page') && $request->user()->is_admin == false) {
  458. $page = (int) $request->input('page');
  459. if (($page * $limit) >= 100) {
  460. return [];
  461. }
  462. }
  463. }
  464. if ($request->has('page')) {
  465. $res = DB::table('followers')
  466. ->select('id', 'profile_id', 'following_id')
  467. ->whereFollowingId($account['id'])
  468. ->orderByDesc('id')
  469. ->simplePaginate($limit)
  470. ->map(function ($follower) use ($napi) {
  471. return $napi ? AccountService::get($follower->profile_id, true) : AccountService::getMastodon($follower->profile_id, true);
  472. })
  473. ->filter(function ($account) {
  474. return $account && isset($account['id']);
  475. })
  476. ->values()
  477. ->toArray();
  478. return $this->json($res);
  479. }
  480. $paginator = DB::table('followers')
  481. ->select('id', 'profile_id', 'following_id')
  482. ->whereFollowingId($account['id'])
  483. ->orderByDesc('id')
  484. ->cursorPaginate($limit)
  485. ->withQueryString();
  486. $link = null;
  487. if ($paginator->onFirstPage()) {
  488. if ($paginator->hasMorePages()) {
  489. $link = '<'.$paginator->nextPageUrl().'>; rel="prev"';
  490. }
  491. } else {
  492. if ($paginator->previousPageUrl()) {
  493. $link = '<'.$paginator->previousPageUrl().'>; rel="next"';
  494. }
  495. if ($paginator->hasMorePages()) {
  496. $link .= ($link ? ', ' : '').'<'.$paginator->nextPageUrl().'>; rel="prev"';
  497. }
  498. }
  499. $res = $paginator->map(function ($follower) use ($napi) {
  500. return $napi ? AccountService::get($follower->profile_id, true) : AccountService::getMastodon($follower->profile_id, true);
  501. })
  502. ->filter(function ($account) {
  503. return $account && isset($account['id']);
  504. })
  505. ->values()
  506. ->toArray();
  507. $headers = isset($link) ? ['Link' => $link] : [];
  508. return $this->json($res, 200, $headers);
  509. }
  510. /**
  511. * GET /api/v1/accounts/{id}/following
  512. *
  513. * @param int $id
  514. * @return \App\Transformer\Api\AccountTransformer
  515. */
  516. public function accountFollowingById(Request $request, $id)
  517. {
  518. abort_if(! $request->user() || ! $request->user()->token(), 403);
  519. abort_unless($request->user()->tokenCan('read'), 403);
  520. $account = AccountService::get($id);
  521. abort_if(! $account, 404);
  522. $pid = $request->user()->profile_id;
  523. $this->validate($request, [
  524. 'limit' => 'sometimes|integer|min:1',
  525. ]);
  526. $limit = $request->input('limit', 10);
  527. if ($limit > 80) {
  528. $limit = 80;
  529. }
  530. $napi = $request->has(self::PF_API_ENTITY_KEY);
  531. if ($account && strpos($account['acct'], '@') != -1) {
  532. $domain = parse_url($account['url'], PHP_URL_HOST);
  533. abort_if(in_array($domain, InstanceService::getBannedDomains()), 404);
  534. }
  535. if (intval($pid) !== intval($account['id'])) {
  536. if ($account['locked']) {
  537. if (! FollowerService::follows($pid, $account['id'])) {
  538. return [];
  539. }
  540. }
  541. if (AccountService::hiddenFollowing($id)) {
  542. return [];
  543. }
  544. if ($request->has('page') && $request->user()->is_admin == false) {
  545. $page = (int) $request->input('page');
  546. if (($page * $limit) >= 100) {
  547. return [];
  548. }
  549. }
  550. }
  551. if ($request->has('page')) {
  552. $res = DB::table('followers')
  553. ->select('id', 'profile_id', 'following_id')
  554. ->whereProfileId($account['id'])
  555. ->orderByDesc('id')
  556. ->simplePaginate($limit)
  557. ->map(function ($follower) use ($napi) {
  558. return $napi ? AccountService::get($follower->following_id, true) : AccountService::getMastodon($follower->following_id, true);
  559. })
  560. ->filter(function ($account) {
  561. return $account && isset($account['id']);
  562. })
  563. ->values()
  564. ->toArray();
  565. return $this->json($res);
  566. }
  567. $paginator = DB::table('followers')
  568. ->select('id', 'profile_id', 'following_id')
  569. ->whereProfileId($account['id'])
  570. ->orderByDesc('id')
  571. ->cursorPaginate($limit)
  572. ->withQueryString();
  573. $link = null;
  574. if ($paginator->onFirstPage()) {
  575. if ($paginator->hasMorePages()) {
  576. $link = '<'.$paginator->nextPageUrl().'>; rel="prev"';
  577. }
  578. } else {
  579. if ($paginator->previousPageUrl()) {
  580. $link = '<'.$paginator->previousPageUrl().'>; rel="next"';
  581. }
  582. if ($paginator->hasMorePages()) {
  583. $link .= ($link ? ', ' : '').'<'.$paginator->nextPageUrl().'>; rel="prev"';
  584. }
  585. }
  586. $res = $paginator->map(function ($follower) use ($napi) {
  587. return $napi ? AccountService::get($follower->following_id, true) : AccountService::getMastodon($follower->following_id, true);
  588. })
  589. ->filter(function ($account) {
  590. return $account && isset($account['id']);
  591. })
  592. ->values()
  593. ->toArray();
  594. $headers = isset($link) ? ['Link' => $link] : [];
  595. return $this->json($res, 200, $headers);
  596. }
  597. /**
  598. * GET /api/v1/accounts/{id}/statuses
  599. *
  600. * @param int $id
  601. * @return \App\Transformer\Api\StatusTransformer
  602. */
  603. public function accountStatusesById(Request $request, $id)
  604. {
  605. abort_if(! $request->user() || ! $request->user()->token(), 403);
  606. abort_unless($request->user()->tokenCan('read'), 403);
  607. $user = $request->user();
  608. $this->validate($request, [
  609. 'only_media' => 'nullable',
  610. 'media_type' => 'sometimes|string|in:photo,video',
  611. 'pinned' => 'nullable',
  612. 'exclude_replies' => 'nullable',
  613. 'max_id' => 'nullable|integer|min:0|max:'.PHP_INT_MAX,
  614. 'since_id' => 'nullable|integer|min:0|max:'.PHP_INT_MAX,
  615. 'min_id' => 'nullable|integer|min:0|max:'.PHP_INT_MAX,
  616. 'limit' => 'nullable|integer|min:1',
  617. ]);
  618. $napi = $request->has(self::PF_API_ENTITY_KEY);
  619. $profile = $napi ? AccountService::get($id, true) : AccountService::getMastodon($id, true);
  620. if (! $profile || ! isset($profile['id']) || ! $user) {
  621. return $this->json(['error' => 'Account not found'], 404);
  622. }
  623. if ($profile && strpos($profile['acct'], '@') != -1) {
  624. $domain = parse_url($profile['url'], PHP_URL_HOST);
  625. abort_if(in_array($domain, InstanceService::getBannedDomains()), 404);
  626. }
  627. $limit = $request->input('limit') ?? 20;
  628. if ($limit > 40) {
  629. $limit = 40;
  630. }
  631. $max_id = $request->max_id;
  632. $min_id = $request->min_id;
  633. if (! $max_id && ! $min_id) {
  634. $min_id = 1;
  635. }
  636. $pid = $request->user()->profile_id;
  637. $scope = $request->only_media == true ?
  638. ['photo', 'photo:album', 'video', 'video:album'] :
  639. ['photo', 'photo:album', 'video', 'video:album', 'share', 'reply'];
  640. if ($request->only_media && $request->has('media_type')) {
  641. $mt = $request->input('media_type');
  642. if ($mt == 'video') {
  643. $scope = ['video', 'video:album'];
  644. }
  645. }
  646. if (intval($pid) === intval($profile['id'])) {
  647. $visibility = ['public', 'unlisted', 'private'];
  648. } elseif ($profile['locked']) {
  649. $following = FollowerService::follows($pid, $profile['id']);
  650. if (! $following) {
  651. return response('', 403);
  652. }
  653. $visibility = ['public', 'unlisted', 'private'];
  654. } else {
  655. $following = FollowerService::follows($pid, $profile['id']);
  656. $visibility = $following ? ['public', 'unlisted', 'private'] : ['public', 'unlisted'];
  657. }
  658. $dir = $min_id ? '>' : '<';
  659. $id = $min_id ?? $max_id;
  660. $res = Status::select(
  661. 'profile_id',
  662. 'in_reply_to_id',
  663. 'reblog_of_id',
  664. 'type',
  665. 'id',
  666. 'scope'
  667. )
  668. ->whereProfileId($profile['id'])
  669. ->whereNull('in_reply_to_id')
  670. ->whereNull('reblog_of_id')
  671. ->whereIn('type', $scope)
  672. ->where('id', $dir, $id)
  673. ->whereIn('scope', $visibility)
  674. ->limit($limit)
  675. ->orderByDesc('id')
  676. ->get()
  677. ->map(function ($s) use ($user, $napi, $profile) {
  678. try {
  679. $status = $napi ? StatusService::get($s->id, false) : StatusService::getMastodon($s->id, false);
  680. } catch (\Exception $e) {
  681. return false;
  682. }
  683. if ($profile) {
  684. $status['account'] = $profile;
  685. }
  686. if ($user && $status) {
  687. $status['favourited'] = (bool) LikeService::liked($user->profile_id, $s->id);
  688. $status['reblogged'] = (bool) ReblogService::get($user->profile_id, $s->id);
  689. $status['bookmarked'] = (bool) BookmarkService::get($user->profile_id, $s->id);
  690. }
  691. return $status;
  692. })
  693. ->filter(function ($s) {
  694. return $s;
  695. })
  696. ->values();
  697. return $this->json($res);
  698. }
  699. /**
  700. * POST /api/v1/accounts/{id}/follow
  701. *
  702. * @param int $id
  703. * @return \App\Transformer\Api\RelationshipTransformer
  704. */
  705. public function accountFollowById(Request $request, $id)
  706. {
  707. abort_if(! $request->user() || ! $request->user()->token(), 403);
  708. abort_unless($request->user()->tokenCan('follow'), 403);
  709. $user = $request->user();
  710. abort_if($user->has_roles && ! UserRoleService::can('can-follow', $user->id), 403, 'Invalid permissions for this action');
  711. AccountService::setLastActive($user->id);
  712. $target = Profile::where('id', '!=', $user->profile_id)
  713. ->whereNull('status')
  714. ->findOrFail($id);
  715. if ($target && $target->domain) {
  716. $domain = $target->domain;
  717. abort_if(in_array($domain, InstanceService::getBannedDomains()), 404);
  718. }
  719. $private = (bool) $target->is_private;
  720. $remote = (bool) $target->domain;
  721. $blocked = UserFilter::whereUserId($target->id)
  722. ->whereFilterType('block')
  723. ->whereFilterableId($user->profile_id)
  724. ->whereFilterableType('App\Profile')
  725. ->exists();
  726. if ($blocked == true) {
  727. abort(400, 'You cannot follow this user.');
  728. }
  729. $isFollowing = Follower::whereProfileId($user->profile_id)
  730. ->whereFollowingId($target->id)
  731. ->exists();
  732. // Following already, return empty relationship
  733. if ($isFollowing == true) {
  734. $res = RelationshipService::get($user->profile_id, $target->id) ?? [];
  735. return $this->json($res);
  736. }
  737. // Rate limits, max 7500 followers per account
  738. if ($user->profile->following_count && $user->profile->following_count >= Follower::MAX_FOLLOWING) {
  739. abort(400, 'You cannot follow more than '.Follower::MAX_FOLLOWING.' accounts');
  740. }
  741. if ($private == true) {
  742. $follow = FollowRequest::firstOrCreate([
  743. 'follower_id' => $user->profile_id,
  744. 'following_id' => $target->id,
  745. ]);
  746. if ($remote == true && config('federation.activitypub.remoteFollow') == true) {
  747. (new FollowerController())->sendFollow($user->profile, $target);
  748. }
  749. } else {
  750. $follower = Follower::firstOrCreate([
  751. 'profile_id' => $user->profile_id,
  752. 'following_id' => $target->id,
  753. ]);
  754. if ($remote == true && config('federation.activitypub.remoteFollow') == true) {
  755. (new FollowerController())->sendFollow($user->profile, $target);
  756. }
  757. FollowPipeline::dispatch($follower)->onQueue('high');
  758. }
  759. RelationshipService::refresh($user->profile_id, $target->id);
  760. Cache::forget('profile:following:'.$target->id);
  761. Cache::forget('profile:followers:'.$target->id);
  762. Cache::forget('profile:following:'.$user->profile_id);
  763. Cache::forget('profile:followers:'.$user->profile_id);
  764. Cache::forget('api:local:exp:rec:'.$user->profile_id);
  765. Cache::forget('user:account:id:'.$target->user_id);
  766. Cache::forget('user:account:id:'.$user->id);
  767. Cache::forget('profile:follower_count:'.$target->id);
  768. Cache::forget('profile:follower_count:'.$user->profile_id);
  769. Cache::forget('profile:following_count:'.$target->id);
  770. Cache::forget('profile:following_count:'.$user->profile_id);
  771. AccountService::del($user->profile_id);
  772. AccountService::del($target->id);
  773. $res = RelationshipService::get($user->profile_id, $target->id);
  774. return $this->json($res);
  775. }
  776. /**
  777. * POST /api/v1/accounts/{id}/unfollow
  778. *
  779. * @param int $id
  780. * @return \App\Transformer\Api\RelationshipTransformer
  781. */
  782. public function accountUnfollowById(Request $request, $id)
  783. {
  784. abort_if(! $request->user() || ! $request->user()->token(), 403);
  785. abort_unless($request->user()->tokenCan('follow'), 403);
  786. $user = $request->user();
  787. AccountService::setLastActive($user->id);
  788. $target = Profile::where('id', '!=', $user->profile_id)
  789. ->whereNull('status')
  790. ->findOrFail($id);
  791. $private = (bool) $target->is_private;
  792. $remote = (bool) $target->domain;
  793. $isFollowing = Follower::whereProfileId($user->profile_id)
  794. ->whereFollowingId($target->id)
  795. ->exists();
  796. if ($isFollowing == false) {
  797. $followRequest = FollowRequest::whereFollowerId($user->profile_id)
  798. ->whereFollowingId($target->id)
  799. ->first();
  800. if ($followRequest) {
  801. $followRequest->delete();
  802. RelationshipService::refresh($target->id, $user->profile_id);
  803. }
  804. $resource = new Fractal\Resource\Item($target, new RelationshipTransformer());
  805. $res = $this->fractal->createData($resource)->toArray();
  806. return $this->json($res);
  807. }
  808. Follower::whereProfileId($user->profile_id)
  809. ->whereFollowingId($target->id)
  810. ->delete();
  811. UnfollowPipeline::dispatch($user->profile_id, $target->id)->onQueue('high');
  812. if ($remote == true && config('federation.activitypub.remoteFollow') == true) {
  813. (new FollowerController())->sendUndoFollow($user->profile, $target);
  814. }
  815. RelationshipService::refresh($user->profile_id, $target->id);
  816. Cache::forget('profile:following:'.$target->id);
  817. Cache::forget('profile:followers:'.$target->id);
  818. Cache::forget('profile:following:'.$user->profile_id);
  819. Cache::forget('profile:followers:'.$user->profile_id);
  820. Cache::forget('api:local:exp:rec:'.$user->profile_id);
  821. Cache::forget('user:account:id:'.$target->user_id);
  822. Cache::forget('user:account:id:'.$user->id);
  823. Cache::forget('profile:follower_count:'.$target->id);
  824. Cache::forget('profile:follower_count:'.$user->profile_id);
  825. Cache::forget('profile:following_count:'.$target->id);
  826. Cache::forget('profile:following_count:'.$user->profile_id);
  827. AccountService::del($user->profile_id);
  828. AccountService::del($target->id);
  829. $res = RelationshipService::get($user->profile_id, $target->id);
  830. return $this->json($res);
  831. }
  832. /**
  833. * GET /api/v1/accounts/relationships
  834. *
  835. * @param array|int $id
  836. * @return \App\Services\RelationshipService
  837. */
  838. public function accountRelationshipsById(Request $request)
  839. {
  840. abort_if(! $request->user(), 403);
  841. $this->validate($request, [
  842. 'id' => 'required|array|min:1',
  843. 'id.*' => 'required|integer|min:1|max:'.PHP_INT_MAX,
  844. ]);
  845. $ids = $request->input('id');
  846. if (count($ids) > 20) {
  847. $ids = collect($ids)->take(20)->toArray();
  848. }
  849. $napi = $request->has(self::PF_API_ENTITY_KEY);
  850. $pid = $request->user()->profile_id ?? $request->user()->profile->id;
  851. $res = collect($ids)
  852. ->map(function ($id) use ($pid, $napi) {
  853. if (intval($id) === intval($pid)) {
  854. return [
  855. 'id' => $id,
  856. 'following' => false,
  857. 'followed_by' => false,
  858. 'blocking' => false,
  859. 'muting' => false,
  860. 'muting_notifications' => false,
  861. 'requested' => false,
  862. 'domain_blocking' => false,
  863. 'showing_reblogs' => false,
  864. 'endorsed' => false,
  865. ];
  866. }
  867. return $napi ?
  868. RelationshipService::getWithDate($pid, $id) :
  869. RelationshipService::get($pid, $id);
  870. });
  871. return $this->json($res);
  872. }
  873. /**
  874. * GET /api/v1/accounts/search
  875. *
  876. *
  877. *
  878. * @return \App\Transformer\Api\AccountTransformer
  879. */
  880. public function accountSearch(Request $request)
  881. {
  882. abort_if(! $request->user() || ! $request->user()->token(), 403);
  883. abort_unless($request->user()->tokenCan('read'), 403);
  884. $this->validate($request, [
  885. 'q' => 'required|string|min:1|max:30',
  886. 'limit' => 'nullable|integer|min:1',
  887. 'resolve' => 'nullable',
  888. ]);
  889. $user = $request->user();
  890. abort_if($user->has_roles && ! UserRoleService::can('can-view-discover', $user->id), 403, 'Invalid permissions for this action');
  891. AccountService::setLastActive($user->id);
  892. $query = $request->input('q');
  893. $limit = $request->input('limit') ?? 20;
  894. if ($limit > 20) {
  895. $limit = 20;
  896. }
  897. $resolve = $request->boolean('resolve', false);
  898. $q = $query.'%';
  899. $profiles = Profile::where('username', 'like', $q)
  900. ->orderByDesc('followers_count')
  901. ->limit($limit)
  902. ->pluck('id')
  903. ->map(function ($id) {
  904. return AccountService::getMastodon($id);
  905. })
  906. ->filter(function ($account) {
  907. return $account && isset($account['id']);
  908. })
  909. ->values();
  910. return $this->json($profiles);
  911. }
  912. /**
  913. * GET /api/v1/blocks
  914. *
  915. *
  916. *
  917. * @return \App\Transformer\Api\AccountTransformer
  918. */
  919. public function accountBlocks(Request $request)
  920. {
  921. abort_if(! $request->user() || ! $request->user()->token(), 403);
  922. abort_unless($request->user()->tokenCan('read'), 403);
  923. $this->validate($request, [
  924. 'limit' => 'sometimes|integer|min:1',
  925. 'page' => 'sometimes|integer|min:1',
  926. ]);
  927. $user = $request->user();
  928. $limit = $request->input('limit') ?? 40;
  929. if ($limit > 80) {
  930. $limit = 80;
  931. }
  932. $blocks = UserFilter::select('filterable_id', 'filterable_type', 'filter_type', 'user_id')
  933. ->whereUserId($user->profile_id)
  934. ->whereFilterableType('App\Profile')
  935. ->whereFilterType('block')
  936. ->orderByDesc('id')
  937. ->simplePaginate($limit)
  938. ->withQueryString();
  939. $res = $blocks->pluck('filterable_id')
  940. ->map(function ($id) {
  941. return AccountService::get($id, true);
  942. })
  943. ->filter(function ($account) {
  944. return $account && isset($account['id']);
  945. })
  946. ->values();
  947. $baseUrl = config('app.url').'/api/v1/blocks?limit='.$limit.'&';
  948. $next = $blocks->nextPageUrl();
  949. $prev = $blocks->previousPageUrl();
  950. if ($next && ! $prev) {
  951. $link = '<'.$next.'>; rel="next"';
  952. }
  953. if (! $next && $prev) {
  954. $link = '<'.$prev.'>; rel="prev"';
  955. }
  956. if ($next && $prev) {
  957. $link = '<'.$next.'>; rel="next",<'.$prev.'>; rel="prev"';
  958. }
  959. $headers = isset($link) ? ['Link' => $link] : [];
  960. return $this->json($res, 200, $headers);
  961. }
  962. /**
  963. * POST /api/v1/accounts/{id}/block
  964. *
  965. * @param int $id
  966. * @return \App\Transformer\Api\RelationshipTransformer
  967. */
  968. public function accountBlockById(Request $request, $id)
  969. {
  970. abort_if(! $request->user() || ! $request->user()->token(), 403);
  971. abort_unless($request->user()->tokenCan('write'), 403);
  972. $user = $request->user();
  973. $pid = $user->profile_id ?? $user->profile->id;
  974. AccountService::setLastActive($user->id);
  975. if (intval($id) === intval($pid)) {
  976. abort(400, 'You cannot block yourself');
  977. }
  978. $profile = Profile::findOrFail($id);
  979. if ($profile->user && $profile->user->is_admin == true) {
  980. abort(400, 'You cannot block an admin');
  981. }
  982. $count = UserFilterService::blockCount($pid);
  983. $maxLimit = (int) config_cache('instance.user_filters.max_user_blocks');
  984. if ($count == 0) {
  985. $filterCount = UserFilter::whereUserId($pid)
  986. ->whereFilterType('block')
  987. ->get()
  988. ->map(function ($rec) {
  989. return AccountService::get($rec->filterable_id, true);
  990. })
  991. ->filter(function ($account) {
  992. return $account && isset($account['id']);
  993. })
  994. ->values()
  995. ->count();
  996. abort_if($filterCount >= $maxLimit, 422, AccountController::FILTER_LIMIT_BLOCK_TEXT.$maxLimit.' accounts');
  997. } else {
  998. abort_if($count >= $maxLimit, 422, AccountController::FILTER_LIMIT_BLOCK_TEXT.$maxLimit.' accounts');
  999. }
  1000. $followed = Follower::whereProfileId($profile->id)->whereFollowingId($pid)->first();
  1001. if ($followed) {
  1002. $followed->delete();
  1003. $profile->following_count = Follower::whereProfileId($profile->id)->count();
  1004. $profile->save();
  1005. $selfProfile = $user->profile;
  1006. $selfProfile->followers_count = Follower::whereFollowingId($pid)->count();
  1007. $selfProfile->save();
  1008. FollowerService::remove($profile->id, $pid);
  1009. AccountService::del($pid);
  1010. AccountService::del($profile->id);
  1011. }
  1012. $following = Follower::whereProfileId($pid)->whereFollowingId($profile->id)->first();
  1013. if ($following) {
  1014. $following->delete();
  1015. $profile->followers_count = Follower::whereFollowingId($profile->id)->count();
  1016. $profile->save();
  1017. $selfProfile = $user->profile;
  1018. $selfProfile->following_count = Follower::whereProfileId($pid)->count();
  1019. $selfProfile->save();
  1020. FollowerService::remove($pid, $profile->pid);
  1021. AccountService::del($pid);
  1022. AccountService::del($profile->id);
  1023. }
  1024. Notification::whereProfileId($pid)
  1025. ->whereActorId($profile->id)
  1026. ->get()
  1027. ->map(function ($n) use ($pid) {
  1028. NotificationService::del($pid, $n['id']);
  1029. $n->forceDelete();
  1030. });
  1031. $filter = UserFilter::firstOrCreate([
  1032. 'user_id' => $pid,
  1033. 'filterable_id' => $profile->id,
  1034. 'filterable_type' => 'App\Profile',
  1035. 'filter_type' => 'block',
  1036. ]);
  1037. UserFilterService::block($pid, $id);
  1038. RelationshipService::refresh($pid, $id);
  1039. $resource = new Fractal\Resource\Item($profile, new RelationshipTransformer());
  1040. $res = $this->fractal->createData($resource)->toArray();
  1041. return $this->json($res);
  1042. }
  1043. /**
  1044. * POST /api/v1/accounts/{id}/unblock
  1045. *
  1046. * @param int $id
  1047. * @return \App\Transformer\Api\RelationshipTransformer
  1048. */
  1049. public function accountUnblockById(Request $request, $id)
  1050. {
  1051. abort_if(! $request->user() || ! $request->user()->token(), 403);
  1052. abort_unless($request->user()->tokenCan('write'), 403);
  1053. $user = $request->user();
  1054. $pid = $user->profile_id ?? $user->profile->id;
  1055. AccountService::setLastActive($user->id);
  1056. if (intval($id) === intval($pid)) {
  1057. abort(400, 'You cannot unblock yourself');
  1058. }
  1059. $profile = Profile::findOrFail($id);
  1060. $filter = UserFilter::whereUserId($pid)
  1061. ->whereFilterableId($profile->id)
  1062. ->whereFilterableType('App\Profile')
  1063. ->whereFilterType('block')
  1064. ->first();
  1065. if ($filter) {
  1066. $filter->delete();
  1067. UserFilterService::unblock($pid, $profile->id);
  1068. }
  1069. RelationshipService::refresh($pid, $id);
  1070. $resource = new Fractal\Resource\Item($profile, new RelationshipTransformer());
  1071. $res = $this->fractal->createData($resource)->toArray();
  1072. return $this->json($res);
  1073. }
  1074. /**
  1075. * GET /api/v1/custom_emojis
  1076. *
  1077. * Return custom emoji
  1078. *
  1079. * @return array
  1080. */
  1081. public function customEmojis()
  1082. {
  1083. return response(CustomEmojiService::all())->header('Content-Type', 'application/json');
  1084. }
  1085. /**
  1086. * GET /api/v1/domain_blocks
  1087. *
  1088. * Return empty array
  1089. *
  1090. * @return array
  1091. */
  1092. public function accountDomainBlocks(Request $request)
  1093. {
  1094. abort_if(! $request->user() || ! $request->user()->token(), 403);
  1095. abort_unless($request->user()->tokenCan('read'), 403);
  1096. return response()->json([]);
  1097. }
  1098. /**
  1099. * GET /api/v1/endorsements
  1100. *
  1101. * Return empty array
  1102. *
  1103. * @return array
  1104. */
  1105. public function accountEndorsements(Request $request)
  1106. {
  1107. abort_if(! $request->user() || ! $request->user()->token(), 403);
  1108. abort_unless($request->user()->tokenCan('read'), 403);
  1109. return response()->json([]);
  1110. }
  1111. /**
  1112. * GET /api/v1/favourites
  1113. *
  1114. * Returns collection of liked statuses
  1115. *
  1116. * @return \App\Transformer\Api\StatusTransformer
  1117. */
  1118. public function accountFavourites(Request $request)
  1119. {
  1120. abort_if(! $request->user() || ! $request->user()->token(), 403);
  1121. abort_unless($request->user()->tokenCan('read'), 403);
  1122. $this->validate($request, [
  1123. 'limit' => 'sometimes|integer|min:1',
  1124. ]);
  1125. $user = $request->user();
  1126. $maxId = $request->input('max_id');
  1127. $minId = $request->input('min_id');
  1128. $limit = $request->input('limit') ?? 10;
  1129. if ($limit > 40) {
  1130. $limit = 40;
  1131. }
  1132. $res = Like::whereProfileId($user->profile_id)
  1133. ->when($maxId, function ($q, $maxId) {
  1134. return $q->where('id', '<', $maxId);
  1135. })
  1136. ->when($minId, function ($q, $minId) {
  1137. return $q->where('id', '>', $minId);
  1138. })
  1139. ->orderByDesc('id')
  1140. ->limit($limit)
  1141. ->get()
  1142. ->map(function ($like) {
  1143. $status = StatusService::getMastodon($like['status_id'], false);
  1144. $status['favourited'] = true;
  1145. $status['like_id'] = $like->id;
  1146. $status['liked_at'] = str_replace('+00:00', 'Z', $like->created_at->format(DATE_RFC3339_EXTENDED));
  1147. return $status;
  1148. })
  1149. ->filter(function ($status) {
  1150. return $status && isset($status['id'], $status['like_id']);
  1151. })
  1152. ->values();
  1153. if ($res->count()) {
  1154. $ids = $res->map(function ($status) {
  1155. return $status['like_id'];
  1156. });
  1157. $max = $ids->max();
  1158. $min = $ids->min();
  1159. $baseUrl = config('app.url').'/api/v1/favourites?limit='.$limit.'&';
  1160. $link = '<'.$baseUrl.'max_id='.$max.'>; rel="next",<'.$baseUrl.'min_id='.$min.'>; rel="prev"';
  1161. return $this->json($res, 200, ['Link' => $link]);
  1162. } else {
  1163. return $this->json($res);
  1164. }
  1165. }
  1166. /**
  1167. * POST /api/v1/statuses/{id}/favourite
  1168. *
  1169. * @param int $id
  1170. * @return \App\Transformer\Api\StatusTransformer
  1171. */
  1172. public function statusFavouriteById(Request $request, $id)
  1173. {
  1174. abort_if(! $request->user() || ! $request->user()->token(), 403);
  1175. abort_unless($request->user()->tokenCan('write'), 403);
  1176. $user = $request->user();
  1177. abort_if($user->has_roles && ! UserRoleService::can('can-like', $user->id), 403, 'Invalid permissions for this action');
  1178. $napi = $request->has(self::PF_API_ENTITY_KEY);
  1179. $status = $napi ? StatusService::get($id, false) : StatusService::getMastodon($id, false);
  1180. abort_unless($status, 404);
  1181. if ($status && isset($status['account'], $status['account']['acct']) && strpos($status['account']['acct'], '@') != -1) {
  1182. $domain = parse_url($status['account']['url'], PHP_URL_HOST);
  1183. abort_if(in_array($domain, InstanceService::getBannedDomains()), 404);
  1184. }
  1185. $spid = $status['account']['id'];
  1186. AccountService::setLastActive($user->id);
  1187. if (intval($spid) !== intval($user->profile_id)) {
  1188. if ($status['visibility'] == 'private') {
  1189. abort_if(! FollowerService::follows($user->profile_id, $spid), 403);
  1190. } else {
  1191. abort_if(! in_array($status['visibility'], ['public', 'unlisted']), 403);
  1192. }
  1193. }
  1194. abort_if(
  1195. Like::whereProfileId($user->profile_id)
  1196. ->where('created_at', '>', now()->subDay())
  1197. ->count() >= Like::MAX_PER_DAY,
  1198. 429
  1199. );
  1200. $blocks = UserFilterService::blocks($spid);
  1201. if ($blocks && in_array($user->profile_id, $blocks)) {
  1202. abort(422);
  1203. }
  1204. $like = Like::firstOrCreate([
  1205. 'profile_id' => $user->profile_id,
  1206. 'status_id' => $status['id'],
  1207. ]);
  1208. if ($like->wasRecentlyCreated == true) {
  1209. $like->status_profile_id = $spid;
  1210. $like->is_comment = ! empty($status['in_reply_to_id']);
  1211. $like->save();
  1212. Status::findOrFail($status['id'])->update([
  1213. 'likes_count' => ($status['favourites_count'] ?? 0) + 1,
  1214. ]);
  1215. LikePipeline::dispatch($like)->onQueue('feed');
  1216. }
  1217. $status['favourited'] = true;
  1218. $status['favourites_count'] = $status['favourites_count'] + 1;
  1219. return $this->json($status);
  1220. }
  1221. /**
  1222. * POST /api/v1/statuses/{id}/unfavourite
  1223. *
  1224. * @param int $id
  1225. * @return \App\Transformer\Api\StatusTransformer
  1226. */
  1227. public function statusUnfavouriteById(Request $request, $id)
  1228. {
  1229. abort_if(! $request->user() || ! $request->user()->token(), 403);
  1230. abort_unless($request->user()->tokenCan('write'), 403);
  1231. $user = $request->user();
  1232. abort_if($user->has_roles && ! UserRoleService::can('can-like', $user->id), 403, 'Invalid permissions for this action');
  1233. $napi = $request->has(self::PF_API_ENTITY_KEY);
  1234. $status = $napi ? StatusService::get($id, false) : StatusService::getMastodon($id, false);
  1235. abort_unless($status && isset($status['account']), 404);
  1236. if ($status && isset($status['account'], $status['account']['acct']) && strpos($status['account']['acct'], '@') != -1) {
  1237. $domain = parse_url($status['account']['url'], PHP_URL_HOST);
  1238. abort_if(in_array($domain, InstanceService::getBannedDomains()), 404);
  1239. }
  1240. $spid = $status['account']['id'];
  1241. AccountService::setLastActive($user->id);
  1242. if (intval($spid) !== intval($user->profile_id)) {
  1243. if ($status['visibility'] == 'private') {
  1244. abort_if(! FollowerService::follows($user->profile_id, $spid), 403);
  1245. } else {
  1246. abort_if(! in_array($status['visibility'], ['public', 'unlisted']), 403);
  1247. }
  1248. }
  1249. $like = Like::whereProfileId($user->profile_id)
  1250. ->whereStatusId($status['id'])
  1251. ->first();
  1252. if ($like) {
  1253. $like->forceDelete();
  1254. $ogStatus = Status::find($status['id']);
  1255. if ($ogStatus) {
  1256. $ogStatus->likes_count = $ogStatus->likes_count > 1 ? $ogStatus->likes_count - 1 : 0;
  1257. $ogStatus->save();
  1258. }
  1259. }
  1260. StatusService::del($status['id']);
  1261. $status['favourited'] = false;
  1262. $status['favourites_count'] = isset($ogStatus) ? $ogStatus->likes_count : $status['favourites_count'] - 1;
  1263. return $this->json($status);
  1264. }
  1265. /**
  1266. * GET /api/v1/filters
  1267. *
  1268. * Return empty response since we filter server side
  1269. *
  1270. * @return array
  1271. */
  1272. public function accountFilters(Request $request)
  1273. {
  1274. abort_if(! $request->user() || ! $request->user()->token(), 403);
  1275. abort_unless($request->user()->tokenCan('read'), 403);
  1276. return response()->json([]);
  1277. }
  1278. /**
  1279. * GET /api/v1/follow_requests
  1280. *
  1281. * Return array of Accounts that have sent follow requests
  1282. *
  1283. * @return \App\Transformer\Api\AccountTransformer
  1284. */
  1285. public function accountFollowRequests(Request $request)
  1286. {
  1287. abort_if(! $request->user() || ! $request->user()->token(), 403);
  1288. abort_unless($request->user()->tokenCan('read'), 403);
  1289. $this->validate($request, [
  1290. 'limit' => 'sometimes|integer|min:1|max:100',
  1291. ]);
  1292. $user = $request->user();
  1293. $res = FollowRequest::whereFollowingId($user->profile->id)
  1294. ->limit($request->input('limit', 40))
  1295. ->pluck('follower_id')
  1296. ->map(function ($id) {
  1297. return AccountService::getMastodon($id, true);
  1298. })
  1299. ->filter(function ($acct) {
  1300. return $acct && isset($acct['id']);
  1301. })
  1302. ->values();
  1303. return $this->json($res);
  1304. }
  1305. /**
  1306. * POST /api/v1/follow_requests/{id}/authorize
  1307. *
  1308. * @param int $id
  1309. * @return null
  1310. */
  1311. public function accountFollowRequestAccept(Request $request, $id)
  1312. {
  1313. abort_if(! $request->user() || ! $request->user()->token(), 403);
  1314. abort_unless($request->user()->tokenCan('follow'), 403);
  1315. $pid = $request->user()->profile_id;
  1316. $target = AccountService::getMastodon($id);
  1317. if (! $target) {
  1318. return response()->json(['error' => 'Record not found'], 404);
  1319. }
  1320. if ($target && strpos($target['acct'], '@') != -1) {
  1321. $domain = parse_url($target['url'], PHP_URL_HOST);
  1322. abort_if(in_array($domain, InstanceService::getBannedDomains()), 404);
  1323. }
  1324. $followRequest = FollowRequest::whereFollowingId($pid)->whereFollowerId($id)->first();
  1325. if (! $followRequest) {
  1326. return response()->json(['error' => 'Record not found'], 404);
  1327. }
  1328. $follower = $followRequest->follower;
  1329. $follow = new Follower();
  1330. $follow->profile_id = $follower->id;
  1331. $follow->following_id = $pid;
  1332. $follow->save();
  1333. $profile = Profile::findOrFail($pid);
  1334. $profile->followers_count++;
  1335. $profile->save();
  1336. AccountService::del($profile->id);
  1337. $profile = Profile::findOrFail($follower->id);
  1338. $profile->following_count++;
  1339. $profile->save();
  1340. AccountService::del($profile->id);
  1341. if ($follower->domain != null && $follower->private_key === null) {
  1342. FollowAcceptPipeline::dispatch($followRequest)->onQueue('follow');
  1343. } else {
  1344. FollowPipeline::dispatch($follow);
  1345. $followRequest->delete();
  1346. }
  1347. RelationshipService::refresh($pid, $id);
  1348. $res = RelationshipService::get($pid, $id);
  1349. $res['followed_by'] = true;
  1350. return $this->json($res);
  1351. }
  1352. /**
  1353. * POST /api/v1/follow_requests/{id}/reject
  1354. *
  1355. * @param int $id
  1356. * @return null
  1357. */
  1358. public function accountFollowRequestReject(Request $request, $id)
  1359. {
  1360. abort_if(! $request->user() || ! $request->user()->token(), 403);
  1361. abort_unless($request->user()->tokenCan('follow'), 403);
  1362. $pid = $request->user()->profile_id;
  1363. $target = AccountService::getMastodon($id);
  1364. if (! $target) {
  1365. return response()->json(['error' => 'Record not found'], 404);
  1366. }
  1367. $followRequest = FollowRequest::whereFollowingId($pid)->whereFollowerId($id)->first();
  1368. if (! $followRequest) {
  1369. return response()->json(['error' => 'Record not found'], 404);
  1370. }
  1371. $follower = $followRequest->follower;
  1372. if ($follower->domain != null && $follower->private_key === null) {
  1373. FollowRejectPipeline::dispatch($followRequest)->onQueue('follow');
  1374. } else {
  1375. $followRequest->delete();
  1376. }
  1377. RelationshipService::refresh($pid, $id);
  1378. $res = RelationshipService::get($pid, $id);
  1379. return $this->json($res);
  1380. }
  1381. /**
  1382. * GET /api/v1/suggestions
  1383. *
  1384. * Return empty array as we don't support suggestions
  1385. *
  1386. * @return null
  1387. */
  1388. public function accountSuggestions(Request $request)
  1389. {
  1390. abort_if(! $request->user() || ! $request->user()->token(), 403);
  1391. abort_unless($request->user()->tokenCan('read'), 403);
  1392. // todo
  1393. return response()->json([]);
  1394. }
  1395. /**
  1396. * GET /api/v1/instance
  1397. *
  1398. * Information about the server.
  1399. *
  1400. * @return Instance
  1401. */
  1402. public function instance(Request $request)
  1403. {
  1404. $res = Cache::remember('api:v1:instance-data-response-v1', 1800, function () {
  1405. $contact = Cache::remember('api:v1:instance-data:contact', 604800, function () {
  1406. if (config_cache('instance.admin.pid')) {
  1407. return AccountService::getMastodon(config_cache('instance.admin.pid'), true);
  1408. }
  1409. $admin = User::whereIsAdmin(true)->first();
  1410. return $admin && isset($admin->profile_id) ?
  1411. AccountService::getMastodon($admin->profile_id, true) :
  1412. null;
  1413. });
  1414. $stats = Cache::remember('api:v1:instance-data:stats', 43200, function () {
  1415. return [
  1416. 'user_count' => User::count(),
  1417. 'status_count' => StatusService::totalLocalStatuses(),
  1418. 'domain_count' => Instance::count(),
  1419. ];
  1420. });
  1421. $rules = Cache::remember('api:v1:instance-data:rules', 604800, function () {
  1422. return config_cache('app.rules') ?
  1423. collect(json_decode(config_cache('app.rules'), true))
  1424. ->map(function ($rule, $key) {
  1425. $id = $key + 1;
  1426. return [
  1427. 'id' => "{$id}",
  1428. 'text' => $rule,
  1429. ];
  1430. })
  1431. ->toArray() : [];
  1432. });
  1433. return [
  1434. 'uri' => config('pixelfed.domain.app'),
  1435. 'title' => config_cache('app.name'),
  1436. 'short_description' => config_cache('app.short_description'),
  1437. 'description' => config_cache('app.description'),
  1438. 'email' => config('instance.email'),
  1439. 'version' => '3.5.3 (compatible; Pixelfed '.config('pixelfed.version').')',
  1440. 'urls' => [
  1441. 'streaming_api' => null,
  1442. ],
  1443. 'stats' => $stats,
  1444. 'thumbnail' => config_cache('app.banner_image') ?? url(Storage::url('public/headers/default.jpg')),
  1445. 'languages' => [config('app.locale')],
  1446. 'registrations' => (bool) config_cache('pixelfed.open_registration'),
  1447. 'approval_required' => (bool) config_cache('instance.curated_registration.enabled'),
  1448. 'contact_account' => $contact,
  1449. 'rules' => $rules,
  1450. 'configuration' => [
  1451. 'media_attachments' => [
  1452. 'image_matrix_limit' => 16777216,
  1453. 'image_size_limit' => config_cache('pixelfed.max_photo_size') * 1024,
  1454. 'supported_mime_types' => explode(',', config_cache('pixelfed.media_types')),
  1455. 'video_frame_rate_limit' => 120,
  1456. 'video_matrix_limit' => 2304000,
  1457. 'video_size_limit' => config_cache('pixelfed.max_photo_size') * 1024,
  1458. ],
  1459. 'polls' => [
  1460. 'max_characters_per_option' => 50,
  1461. 'max_expiration' => 2629746,
  1462. 'max_options' => 4,
  1463. 'min_expiration' => 300,
  1464. ],
  1465. 'statuses' => [
  1466. 'characters_reserved_per_url' => 23,
  1467. 'max_characters' => (int) config_cache('pixelfed.max_caption_length'),
  1468. 'max_media_attachments' => (int) config_cache('pixelfed.max_album_length'),
  1469. ],
  1470. ],
  1471. ];
  1472. });
  1473. return $this->json($res);
  1474. }
  1475. /**
  1476. * GET /api/v1/lists
  1477. *
  1478. * Return empty array as we don't support lists
  1479. *
  1480. * @return null
  1481. */
  1482. public function accountLists(Request $request)
  1483. {
  1484. abort_if(! $request->user() || ! $request->user()->token(), 403);
  1485. abort_unless($request->user()->tokenCan('read'), 403);
  1486. return response()->json([]);
  1487. }
  1488. /**
  1489. * GET /api/v1/accounts/{id}/lists
  1490. *
  1491. * @param int $id
  1492. * @return null
  1493. */
  1494. public function accountListsById(Request $request, $id)
  1495. {
  1496. abort_if(! $request->user() || ! $request->user()->token(), 403);
  1497. abort_unless($request->user()->tokenCan('read'), 403);
  1498. return response()->json([]);
  1499. }
  1500. /**
  1501. * POST /api/v1/media
  1502. *
  1503. *
  1504. * @return MediaTransformer
  1505. */
  1506. public function mediaUpload(Request $request)
  1507. {
  1508. abort_if(! $request->user() || ! $request->user()->token(), 403);
  1509. abort_unless($request->user()->tokenCan('write'), 403);
  1510. $this->validate($request, [
  1511. 'file.*' => [
  1512. 'required_without:file',
  1513. 'mimetypes:'.config_cache('pixelfed.media_types'),
  1514. 'max:'.config_cache('pixelfed.max_photo_size'),
  1515. ],
  1516. 'file' => [
  1517. 'required_without:file.*',
  1518. 'mimetypes:'.config_cache('pixelfed.media_types'),
  1519. 'max:'.config_cache('pixelfed.max_photo_size'),
  1520. ],
  1521. 'filter_name' => 'nullable|string|max:24',
  1522. 'filter_class' => 'nullable|alpha_dash|max:24',
  1523. 'description' => 'nullable|string|max:'.config_cache('pixelfed.max_altext_length'),
  1524. ]);
  1525. $user = $request->user();
  1526. abort_if($user->has_roles && ! UserRoleService::can('can-post', $user->id), 403, 'Invalid permissions for this action');
  1527. AccountService::setLastActive($user->id);
  1528. if ($user->last_active_at == null) {
  1529. return [];
  1530. }
  1531. if (empty($request->file('file'))) {
  1532. return response('', 422);
  1533. }
  1534. $limitKey = 'compose:rate-limit:media-upload:'.$user->id;
  1535. $limitTtl = now()->addMinutes(15);
  1536. $limitReached = Cache::remember($limitKey, $limitTtl, function () use ($user) {
  1537. $dailyLimit = Media::whereUserId($user->id)->where('created_at', '>', now()->subDays(1))->count();
  1538. return $dailyLimit >= 1250;
  1539. });
  1540. abort_if($limitReached == true, 429);
  1541. $profile = $user->profile;
  1542. if (config_cache('pixelfed.enforce_account_limit') == true) {
  1543. $size = Cache::remember($user->storageUsedKey(), now()->addDays(3), function () use ($user) {
  1544. return Media::whereUserId($user->id)->sum('size') / 1000;
  1545. });
  1546. $limit = (int) config_cache('pixelfed.max_account_size');
  1547. if ($size >= $limit) {
  1548. abort(403, 'Account size limit reached.');
  1549. }
  1550. }
  1551. $filterClass = in_array($request->input('filter_class'), Filter::classes()) ? $request->input('filter_class') : null;
  1552. $filterName = in_array($request->input('filter_name'), Filter::names()) ? $request->input('filter_name') : null;
  1553. $photo = $request->file('file');
  1554. $mimes = explode(',', config_cache('pixelfed.media_types'));
  1555. if (in_array($photo->getMimeType(), $mimes) == false) {
  1556. abort(403, 'Invalid or unsupported mime type.');
  1557. }
  1558. $storagePath = MediaPathService::get($user, 2);
  1559. $path = $photo->storePublicly($storagePath);
  1560. $hash = \hash_file('sha256', $photo);
  1561. $license = null;
  1562. $mime = $photo->getMimeType();
  1563. // if($photo->getMimeType() == 'image/heic') {
  1564. // abort_if(config('image.driver') !== 'imagick', 422, 'Invalid media type');
  1565. // abort_if(!in_array('HEIC', \Imagick::queryformats()), 422, 'Unsupported media type');
  1566. // $oldPath = $path;
  1567. // $path = str_replace('.heic', '.jpg', $path);
  1568. // $mime = 'image/jpeg';
  1569. // \Image::make($photo)->save(storage_path("app/{$path}"));
  1570. // @unlink(storage_path("app/{$oldPath}"));
  1571. // }
  1572. $settings = UserSetting::whereUserId($user->id)->first();
  1573. if ($settings && ! empty($settings->compose_settings)) {
  1574. $compose = $settings->compose_settings;
  1575. if (isset($compose['default_license']) && $compose['default_license'] != 1) {
  1576. $license = $compose['default_license'];
  1577. }
  1578. }
  1579. abort_if(MediaBlocklistService::exists($hash) == true, 451);
  1580. $media = new Media();
  1581. $media->status_id = null;
  1582. $media->profile_id = $profile->id;
  1583. $media->user_id = $user->id;
  1584. $media->media_path = $path;
  1585. $media->original_sha256 = $hash;
  1586. $media->size = $photo->getSize();
  1587. $media->mime = $mime;
  1588. $media->caption = $request->input('description');
  1589. $media->filter_class = $filterClass;
  1590. $media->filter_name = $filterName;
  1591. if ($license) {
  1592. $media->license = $license;
  1593. }
  1594. $media->save();
  1595. switch ($media->mime) {
  1596. case 'image/jpeg':
  1597. case 'image/png':
  1598. ImageOptimize::dispatch($media)->onQueue('mmo');
  1599. break;
  1600. case 'video/mp4':
  1601. VideoThumbnail::dispatch($media)->onQueue('mmo');
  1602. $preview_url = '/storage/no-preview.png';
  1603. $url = '/storage/no-preview.png';
  1604. break;
  1605. }
  1606. Cache::forget($limitKey);
  1607. $resource = new Fractal\Resource\Item($media, new MediaTransformer());
  1608. $res = $this->fractal->createData($resource)->toArray();
  1609. $res['preview_url'] = $media->url().'?v='.time();
  1610. $res['url'] = $media->url().'?v='.time();
  1611. return $this->json($res);
  1612. }
  1613. /**
  1614. * PUT /api/v1/media/{id}
  1615. *
  1616. * @param int $id
  1617. * @return MediaTransformer
  1618. */
  1619. public function mediaUpdate(Request $request, $id)
  1620. {
  1621. abort_if(! $request->user() || ! $request->user()->token(), 403);
  1622. abort_unless($request->user()->tokenCan('write'), 403);
  1623. $this->validate($request, [
  1624. 'description' => 'nullable|string|max:'.config_cache('pixelfed.max_altext_length'),
  1625. ]);
  1626. $user = $request->user();
  1627. abort_if($user->has_roles && ! UserRoleService::can('can-post', $user->id), 403, 'Invalid permissions for this action');
  1628. AccountService::setLastActive($user->id);
  1629. $media = Media::whereUserId($user->id)
  1630. ->whereProfileId($user->profile_id)
  1631. ->findOrFail($id);
  1632. $executed = RateLimiter::attempt(
  1633. 'media:update:'.$user->id,
  1634. 10,
  1635. function () use ($media, $request) {
  1636. $caption = Purify::clean($request->input('description'));
  1637. if ($caption != $media->caption) {
  1638. $media->caption = $caption;
  1639. $media->save();
  1640. if ($media->status_id) {
  1641. MediaService::del($media->status_id);
  1642. StatusService::del($media->status_id);
  1643. }
  1644. }
  1645. });
  1646. if (! $executed) {
  1647. return response()->json([
  1648. 'error' => 'Too many attempts. Try again in a few minutes.',
  1649. ], 429);
  1650. }
  1651. $fractal = new Fractal\Manager();
  1652. $fractal->setSerializer(new ArraySerializer());
  1653. $resource = new Fractal\Resource\Item($media, new MediaTransformer());
  1654. return $this->json($fractal->createData($resource)->toArray());
  1655. }
  1656. /**
  1657. * GET /api/v1/media/{id}
  1658. *
  1659. * @param int $id
  1660. * @return MediaTransformer
  1661. */
  1662. public function mediaGet(Request $request, $id)
  1663. {
  1664. abort_if(! $request->user() || ! $request->user()->token(), 403);
  1665. abort_unless($request->user()->tokenCan('read'), 403);
  1666. $user = $request->user();
  1667. abort_if($user->has_roles && ! UserRoleService::can('can-post', $user->id), 403, 'Invalid permissions for this action');
  1668. AccountService::setLastActive($user->id);
  1669. $media = Media::whereUserId($user->id)
  1670. ->whereNull('status_id')
  1671. ->findOrFail($id);
  1672. $resource = new Fractal\Resource\Item($media, new MediaTransformer());
  1673. $res = $this->fractal->createData($resource)->toArray();
  1674. return $this->json($res);
  1675. }
  1676. /**
  1677. * POST /api/v2/media
  1678. *
  1679. *
  1680. * @return MediaTransformer
  1681. */
  1682. public function mediaUploadV2(Request $request)
  1683. {
  1684. abort_if(! $request->user() || ! $request->user()->token(), 403);
  1685. abort_unless($request->user()->tokenCan('write'), 403);
  1686. $this->validate($request, [
  1687. 'file.*' => [
  1688. 'required_without:file',
  1689. 'mimetypes:'.config_cache('pixelfed.media_types'),
  1690. 'max:'.config_cache('pixelfed.max_photo_size'),
  1691. ],
  1692. 'file' => [
  1693. 'required_without:file.*',
  1694. 'mimetypes:'.config_cache('pixelfed.media_types'),
  1695. 'max:'.config_cache('pixelfed.max_photo_size'),
  1696. ],
  1697. 'filter_name' => 'nullable|string|max:24',
  1698. 'filter_class' => 'nullable|alpha_dash|max:24',
  1699. 'description' => 'nullable|string|max:'.config_cache('pixelfed.max_altext_length'),
  1700. 'replace_id' => 'sometimes',
  1701. ]);
  1702. $user = $request->user();
  1703. abort_if($user->has_roles && ! UserRoleService::can('can-post', $user->id), 403, 'Invalid permissions for this action');
  1704. if ($user->last_active_at == null) {
  1705. return [];
  1706. }
  1707. AccountService::setLastActive($user->id);
  1708. if (empty($request->file('file'))) {
  1709. return response('', 422);
  1710. }
  1711. $limitKey = 'compose:rate-limit:media-upload:'.$user->id;
  1712. $limitTtl = now()->addMinutes(15);
  1713. $limitReached = Cache::remember($limitKey, $limitTtl, function () use ($user) {
  1714. $dailyLimit = Media::whereUserId($user->id)->where('created_at', '>', now()->subDays(1))->count();
  1715. return $dailyLimit >= 1250;
  1716. });
  1717. abort_if($limitReached == true, 429);
  1718. $profile = $user->profile;
  1719. if (config_cache('pixelfed.enforce_account_limit') == true) {
  1720. $size = Cache::remember($user->storageUsedKey(), now()->addDays(3), function () use ($user) {
  1721. return Media::whereUserId($user->id)->sum('size') / 1000;
  1722. });
  1723. $limit = (int) config_cache('pixelfed.max_account_size');
  1724. if ($size >= $limit) {
  1725. abort(403, 'Account size limit reached.');
  1726. }
  1727. }
  1728. $filterClass = in_array($request->input('filter_class'), Filter::classes()) ? $request->input('filter_class') : null;
  1729. $filterName = in_array($request->input('filter_name'), Filter::names()) ? $request->input('filter_name') : null;
  1730. $photo = $request->file('file');
  1731. $mimes = explode(',', config_cache('pixelfed.media_types'));
  1732. if (in_array($photo->getMimeType(), $mimes) == false) {
  1733. abort(403, 'Invalid or unsupported mime type.');
  1734. }
  1735. $storagePath = MediaPathService::get($user, 2);
  1736. $path = $photo->storePublicly($storagePath);
  1737. $hash = \hash_file('sha256', $photo);
  1738. $license = null;
  1739. $mime = $photo->getMimeType();
  1740. $settings = UserSetting::whereUserId($user->id)->first();
  1741. if ($settings && ! empty($settings->compose_settings)) {
  1742. $compose = $settings->compose_settings;
  1743. if (isset($compose['default_license']) && $compose['default_license'] != 1) {
  1744. $license = $compose['default_license'];
  1745. }
  1746. }
  1747. abort_if(MediaBlocklistService::exists($hash) == true, 451);
  1748. if ($request->has('replace_id')) {
  1749. $rpid = $request->input('replace_id');
  1750. $removeMedia = Media::whereNull('status_id')
  1751. ->whereUserId($user->id)
  1752. ->whereProfileId($profile->id)
  1753. ->where('created_at', '>', now()->subHours(2))
  1754. ->find($rpid);
  1755. if ($removeMedia) {
  1756. $dateTime = Carbon::now();
  1757. MediaDeletePipeline::dispatch($removeMedia)
  1758. ->onQueue('mmo')
  1759. ->delay($dateTime->addMinutes(15));
  1760. }
  1761. }
  1762. $media = new Media();
  1763. $media->status_id = null;
  1764. $media->profile_id = $profile->id;
  1765. $media->user_id = $user->id;
  1766. $media->media_path = $path;
  1767. $media->original_sha256 = $hash;
  1768. $media->size = $photo->getSize();
  1769. $media->mime = $mime;
  1770. $media->caption = $request->input('description');
  1771. $media->filter_class = $filterClass;
  1772. $media->filter_name = $filterName;
  1773. if ($license) {
  1774. $media->license = $license;
  1775. }
  1776. $media->save();
  1777. switch ($media->mime) {
  1778. case 'image/jpeg':
  1779. case 'image/png':
  1780. ImageOptimize::dispatch($media)->onQueue('mmo');
  1781. break;
  1782. case 'video/mp4':
  1783. VideoThumbnail::dispatch($media)->onQueue('mmo');
  1784. $preview_url = '/storage/no-preview.png';
  1785. $url = '/storage/no-preview.png';
  1786. break;
  1787. }
  1788. Cache::forget($limitKey);
  1789. $resource = new Fractal\Resource\Item($media, new MediaTransformer());
  1790. $res = $this->fractal->createData($resource)->toArray();
  1791. $res['preview_url'] = $media->url().'?v='.time();
  1792. $res['url'] = null;
  1793. return $this->json($res, 202);
  1794. }
  1795. /**
  1796. * GET /api/v1/mutes
  1797. *
  1798. *
  1799. * @return AccountTransformer
  1800. */
  1801. public function accountMutes(Request $request)
  1802. {
  1803. abort_if(! $request->user() || ! $request->user()->token(), 403);
  1804. abort_unless($request->user()->tokenCan('read'), 403);
  1805. $this->validate($request, [
  1806. 'limit' => 'sometimes|integer|min:1',
  1807. ]);
  1808. $user = $request->user();
  1809. $limit = $request->input('limit', 40);
  1810. if ($limit > 80) {
  1811. $limit = 80;
  1812. }
  1813. $mutes = UserFilter::whereUserId($user->profile_id)
  1814. ->whereFilterableType('App\Profile')
  1815. ->whereFilterType('mute')
  1816. ->orderByDesc('id')
  1817. ->simplePaginate($limit)
  1818. ->withQueryString();
  1819. $res = $mutes->pluck('filterable_id')
  1820. ->map(function ($id) {
  1821. return AccountService::get($id, true);
  1822. })
  1823. ->filter(function ($account) {
  1824. return $account && isset($account['id']);
  1825. })
  1826. ->values();
  1827. $baseUrl = config('app.url').'/api/v1/mutes?limit='.$limit.'&';
  1828. $next = $mutes->nextPageUrl();
  1829. $prev = $mutes->previousPageUrl();
  1830. if ($next && ! $prev) {
  1831. $link = '<'.$next.'>; rel="next"';
  1832. }
  1833. if (! $next && $prev) {
  1834. $link = '<'.$prev.'>; rel="prev"';
  1835. }
  1836. if ($next && $prev) {
  1837. $link = '<'.$next.'>; rel="next",<'.$prev.'>; rel="prev"';
  1838. }
  1839. $headers = isset($link) ? ['Link' => $link] : [];
  1840. return $this->json($res, 200, $headers);
  1841. }
  1842. /**
  1843. * POST /api/v1/accounts/{id}/mute
  1844. *
  1845. * @param int $id
  1846. * @return RelationshipTransformer
  1847. */
  1848. public function accountMuteById(Request $request, $id)
  1849. {
  1850. abort_if(! $request->user() || ! $request->user()->token(), 403);
  1851. abort_unless($request->user()->tokenCan('write'), 403);
  1852. $user = $request->user();
  1853. $pid = $user->profile_id;
  1854. if (intval($pid) === intval($id)) {
  1855. return $this->json(['error' => 'You cannot mute yourself'], 500);
  1856. }
  1857. $account = Profile::findOrFail($id);
  1858. if ($account && $account->domain) {
  1859. $domain = $account->domain;
  1860. abort_if(in_array($domain, InstanceService::getBannedDomains()), 404);
  1861. }
  1862. $count = UserFilterService::muteCount($pid);
  1863. $maxLimit = (int) config_cache('instance.user_filters.max_user_mutes');
  1864. if ($count == 0) {
  1865. $filterCount = UserFilter::whereUserId($pid)
  1866. ->whereFilterType('mute')
  1867. ->get()
  1868. ->map(function ($rec) {
  1869. return AccountService::get($rec->filterable_id, true);
  1870. })
  1871. ->filter(function ($account) {
  1872. return $account && isset($account['id']);
  1873. })
  1874. ->values()
  1875. ->count();
  1876. abort_if($filterCount >= $maxLimit, 422, AccountController::FILTER_LIMIT_MUTE_TEXT.$maxLimit.' accounts');
  1877. } else {
  1878. abort_if($count >= $maxLimit, 422, AccountController::FILTER_LIMIT_MUTE_TEXT.$maxLimit.' accounts');
  1879. }
  1880. $filter = UserFilter::firstOrCreate([
  1881. 'user_id' => $pid,
  1882. 'filterable_id' => $account->id,
  1883. 'filterable_type' => 'App\Profile',
  1884. 'filter_type' => 'mute',
  1885. ]);
  1886. RelationshipService::refresh($pid, $id);
  1887. $resource = new Fractal\Resource\Item($account, new RelationshipTransformer());
  1888. $res = $this->fractal->createData($resource)->toArray();
  1889. return $this->json($res);
  1890. }
  1891. /**
  1892. * POST /api/v1/accounts/{id}/unmute
  1893. *
  1894. * @param int $id
  1895. * @return RelationshipTransformer
  1896. */
  1897. public function accountUnmuteById(Request $request, $id)
  1898. {
  1899. abort_if(! $request->user() || ! $request->user()->token(), 403);
  1900. abort_unless($request->user()->tokenCan('write'), 403);
  1901. $user = $request->user();
  1902. $pid = $user->profile_id;
  1903. if (intval($pid) === intval($id)) {
  1904. return $this->json(['error' => 'You cannot unmute yourself'], 500);
  1905. }
  1906. $profile = Profile::findOrFail($id);
  1907. $filter = UserFilter::whereUserId($pid)
  1908. ->whereFilterableId($profile->id)
  1909. ->whereFilterableType('App\Profile')
  1910. ->whereFilterType('mute')
  1911. ->first();
  1912. if ($filter) {
  1913. $filter->delete();
  1914. UserFilterService::unmute($pid, $profile->id);
  1915. }
  1916. RelationshipService::refresh($pid, $id);
  1917. $resource = new Fractal\Resource\Item($profile, new RelationshipTransformer());
  1918. $res = $this->fractal->createData($resource)->toArray();
  1919. return $this->json($res);
  1920. }
  1921. /**
  1922. * GET /api/v1/notifications
  1923. *
  1924. *
  1925. * @return NotificationTransformer
  1926. */
  1927. public function accountNotifications(Request $request)
  1928. {
  1929. abort_if(! $request->user() || ! $request->user()->token(), 403);
  1930. abort_unless($request->user()->tokenCan('read'), 403);
  1931. $this->validate($request, [
  1932. 'limit' => 'sometimes|integer|min:1',
  1933. 'min_id' => 'nullable|integer|min:1|max:'.PHP_INT_MAX,
  1934. 'max_id' => 'nullable|integer|min:1|max:'.PHP_INT_MAX,
  1935. 'since_id' => 'nullable|integer|min:1|max:'.PHP_INT_MAX,
  1936. 'types[]' => 'sometimes|array',
  1937. 'types[].*' => 'string|in:mention,reblog,follow,favourite',
  1938. 'type' => 'sometimes|string|in:mention,reblog,follow,favourite',
  1939. '_pe' => 'sometimes',
  1940. ]);
  1941. $pid = $request->user()->profile_id;
  1942. $limit = $request->input('limit', 20);
  1943. $ogLimit = $request->input('limit', 20);
  1944. if ($limit > 40) {
  1945. $limit = 40;
  1946. $ogLimit = 40;
  1947. }
  1948. $since = $request->input('since_id');
  1949. $min = $request->input('min_id');
  1950. $max = $request->input('max_id');
  1951. $pe = $request->filled('_pe');
  1952. if (! $since && ! $min && ! $max) {
  1953. $min = 1;
  1954. }
  1955. if ($since) {
  1956. $min = $since + 1;
  1957. }
  1958. $types = $request->input('types');
  1959. if ($request->has('types')) {
  1960. $limit = 150;
  1961. }
  1962. $maxId = null;
  1963. $minId = null;
  1964. AccountService::setLastActive($request->user()->id);
  1965. $res = $max ?
  1966. NotificationService::getMaxMastodon($pid, $max, $limit) :
  1967. NotificationService::getMinMastodon($pid, $min ?? $since, $limit);
  1968. $ids = $max ?
  1969. NotificationService::getRankedMaxId($pid, $max, $limit) :
  1970. NotificationService::getRankedMinId($pid, $min ?? $since, $limit);
  1971. if (! empty($ids)) {
  1972. $maxId = max($ids);
  1973. $minId = min($ids);
  1974. }
  1975. if (empty($res)) {
  1976. if (! Cache::has('pf:services:notifications:hasSynced:'.$pid)) {
  1977. Cache::put('pf:services:notifications:hasSynced:'.$pid, 1, 1209600);
  1978. NotificationService::warmCache($pid, 400, true);
  1979. }
  1980. }
  1981. if ($request->has('types')) {
  1982. $typesParams = collect($types)->implode('&types[]=');
  1983. $baseUrl = config('app.url').'/api/v1/notifications?types[]='.$typesParams.'&limit='.$ogLimit.'&';
  1984. } else {
  1985. $baseUrl = config('app.url').'/api/v1/notifications?limit='.$ogLimit.'&';
  1986. }
  1987. if ($minId == $maxId) {
  1988. $minId = null;
  1989. }
  1990. $res = collect($res)
  1991. ->map(function ($n) use ($pe) {
  1992. if (! $pe) {
  1993. if ($n['type'] == 'comment') {
  1994. $n['type'] = 'mention';
  1995. return $n;
  1996. }
  1997. return $n;
  1998. }
  1999. return $n;
  2000. })
  2001. ->filter(function ($n) use ($pe) {
  2002. if (in_array($n['type'], ['mention', 'reblog', 'favourite'])) {
  2003. return isset($n['status'], $n['status']['id']);
  2004. }
  2005. if (! $pe) {
  2006. if (in_array($n['type'], [
  2007. 'tagged',
  2008. 'modlog',
  2009. 'story:react',
  2010. 'story:comment',
  2011. 'group:comment',
  2012. 'group:join:approved',
  2013. 'group:join:rejected',
  2014. ])) {
  2015. return false;
  2016. }
  2017. return isset($n['account'], $n['account']['id']);
  2018. }
  2019. return true;
  2020. })
  2021. ->filter(function ($n) use ($types) {
  2022. if (! $types) {
  2023. return true;
  2024. }
  2025. return in_array($n['type'], $types);
  2026. })
  2027. ->take($ogLimit)
  2028. ->values();
  2029. if ($maxId) {
  2030. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next"';
  2031. }
  2032. if ($minId) {
  2033. $link = '<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  2034. }
  2035. if ($maxId && $minId) {
  2036. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next",<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  2037. }
  2038. $headers = isset($link) ? ['Link' => $link] : [];
  2039. return $this->json($res, 200, $headers);
  2040. }
  2041. /**
  2042. * GET /api/v1/timelines/home
  2043. *
  2044. *
  2045. * @return StatusTransformer
  2046. */
  2047. public function timelineHome(Request $request)
  2048. {
  2049. abort_if(! $request->user() || ! $request->user()->token(), 403);
  2050. abort_unless($request->user()->tokenCan('read'), 403);
  2051. $this->validate($request, [
  2052. 'page' => 'sometimes|integer|max:40',
  2053. 'min_id' => 'sometimes|integer|min:0|max:'.PHP_INT_MAX,
  2054. 'max_id' => 'sometimes|integer|min:0|max:'.PHP_INT_MAX,
  2055. 'limit' => 'sometimes|integer|min:1',
  2056. 'include_reblogs' => 'sometimes',
  2057. ]);
  2058. $napi = $request->has(self::PF_API_ENTITY_KEY);
  2059. $page = $request->input('page');
  2060. $min = $request->input('min_id');
  2061. $max = $request->input('max_id');
  2062. $limit = $request->input('limit') ?? 20;
  2063. if ($limit > 40) {
  2064. $limit = 40;
  2065. }
  2066. $pid = $request->user()->profile_id;
  2067. $includeReblogs = $request->filled('include_reblogs') ? $request->boolean('include_reblogs') : false;
  2068. $nullFields = $includeReblogs ?
  2069. ['in_reply_to_id'] :
  2070. ['in_reply_to_id', 'reblog_of_id'];
  2071. $inTypes = $includeReblogs ?
  2072. ['photo', 'photo:album', 'video', 'video:album', 'photo:video:album', 'share'] :
  2073. ['photo', 'photo:album', 'video', 'video:album', 'photo:video:album'];
  2074. AccountService::setLastActive($request->user()->id);
  2075. if (config('exp.cached_home_timeline')) {
  2076. $paddedLimit = $includeReblogs ? $limit + 10 : $limit + 50;
  2077. if ($min || $max) {
  2078. if ($request->has('min_id')) {
  2079. $res = HomeTimelineService::getRankedMinId($pid, $min ?? 0, $paddedLimit);
  2080. } else {
  2081. $res = HomeTimelineService::getRankedMaxId($pid, $max ?? 0, $paddedLimit);
  2082. }
  2083. } else {
  2084. $res = HomeTimelineService::get($pid, 0, $paddedLimit);
  2085. }
  2086. if (! $res) {
  2087. $res = Cache::has('pf:services:apiv1:home:cached:coldbootcheck:'.$pid);
  2088. if (! $res) {
  2089. Cache::set('pf:services:apiv1:home:cached:coldbootcheck:'.$pid, 1, 86400);
  2090. FeedWarmCachePipeline::dispatchSync($pid);
  2091. return response()->json([], 206);
  2092. } else {
  2093. Cache::set('pf:services:apiv1:home:cached:coldbootcheck:'.$pid, 1, 86400);
  2094. return response()->json([], 206);
  2095. }
  2096. }
  2097. $res = collect($res)
  2098. ->map(function ($id) use ($napi) {
  2099. return $napi ? StatusService::get($id, false) : StatusService::getMastodon($id, false);
  2100. })
  2101. ->filter(function ($res) {
  2102. return $res && isset($res['account']);
  2103. })
  2104. ->filter(function ($s) use ($includeReblogs) {
  2105. return $includeReblogs ? true : $s['reblog'] == null;
  2106. })
  2107. ->take($limit)
  2108. ->map(function ($status) use ($pid) {
  2109. if ($pid) {
  2110. $status['favourited'] = (bool) LikeService::liked($pid, $status['id']);
  2111. $status['reblogged'] = (bool) ReblogService::get($pid, $status['id']);
  2112. $status['bookmarked'] = (bool) BookmarkService::get($pid, $status['id']);
  2113. }
  2114. return $status;
  2115. })
  2116. ->values();
  2117. $baseUrl = config('app.url').'/api/v1/timelines/home?limit='.$limit.'&';
  2118. $minId = $res->map(function ($s) {
  2119. return ['id' => $s['id']];
  2120. })->min('id');
  2121. $maxId = $res->map(function ($s) {
  2122. return ['id' => $s['id']];
  2123. })->max('id');
  2124. if ($minId == $maxId) {
  2125. $minId = null;
  2126. }
  2127. if ($maxId) {
  2128. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next"';
  2129. }
  2130. if ($minId) {
  2131. $link = '<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  2132. }
  2133. if ($maxId && $minId) {
  2134. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next",<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  2135. }
  2136. $headers = isset($link) ? ['Link' => $link] : [];
  2137. return $this->json($res->toArray(), 200, $headers);
  2138. }
  2139. $following = Cache::remember('profile:following:'.$pid, 1209600, function () use ($pid) {
  2140. $following = Follower::whereProfileId($pid)->pluck('following_id');
  2141. return $following->push($pid)->toArray();
  2142. });
  2143. $muted = UserFilterService::mutes($pid);
  2144. if ($muted && count($muted)) {
  2145. $following = array_diff($following, $muted);
  2146. }
  2147. if ($min || $max) {
  2148. $dir = $min ? '>' : '<';
  2149. $id = $min ?? $max;
  2150. $res = Status::select(
  2151. 'id',
  2152. 'profile_id',
  2153. 'type',
  2154. 'visibility',
  2155. 'in_reply_to_id',
  2156. 'reblog_of_id'
  2157. )
  2158. ->where('id', $dir, $id)
  2159. ->whereNull($nullFields)
  2160. ->whereIntegerInRaw('profile_id', $following)
  2161. ->whereIn('type', $inTypes)
  2162. ->whereIn('visibility', ['public', 'unlisted', 'private'])
  2163. ->orderByDesc('id')
  2164. ->take(($limit * 2))
  2165. ->get()
  2166. ->map(function ($s) use ($pid, $napi) {
  2167. try {
  2168. $account = $napi ? AccountService::get($s['profile_id'], true) : AccountService::getMastodon($s['profile_id'], true);
  2169. if (! $account) {
  2170. return false;
  2171. }
  2172. $status = $napi ? StatusService::get($s['id'], false) : StatusService::getMastodon($s['id'], false);
  2173. if (! $status || ! isset($status['account']) || ! isset($status['account']['id'])) {
  2174. return false;
  2175. }
  2176. } catch (\Exception $e) {
  2177. return false;
  2178. }
  2179. $status['account'] = $account;
  2180. if ($pid) {
  2181. $status['favourited'] = (bool) LikeService::liked($pid, $s['id']);
  2182. $status['reblogged'] = (bool) ReblogService::get($pid, $status['id']);
  2183. $status['bookmarked'] = (bool) BookmarkService::get($pid, $status['id']);
  2184. }
  2185. return $status;
  2186. })
  2187. ->filter(function ($status) {
  2188. return $status && isset($status['account']);
  2189. })
  2190. ->map(function ($status) use ($pid) {
  2191. if (! empty($status['reblog'])) {
  2192. $status['reblog']['favourited'] = (bool) LikeService::liked($pid, $status['reblog']['id']);
  2193. $status['reblog']['reblogged'] = (bool) ReblogService::get($pid, $status['reblog']['id']);
  2194. $status['bookmarked'] = (bool) BookmarkService::get($pid, $status['id']);
  2195. }
  2196. return $status;
  2197. })
  2198. ->take($limit)
  2199. ->values();
  2200. } else {
  2201. $res = Status::select(
  2202. 'id',
  2203. 'profile_id',
  2204. 'type',
  2205. 'visibility',
  2206. 'in_reply_to_id',
  2207. 'reblog_of_id',
  2208. )
  2209. ->whereNull($nullFields)
  2210. ->whereIntegerInRaw('profile_id', $following)
  2211. ->whereIn('type', $inTypes)
  2212. ->whereIn('visibility', ['public', 'unlisted', 'private'])
  2213. ->orderByDesc('id')
  2214. ->take(($limit * 2))
  2215. ->get()
  2216. ->map(function ($s) use ($pid, $napi) {
  2217. try {
  2218. $account = $napi ? AccountService::get($s['profile_id'], true) : AccountService::getMastodon($s['profile_id'], true);
  2219. if (! $account) {
  2220. return false;
  2221. }
  2222. $status = $napi ? StatusService::get($s['id'], false) : StatusService::getMastodon($s['id'], false);
  2223. if (! $status || ! isset($status['account']) || ! isset($status['account']['id'])) {
  2224. return false;
  2225. }
  2226. } catch (\Exception $e) {
  2227. return false;
  2228. }
  2229. $status['account'] = $account;
  2230. if ($pid) {
  2231. $status['favourited'] = (bool) LikeService::liked($pid, $s['id']);
  2232. $status['reblogged'] = (bool) ReblogService::get($pid, $status['id']);
  2233. $status['bookmarked'] = (bool) BookmarkService::get($pid, $status['id']);
  2234. }
  2235. return $status;
  2236. })
  2237. ->filter(function ($status) {
  2238. return $status && isset($status['account']);
  2239. })
  2240. ->map(function ($status) use ($pid) {
  2241. if (! empty($status['reblog'])) {
  2242. $status['reblog']['favourited'] = (bool) LikeService::liked($pid, $status['reblog']['id']);
  2243. $status['reblog']['reblogged'] = (bool) ReblogService::get($pid, $status['reblog']['id']);
  2244. $status['bookmarked'] = (bool) BookmarkService::get($pid, $status['id']);
  2245. }
  2246. return $status;
  2247. })
  2248. ->take($limit)
  2249. ->values();
  2250. }
  2251. $baseUrl = config('app.url').'/api/v1/timelines/home?limit='.$limit.'&';
  2252. $minId = $res->map(function ($s) {
  2253. return ['id' => $s['id']];
  2254. })->min('id');
  2255. $maxId = $res->map(function ($s) {
  2256. return ['id' => $s['id']];
  2257. })->max('id');
  2258. if ($minId == $maxId) {
  2259. $minId = null;
  2260. }
  2261. if ($maxId) {
  2262. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next"';
  2263. }
  2264. if ($minId) {
  2265. $link = '<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  2266. }
  2267. if ($maxId && $minId) {
  2268. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next",<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  2269. }
  2270. $headers = isset($link) ? ['Link' => $link] : [];
  2271. return $this->json($res->toArray(), 200, $headers);
  2272. }
  2273. /**
  2274. * GET /api/v1/timelines/public
  2275. *
  2276. *
  2277. * @return StatusTransformer
  2278. */
  2279. public function timelinePublic(Request $request)
  2280. {
  2281. $this->validate($request, [
  2282. 'min_id' => 'nullable|integer|min:0|max:'.PHP_INT_MAX,
  2283. 'max_id' => 'nullable|integer|min:0|max:'.PHP_INT_MAX,
  2284. 'limit' => 'sometimes|integer|min:1',
  2285. 'remote' => 'sometimes',
  2286. 'local' => 'sometimes',
  2287. ]);
  2288. $napi = $request->has(self::PF_API_ENTITY_KEY);
  2289. $min = $request->input('min_id');
  2290. $max = $request->input('max_id');
  2291. if ($max == 0) {
  2292. $min = 1;
  2293. }
  2294. $minOrMax = $request->anyFilled(['max_id', 'min_id']);
  2295. $limit = $request->input('limit') ?? 20;
  2296. if ($limit > 40) {
  2297. $limit = 40;
  2298. }
  2299. $user = $request->user();
  2300. $remote = $request->has('remote') && $request->boolean('remote');
  2301. $local = $request->boolean('local');
  2302. $userRoleKey = $remote ? 'can-view-network-feed' : 'can-view-public-feed';
  2303. if ($user->has_roles && ! UserRoleService::can($userRoleKey, $user->id)) {
  2304. return [];
  2305. }
  2306. $filtered = $user ? UserFilterService::filters($user->profile_id) : [];
  2307. AccountService::setLastActive($user->id);
  2308. $domainBlocks = UserFilterService::domainBlocks($user->profile_id);
  2309. $hideNsfw = config('instance.hide_nsfw_on_public_feeds');
  2310. $amin = SnowflakeService::byDate(now()->subDays(config('federation.network_timeline_days_falloff')));
  2311. $asf = AdminShadowFilterService::getHideFromPublicFeedsList();
  2312. if ($local && $remote) {
  2313. $feed = Status::select(
  2314. 'id',
  2315. 'uri',
  2316. 'type',
  2317. 'scope',
  2318. 'created_at',
  2319. 'profile_id',
  2320. 'in_reply_to_id',
  2321. 'reblog_of_id'
  2322. )
  2323. ->when($minOrMax, function ($q, $minOrMax) use ($min, $max) {
  2324. $dir = $min ? '>' : '<';
  2325. $id = $min ?? $max;
  2326. return $q->where('id', $dir, $id);
  2327. })
  2328. ->whereNull(['in_reply_to_id', 'reblog_of_id'])
  2329. ->when($hideNsfw, function ($q, $hideNsfw) {
  2330. return $q->where('is_nsfw', false);
  2331. })
  2332. ->whereIn('type', ['photo', 'photo:album', 'video', 'video:album', 'photo:video:album'])
  2333. ->whereScope('public')
  2334. ->where('id', '>', $amin)
  2335. ->orderByDesc('id')
  2336. ->limit(($limit * 2))
  2337. ->pluck('id')
  2338. ->values()
  2339. ->toArray();
  2340. } elseif ($remote && ! $local) {
  2341. if (config('instance.timeline.network.cached')) {
  2342. Cache::remember('api:v1:timelines:network:cache_check', 10368000, function () {
  2343. if (NetworkTimelineService::count() == 0) {
  2344. NetworkTimelineService::warmCache(true, config('instance.timeline.network.cache_dropoff'));
  2345. }
  2346. });
  2347. if ($max) {
  2348. $feed = NetworkTimelineService::getRankedMaxId($max, $limit + 5);
  2349. } elseif ($min) {
  2350. $feed = NetworkTimelineService::getRankedMinId($min, $limit + 5);
  2351. } else {
  2352. $feed = NetworkTimelineService::get(0, $limit + 5);
  2353. }
  2354. } else {
  2355. $feed = Status::select(
  2356. 'id',
  2357. 'uri',
  2358. 'type',
  2359. 'scope',
  2360. 'local',
  2361. 'created_at',
  2362. 'profile_id',
  2363. 'in_reply_to_id',
  2364. 'reblog_of_id'
  2365. )
  2366. ->when($minOrMax, function ($q, $minOrMax) use ($min, $max) {
  2367. $dir = $min ? '>' : '<';
  2368. $id = $min ?? $max;
  2369. return $q->where('id', $dir, $id);
  2370. })
  2371. ->whereNull(['in_reply_to_id', 'reblog_of_id'])
  2372. ->when($hideNsfw, function ($q, $hideNsfw) {
  2373. return $q->where('is_nsfw', false);
  2374. })
  2375. ->whereIn('type', ['photo', 'photo:album', 'video', 'video:album', 'photo:video:album'])
  2376. ->whereLocal(false)
  2377. ->whereScope('public')
  2378. ->where('id', '>', $amin)
  2379. ->orderByDesc('id')
  2380. ->limit(($limit * 2))
  2381. ->pluck('id')
  2382. ->values()
  2383. ->toArray();
  2384. }
  2385. } else {
  2386. if (config('instance.timeline.local.cached')) {
  2387. Cache::remember('api:v1:timelines:public:cache_check', 10368000, function () {
  2388. if (PublicTimelineService::count() == 0) {
  2389. PublicTimelineService::warmCache(true, 400);
  2390. }
  2391. });
  2392. if ($max) {
  2393. $feed = PublicTimelineService::getRankedMaxId($max, $limit + 5);
  2394. } elseif ($min) {
  2395. $feed = PublicTimelineService::getRankedMinId($min, $limit + 5);
  2396. } else {
  2397. $feed = PublicTimelineService::get(0, $limit + 5);
  2398. }
  2399. } else {
  2400. $feed = Status::select(
  2401. 'id',
  2402. 'uri',
  2403. 'type',
  2404. 'scope',
  2405. 'local',
  2406. 'created_at',
  2407. 'profile_id',
  2408. 'in_reply_to_id',
  2409. 'reblog_of_id'
  2410. )
  2411. ->when($minOrMax, function ($q, $minOrMax) use ($min, $max) {
  2412. $dir = $min ? '>' : '<';
  2413. $id = $min ?? $max;
  2414. return $q->where('id', $dir, $id);
  2415. })
  2416. ->whereNull(['in_reply_to_id', 'reblog_of_id'])
  2417. ->when($hideNsfw, function ($q, $hideNsfw) {
  2418. return $q->where('is_nsfw', false);
  2419. })
  2420. ->whereIn('type', ['photo', 'photo:album', 'video', 'video:album', 'photo:video:album'])
  2421. ->whereLocal(true)
  2422. ->whereScope('public')
  2423. ->where('id', '>', $amin)
  2424. ->orderByDesc('id')
  2425. ->limit(($limit * 2))
  2426. ->pluck('id')
  2427. ->values()
  2428. ->toArray();
  2429. }
  2430. }
  2431. $res = collect($feed)
  2432. ->filter(function ($k) use ($min, $max) {
  2433. if (! $min && ! $max) {
  2434. return true;
  2435. }
  2436. if ($min) {
  2437. return $min != $k;
  2438. }
  2439. if ($max) {
  2440. return $max != $k;
  2441. }
  2442. })
  2443. ->map(function ($k) use ($user, $napi) {
  2444. try {
  2445. $status = $napi ? StatusService::get($k) : StatusService::getMastodon($k);
  2446. if (! $status || ! isset($status['account']) || ! isset($status['account']['id'])) {
  2447. return false;
  2448. }
  2449. } catch (\Exception $e) {
  2450. return false;
  2451. }
  2452. $account = $napi ? AccountService::get($status['account']['id'], true) : AccountService::getMastodon($status['account']['id'], true);
  2453. if (! $account) {
  2454. return false;
  2455. }
  2456. $status['account'] = $account;
  2457. if ($user) {
  2458. $status['favourited'] = (bool) LikeService::liked($user->profile_id, $k);
  2459. $status['reblogged'] = (bool) ReblogService::get($user->profile_id, $status['id']);
  2460. $status['bookmarked'] = (bool) BookmarkService::get($user->profile_id, $status['id']);
  2461. }
  2462. return $status;
  2463. })
  2464. ->filter(function ($s) use ($filtered) {
  2465. return $s && isset($s['account']) && in_array($s['account']['id'], $filtered) == false;
  2466. })
  2467. ->filter(function ($s) use ($domainBlocks) {
  2468. if (! $domainBlocks || ! count($domainBlocks)) {
  2469. return $s;
  2470. }
  2471. $domain = strtolower(parse_url($s['url'], PHP_URL_HOST));
  2472. return ! in_array($domain, $domainBlocks);
  2473. })
  2474. ->filter(function ($s) use ($asf, $user) {
  2475. if (! $asf || count($asf) === 0) {
  2476. return true;
  2477. }
  2478. if (in_array($s['account']['id'], $asf)) {
  2479. if ($user->profile_id == $s['account']['id']) {
  2480. return true;
  2481. }
  2482. return false;
  2483. }
  2484. return true;
  2485. })
  2486. ->take($limit)
  2487. ->values();
  2488. $baseUrl = config('app.url').'/api/v1/timelines/public?limit='.$limit.'&';
  2489. if ($remote) {
  2490. $baseUrl .= 'remote=1&';
  2491. }
  2492. if ($local) {
  2493. $baseUrl .= 'local=1&';
  2494. }
  2495. $minId = $res->map(function ($s) {
  2496. return ['id' => $s['id']];
  2497. })->min('id');
  2498. $maxId = $res->map(function ($s) {
  2499. return ['id' => $s['id']];
  2500. })->max('id');
  2501. if ($minId == $maxId) {
  2502. $minId = null;
  2503. }
  2504. if ($maxId) {
  2505. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next"';
  2506. }
  2507. if ($minId) {
  2508. $link = '<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  2509. }
  2510. if ($maxId && $minId) {
  2511. $link = '<'.$baseUrl.'max_id='.$minId.'>; rel="next",<'.$baseUrl.'min_id='.$maxId.'>; rel="prev"';
  2512. }
  2513. $headers = isset($link) ? ['Link' => $link] : [];
  2514. return $this->json($res->toArray(), 200, $headers);
  2515. }
  2516. /**
  2517. * GET /api/v1/conversations
  2518. *
  2519. * Not implemented
  2520. *
  2521. * @return array
  2522. */
  2523. public function conversations(Request $request)
  2524. {
  2525. abort_if(! $request->user() || ! $request->user()->token(), 403);
  2526. abort_unless($request->user()->tokenCan('read'), 403);
  2527. $this->validate($request, [
  2528. 'limit' => 'min:1|max:40',
  2529. 'scope' => 'nullable|in:inbox,sent,requests',
  2530. ]);
  2531. $limit = $request->input('limit', 20);
  2532. $scope = $request->input('scope', 'inbox');
  2533. $user = $request->user();
  2534. if ($user->has_roles && ! UserRoleService::can('can-direct-message', $user->id)) {
  2535. return [];
  2536. }
  2537. $pid = $user->profile_id;
  2538. if (config('database.default') == 'pgsql') {
  2539. $dms = DirectMessage::when($scope === 'inbox', function ($q, $scope) use ($pid) {
  2540. return $q->whereIsHidden(false)->where('to_id', $pid)->orWhere('from_id', $pid);
  2541. })
  2542. ->when($scope === 'sent', function ($q, $scope) use ($pid) {
  2543. return $q->whereFromId($pid)->groupBy(['to_id', 'id']);
  2544. })
  2545. ->when($scope === 'requests', function ($q, $scope) use ($pid) {
  2546. return $q->whereToId($pid)->whereIsHidden(true);
  2547. });
  2548. } else {
  2549. $dms = Conversation::when($scope === 'inbox', function ($q, $scope) use ($pid) {
  2550. return $q->whereIsHidden(false)
  2551. ->where('to_id', $pid)
  2552. ->orWhere('from_id', $pid)
  2553. ->orderByDesc('status_id')
  2554. ->groupBy(['to_id', 'from_id']);
  2555. })
  2556. ->when($scope === 'sent', function ($q, $scope) use ($pid) {
  2557. return $q->whereFromId($pid)->groupBy('to_id');
  2558. })
  2559. ->when($scope === 'requests', function ($q, $scope) use ($pid) {
  2560. return $q->whereToId($pid)->whereIsHidden(true);
  2561. });
  2562. }
  2563. $dms = $dms->orderByDesc('status_id')
  2564. ->simplePaginate($limit)
  2565. ->map(function ($dm) use ($pid) {
  2566. $from = $pid == $dm->to_id ? $dm->from_id : $dm->to_id;
  2567. $res = [
  2568. 'id' => $dm->id,
  2569. 'unread' => false,
  2570. 'accounts' => [
  2571. AccountService::getMastodon($from, true),
  2572. ],
  2573. 'last_status' => StatusService::getDirectMessage($dm->status_id),
  2574. ];
  2575. return $res;
  2576. })
  2577. ->filter(function ($dm) {
  2578. if (! $dm || empty($dm['last_status']) || ! isset($dm['accounts']) || ! count($dm['accounts']) || ! isset($dm['accounts'][0]) || ! isset($dm['accounts'][0]['id'])) {
  2579. return false;
  2580. }
  2581. return true;
  2582. })
  2583. ->unique(function ($item, $key) {
  2584. return $item['accounts'][0]['id'];
  2585. })
  2586. ->values();
  2587. return $this->json($dms);
  2588. }
  2589. /**
  2590. * GET /api/v1/statuses/{id}
  2591. *
  2592. * @param int $id
  2593. * @return StatusTransformer
  2594. */
  2595. public function statusById(Request $request, $id)
  2596. {
  2597. abort_if(! $request->user() || ! $request->user()->token(), 403);
  2598. abort_unless($request->user()->tokenCan('read'), 403);
  2599. AccountService::setLastActive($request->user()->id);
  2600. $pid = $request->user()->profile_id;
  2601. $res = $request->has(self::PF_API_ENTITY_KEY) ? StatusService::get($id, false) : StatusService::getMastodon($id, false);
  2602. if (! $res || ! isset($res['visibility'])) {
  2603. abort(404);
  2604. }
  2605. if ($res && isset($res['account'], $res['account']['acct'], $res['account']['url']) && strpos($res['account']['acct'], '@') != -1) {
  2606. $domain = parse_url($res['account']['url'], PHP_URL_HOST);
  2607. abort_if(in_array($domain, InstanceService::getBannedDomains()), 404);
  2608. }
  2609. $scope = $res['visibility'];
  2610. if (! in_array($scope, ['public', 'unlisted'])) {
  2611. if ($scope === 'private') {
  2612. if (intval($res['account']['id']) !== intval($pid)) {
  2613. abort_unless(FollowerService::follows($pid, $res['account']['id']), 403);
  2614. }
  2615. } else {
  2616. abort(400, 'Invalid request');
  2617. }
  2618. }
  2619. if (! empty($res['reblog']) && isset($res['reblog']['id'])) {
  2620. $res['reblog']['favourited'] = (bool) LikeService::liked($pid, $res['reblog']['id']);
  2621. $res['reblog']['reblogged'] = (bool) ReblogService::get($pid, $res['reblog']['id']);
  2622. $res['reblog']['bookmarked'] = BookmarkService::get($pid, $res['reblog']['id']);
  2623. }
  2624. $res['favourited'] = LikeService::liked($pid, $res['id']);
  2625. $res['reblogged'] = ReblogService::get($pid, $res['id']);
  2626. $res['bookmarked'] = BookmarkService::get($pid, $res['id']);
  2627. return $this->json($res);
  2628. }
  2629. /**
  2630. * GET /api/v1/statuses/{id}/context
  2631. *
  2632. * @param int $id
  2633. * @return StatusTransformer
  2634. */
  2635. public function statusContext(Request $request, $id)
  2636. {
  2637. abort_if(! $request->user() || ! $request->user()->token(), 403);
  2638. abort_unless($request->user()->tokenCan('read'), 403);
  2639. $user = $request->user();
  2640. $pid = $user->profile_id;
  2641. $status = StatusService::getMastodon($id, false);
  2642. $pe = $request->has(self::PF_API_ENTITY_KEY);
  2643. if (! $status || ! isset($status['account'])) {
  2644. return response('', 404);
  2645. }
  2646. if ($status && isset($status['account'], $status['account']['acct']) && strpos($status['account']['acct'], '@') != -1) {
  2647. $domain = parse_url($status['account']['url'], PHP_URL_HOST);
  2648. abort_if(in_array($domain, InstanceService::getBannedDomains()), 404);
  2649. }
  2650. if (intval($status['account']['id']) !== intval($user->profile_id)) {
  2651. if ($status['visibility'] == 'private') {
  2652. if (! FollowerService::follows($user->profile_id, $status['account']['id'])) {
  2653. return response('', 404);
  2654. }
  2655. } else {
  2656. if (! in_array($status['visibility'], ['public', 'unlisted'])) {
  2657. return response('', 404);
  2658. }
  2659. }
  2660. }
  2661. $ancestors = [];
  2662. $descendants = [];
  2663. if ($status['in_reply_to_id']) {
  2664. $ancestors[] = $pe ?
  2665. StatusService::get($status['in_reply_to_id'], false) :
  2666. StatusService::getMastodon($status['in_reply_to_id'], false);
  2667. }
  2668. if ($status['replies_count']) {
  2669. $filters = UserFilterService::filters($pid);
  2670. $descendants = DB::table('statuses')
  2671. ->where('in_reply_to_id', $id)
  2672. ->limit(20)
  2673. ->pluck('id')
  2674. ->map(function ($sid) use ($pe) {
  2675. return $pe ?
  2676. StatusService::get($sid, false) :
  2677. StatusService::getMastodon($sid, false);
  2678. })
  2679. ->filter(function ($post) use ($filters) {
  2680. return $post && isset($post['account'], $post['account']['id']) && ! in_array($post['account']['id'], $filters);
  2681. })
  2682. ->map(function ($status) use ($pid) {
  2683. $status['favourited'] = LikeService::liked($pid, $status['id']);
  2684. $status['reblogged'] = ReblogService::get($pid, $status['id']);
  2685. return $status;
  2686. })
  2687. ->values();
  2688. }
  2689. $res = [
  2690. 'ancestors' => $ancestors,
  2691. 'descendants' => $descendants,
  2692. ];
  2693. return $this->json($res);
  2694. }
  2695. /**
  2696. * GET /api/v1/statuses/{id}/card
  2697. *
  2698. * @param int $id
  2699. * @return StatusTransformer
  2700. */
  2701. public function statusCard(Request $request, $id)
  2702. {
  2703. abort_if(! $request->user() || ! $request->user()->token(), 403);
  2704. abort_unless($request->user()->tokenCan('read'), 403);
  2705. $res = [];
  2706. return response()->json($res);
  2707. }
  2708. /**
  2709. * GET /api/v1/statuses/{id}/reblogged_by
  2710. *
  2711. * @param int $id
  2712. * @return AccountTransformer
  2713. */
  2714. public function statusRebloggedBy(Request $request, $id)
  2715. {
  2716. abort_if(! $request->user() || ! $request->user()->token(), 403);
  2717. abort_unless($request->user()->tokenCan('read'), 403);
  2718. $this->validate($request, [
  2719. 'limit' => 'sometimes|integer|min:1|max:80',
  2720. ]);
  2721. $limit = $request->input('limit', 10);
  2722. $user = $request->user();
  2723. $pid = $user->profile_id;
  2724. $status = Status::findOrFail($id);
  2725. $account = AccountService::get($status->profile_id, true);
  2726. abort_if(! $account, 404);
  2727. if ($account && strpos($account['acct'], '@') != -1) {
  2728. $domain = parse_url($account['url'], PHP_URL_HOST);
  2729. abort_if(in_array($domain, InstanceService::getBannedDomains()), 404);
  2730. }
  2731. $author = intval($status->profile_id) === intval($pid) || $user->is_admin;
  2732. $napi = $request->has(self::PF_API_ENTITY_KEY);
  2733. abort_if(
  2734. ! $status->type ||
  2735. ! in_array($status->type, ['photo', 'photo:album', 'photo:video:album', 'reply', 'text', 'video', 'video:album']),
  2736. 404,
  2737. );
  2738. if (! $author) {
  2739. if ($status->scope == 'private') {
  2740. abort_if(! FollowerService::follows($pid, $status->profile_id), 403);
  2741. } else {
  2742. abort_if(! in_array($status->scope, ['public', 'unlisted']), 403);
  2743. }
  2744. if ($request->has('cursor')) {
  2745. return $this->json([]);
  2746. }
  2747. }
  2748. $res = Status::where('reblog_of_id', $status->id)
  2749. ->orderByDesc('id')
  2750. ->cursorPaginate($limit)
  2751. ->withQueryString();
  2752. if (! $res) {
  2753. return $this->json([]);
  2754. }
  2755. $headers = [];
  2756. if ($author && $res->hasPages()) {
  2757. $links = '';
  2758. if ($res->onFirstPage()) {
  2759. if ($res->nextPageUrl()) {
  2760. $links = '<'.$res->nextPageUrl().'>; rel="prev"';
  2761. }
  2762. } else {
  2763. if ($res->previousPageUrl()) {
  2764. $links = '<'.$res->previousPageUrl().'>; rel="next"';
  2765. }
  2766. if ($res->nextPageUrl()) {
  2767. if (! empty($links)) {
  2768. $links .= ', ';
  2769. }
  2770. $links .= '<'.$res->nextPageUrl().'>; rel="prev"';
  2771. }
  2772. }
  2773. $headers = ['Link' => $links];
  2774. }
  2775. $res = $res->map(function ($status) use ($pid, $napi) {
  2776. $account = $napi ? AccountService::get($status->profile_id, true) : AccountService::getMastodon($status->profile_id, true);
  2777. if (! $account) {
  2778. return false;
  2779. }
  2780. if ($napi) {
  2781. $account['follows'] = $status->profile_id == $pid ? null : FollowerService::follows($pid, $status->profile_id);
  2782. }
  2783. return $account;
  2784. })
  2785. ->filter(function ($account) {
  2786. return $account && isset($account['id']);
  2787. })
  2788. ->values();
  2789. return $this->json($res, 200, $headers);
  2790. }
  2791. /**
  2792. * GET /api/v1/statuses/{id}/favourited_by
  2793. *
  2794. * @param int $id
  2795. * @return AccountTransformer
  2796. */
  2797. public function statusFavouritedBy(Request $request, $id)
  2798. {
  2799. abort_if(! $request->user() || ! $request->user()->token(), 403);
  2800. abort_unless($request->user()->tokenCan('read'), 403);
  2801. $this->validate($request, [
  2802. 'limit' => 'sometimes|integer|min:1',
  2803. ]);
  2804. $limit = $request->input('limit', 40);
  2805. if ($limit > 80) {
  2806. $limit = 80;
  2807. }
  2808. $user = $request->user();
  2809. $pid = $user->profile_id;
  2810. $status = Status::findOrFail($id);
  2811. $account = AccountService::get($status->profile_id, true);
  2812. if ($account && strpos($account['acct'], '@') != -1) {
  2813. $domain = parse_url($account['url'], PHP_URL_HOST);
  2814. abort_if(in_array($domain, InstanceService::getBannedDomains()), 404);
  2815. }
  2816. abort_if(! $account, 404);
  2817. $author = intval($status->profile_id) === intval($pid) || $user->is_admin;
  2818. $napi = $request->has(self::PF_API_ENTITY_KEY);
  2819. abort_if(
  2820. ! $status->type ||
  2821. ! in_array($status->type, ['photo', 'photo:album', 'photo:video:album', 'reply', 'text', 'video', 'video:album']),
  2822. 404,
  2823. );
  2824. if (! $author) {
  2825. if ($status->scope == 'private') {
  2826. abort_if(! FollowerService::follows($pid, $status->profile_id), 403);
  2827. } else {
  2828. abort_if(! in_array($status->scope, ['public', 'unlisted']), 403);
  2829. }
  2830. if ($request->has('cursor')) {
  2831. return $this->json([]);
  2832. }
  2833. }
  2834. $res = Like::where('status_id', $status->id)
  2835. ->orderByDesc('id')
  2836. ->cursorPaginate($limit)
  2837. ->withQueryString();
  2838. if (! $res) {
  2839. return $this->json([]);
  2840. }
  2841. $headers = [];
  2842. if ($author && $res->hasPages()) {
  2843. $links = '';
  2844. if ($res->onFirstPage()) {
  2845. if ($res->nextPageUrl()) {
  2846. $links = '<'.$res->nextPageUrl().'>; rel="prev"';
  2847. }
  2848. } else {
  2849. if ($res->previousPageUrl()) {
  2850. $links = '<'.$res->previousPageUrl().'>; rel="next"';
  2851. }
  2852. if ($res->nextPageUrl()) {
  2853. if (! empty($links)) {
  2854. $links .= ', ';
  2855. }
  2856. $links .= '<'.$res->nextPageUrl().'>; rel="prev"';
  2857. }
  2858. }
  2859. $headers = ['Link' => $links];
  2860. }
  2861. $res = $res->map(function ($like) use ($pid, $napi) {
  2862. $account = $napi ? AccountService::get($like->profile_id, true) : AccountService::getMastodon($like->profile_id, true);
  2863. if (! $account) {
  2864. return false;
  2865. }
  2866. if ($napi) {
  2867. $account['follows'] = $like->profile_id == $pid ? null : FollowerService::follows($pid, $like->profile_id);
  2868. }
  2869. return $account;
  2870. })
  2871. ->filter(function ($account) {
  2872. return $account && isset($account['id']);
  2873. })
  2874. ->values();
  2875. return $this->json($res, 200, $headers);
  2876. }
  2877. /**
  2878. * POST /api/v1/statuses
  2879. *
  2880. *
  2881. * @return StatusTransformer
  2882. */
  2883. public function statusCreate(Request $request)
  2884. {
  2885. abort_if(! $request->user() || ! $request->user()->token(), 403);
  2886. abort_unless($request->user()->tokenCan('write'), 403);
  2887. $this->validate($request, [
  2888. 'status' => 'nullable|string|max:'.(int) config_cache('pixelfed.max_caption_length'),
  2889. 'in_reply_to_id' => 'nullable',
  2890. 'media_ids' => 'sometimes|array|max:'.(int) config_cache('pixelfed.max_album_length'),
  2891. 'sensitive' => 'nullable',
  2892. 'visibility' => 'string|in:private,unlisted,public',
  2893. 'spoiler_text' => 'sometimes|max:140',
  2894. 'place_id' => 'sometimes|integer|min:1|max:128769',
  2895. 'collection_ids' => 'sometimes|array|max:3',
  2896. 'comments_disabled' => 'sometimes|boolean',
  2897. ]);
  2898. if ($request->hasHeader('idempotency-key')) {
  2899. $key = 'pf:api:v1:status:idempotency-key:'.$request->user()->id.':'.hash('sha1', $request->header('idempotency-key'));
  2900. $exists = Cache::has($key);
  2901. abort_if($exists, 400, 'Duplicate idempotency key.');
  2902. Cache::put($key, 1, 3600);
  2903. }
  2904. if (config('costar.enabled') == true) {
  2905. $blockedKeywords = config('costar.keyword.block');
  2906. if ($blockedKeywords !== null && $request->status) {
  2907. $keywords = config('costar.keyword.block');
  2908. foreach ($keywords as $kw) {
  2909. if (Str::contains($request->status, $kw) == true) {
  2910. abort(400, 'Invalid object. Contains banned keyword.');
  2911. }
  2912. }
  2913. }
  2914. }
  2915. if (! $request->filled('media_ids') && ! $request->filled('in_reply_to_id')) {
  2916. abort(403, 'Empty statuses are not allowed');
  2917. }
  2918. $ids = $request->input('media_ids');
  2919. $in_reply_to_id = $request->input('in_reply_to_id');
  2920. $user = $request->user();
  2921. if ($user->has_roles) {
  2922. if ($in_reply_to_id != null) {
  2923. abort_if(! UserRoleService::can('can-comment', $user->id), 403, 'Invalid permissions for this action');
  2924. } else {
  2925. abort_if(! UserRoleService::can('can-post', $user->id), 403, 'Invalid permissions for this action');
  2926. }
  2927. }
  2928. $profile = $user->profile;
  2929. $limitKey = 'compose:rate-limit:store:'.$user->id;
  2930. $limitTtl = now()->addMinutes(15);
  2931. $limitReached = Cache::remember($limitKey, $limitTtl, function () use ($user) {
  2932. $minId = SnowflakeService::byDate(now()->subDays(1));
  2933. $dailyLimit = Status::whereProfileId($user->profile_id)
  2934. ->where('id', '>', $minId)
  2935. ->count();
  2936. return $dailyLimit >= 1000;
  2937. });
  2938. abort_if($limitReached == true, 429);
  2939. $visibility = $profile->is_private ? 'private' : (
  2940. $profile->unlisted == true &&
  2941. $request->input('visibility', 'public') == 'public' ?
  2942. 'unlisted' :
  2943. $request->input('visibility', 'public'));
  2944. if ($user->last_active_at == null) {
  2945. return [];
  2946. }
  2947. $content = strip_tags($request->input('status'));
  2948. $rendered = Autolink::create()->autolink($content);
  2949. $cw = $user->profile->cw == true ? true : $request->boolean('sensitive', false);
  2950. $spoilerText = $cw && $request->filled('spoiler_text') ? $request->input('spoiler_text') : null;
  2951. if ($in_reply_to_id) {
  2952. $parent = Status::findOrFail($in_reply_to_id);
  2953. if ($parent->comments_disabled) {
  2954. return $this->json('Comments have been disabled on this post', 422);
  2955. }
  2956. $blocks = UserFilterService::blocks($parent->profile_id);
  2957. abort_if(in_array($profile->id, $blocks), 422, 'Cannot reply to this post at this time.');
  2958. $status = new Status;
  2959. $status->caption = $content;
  2960. $status->rendered = $rendered;
  2961. $status->scope = $visibility;
  2962. $status->visibility = $visibility;
  2963. $status->profile_id = $user->profile_id;
  2964. $status->is_nsfw = $cw;
  2965. $status->cw_summary = $spoilerText;
  2966. $status->in_reply_to_id = $parent->id;
  2967. $status->in_reply_to_profile_id = $parent->profile_id;
  2968. $status->save();
  2969. StatusService::del($parent->id);
  2970. Cache::forget('status:replies:all:'.$parent->id);
  2971. }
  2972. if ($ids) {
  2973. if (Media::whereUserId($user->id)
  2974. ->whereNull('status_id')
  2975. ->find($ids)
  2976. ->count() == 0
  2977. ) {
  2978. abort(400, 'Invalid media_ids');
  2979. }
  2980. if (! $in_reply_to_id) {
  2981. $status = new Status;
  2982. $status->caption = $content;
  2983. $status->rendered = $rendered;
  2984. $status->profile_id = $user->profile_id;
  2985. $status->is_nsfw = $cw;
  2986. $status->cw_summary = $spoilerText;
  2987. $status->scope = 'draft';
  2988. $status->visibility = 'draft';
  2989. if ($request->has('place_id')) {
  2990. $status->place_id = $request->input('place_id');
  2991. }
  2992. $status->save();
  2993. }
  2994. $mimes = [];
  2995. foreach ($ids as $k => $v) {
  2996. if ($k + 1 > (int) config_cache('pixelfed.max_album_length')) {
  2997. continue;
  2998. }
  2999. $m = Media::whereUserId($user->id)->whereNull('status_id')->findOrFail($v);
  3000. if ($m->profile_id !== $user->profile_id || $m->status_id) {
  3001. abort(403, 'Invalid media id');
  3002. }
  3003. $m->order = $k + 1;
  3004. $m->status_id = $status->id;
  3005. $m->save();
  3006. array_push($mimes, $m->mime);
  3007. }
  3008. if (empty($mimes)) {
  3009. $status->delete();
  3010. abort(400, 'Invalid media ids');
  3011. }
  3012. if ($request->has('comments_disabled') && $request->input('comments_disabled')) {
  3013. $status->comments_disabled = true;
  3014. }
  3015. $status->scope = $visibility;
  3016. $status->visibility = $visibility;
  3017. $status->type = StatusController::mimeTypeCheck($mimes);
  3018. $status->save();
  3019. }
  3020. if (! $status) {
  3021. abort(500, 'An error occured.');
  3022. }
  3023. NewStatusPipeline::dispatch($status);
  3024. if ($status->in_reply_to_id) {
  3025. CommentPipeline::dispatch($parent, $status);
  3026. }
  3027. Cache::forget('user:account:id:'.$user->id);
  3028. Cache::forget('_api:statuses:recent_9:'.$user->profile_id);
  3029. Cache::forget('profile:status_count:'.$user->profile_id);
  3030. Cache::forget($user->storageUsedKey());
  3031. Cache::forget('profile:embed:'.$status->profile_id);
  3032. Cache::forget($limitKey);
  3033. if ($request->has('collection_ids') && $ids) {
  3034. $collections = Collection::whereProfileId($user->profile_id)
  3035. ->find($request->input('collection_ids'))
  3036. ->each(function ($collection) use ($status) {
  3037. $count = $collection->items()->count();
  3038. $item = CollectionItem::firstOrCreate([
  3039. 'collection_id' => $collection->id,
  3040. 'object_type' => 'App\Status',
  3041. 'object_id' => $status->id,
  3042. ], [
  3043. 'order' => $count,
  3044. ]);
  3045. CollectionService::addItem(
  3046. $collection->id,
  3047. $status->id,
  3048. $count
  3049. );
  3050. $collection->updated_at = now();
  3051. $collection->save();
  3052. CollectionService::setCollection($collection->id, $collection);
  3053. });
  3054. }
  3055. $res = StatusService::getMastodon($status->id, false);
  3056. $res['favourited'] = false;
  3057. $res['language'] = 'en';
  3058. $res['bookmarked'] = false;
  3059. $res['card'] = null;
  3060. return $this->json($res);
  3061. }
  3062. /**
  3063. * DELETE /api/v1/statuses
  3064. *
  3065. * @param int $id
  3066. * @return null
  3067. */
  3068. public function statusDelete(Request $request, $id)
  3069. {
  3070. abort_if(! $request->user() || ! $request->user()->token(), 403);
  3071. abort_unless($request->user()->tokenCan('write'), 403);
  3072. AccountService::setLastActive($request->user()->id);
  3073. $status = Status::whereProfileId($request->user()->profile->id)
  3074. ->findOrFail($id);
  3075. $resource = new Fractal\Resource\Item($status, new StatusTransformer());
  3076. Cache::forget('profile:status_count:'.$status->profile_id);
  3077. StatusDelete::dispatch($status);
  3078. $res = $this->fractal->createData($resource)->toArray();
  3079. $res['text'] = $res['content'];
  3080. unset($res['content']);
  3081. return $this->json($res);
  3082. }
  3083. /**
  3084. * POST /api/v1/statuses/{id}/reblog
  3085. *
  3086. * @param int $id
  3087. * @return StatusTransformer
  3088. */
  3089. public function statusShare(Request $request, $id)
  3090. {
  3091. abort_if(! $request->user() || ! $request->user()->token(), 403);
  3092. abort_unless($request->user()->tokenCan('write'), 403);
  3093. $user = $request->user();
  3094. abort_if($user->has_roles && ! UserRoleService::can('can-share', $user->id), 403, 'Invalid permissions for this action');
  3095. AccountService::setLastActive($user->id);
  3096. $status = Status::whereScope('public')->findOrFail($id);
  3097. if ($status && ($status->uri || $status->url || $status->object_url)) {
  3098. $url = $status->uri ?? $status->url ?? $status->object_url;
  3099. $domain = parse_url($url, PHP_URL_HOST);
  3100. abort_if(in_array($domain, InstanceService::getBannedDomains()), 404);
  3101. }
  3102. if (intval($status->profile_id) !== intval($user->profile_id)) {
  3103. if ($status->scope == 'private') {
  3104. abort_if(! FollowerService::follows($user->profile_id, $status->profile_id), 403);
  3105. } else {
  3106. abort_if(! in_array($status->scope, ['public', 'unlisted']), 403);
  3107. }
  3108. $blocks = UserFilterService::blocks($status->profile_id);
  3109. if ($blocks && in_array($user->profile_id, $blocks)) {
  3110. abort(422);
  3111. }
  3112. }
  3113. $share = Status::firstOrCreate([
  3114. 'profile_id' => $user->profile_id,
  3115. 'reblog_of_id' => $status->id,
  3116. 'type' => 'share',
  3117. 'in_reply_to_profile_id' => $status->profile_id,
  3118. 'scope' => 'public',
  3119. 'visibility' => 'public',
  3120. ]);
  3121. SharePipeline::dispatch($share)->onQueue('low');
  3122. StatusService::del($status->id);
  3123. ReblogService::add($user->profile_id, $status->id);
  3124. $res = StatusService::getMastodon($status->id);
  3125. $res['reblogged'] = true;
  3126. return $this->json($res);
  3127. }
  3128. /**
  3129. * POST /api/v1/statuses/{id}/unreblog
  3130. *
  3131. * @param int $id
  3132. * @return StatusTransformer
  3133. */
  3134. public function statusUnshare(Request $request, $id)
  3135. {
  3136. abort_if(! $request->user() || ! $request->user()->token(), 403);
  3137. abort_unless($request->user()->tokenCan('write'), 403);
  3138. $user = $request->user();
  3139. abort_if($user->has_roles && ! UserRoleService::can('can-share', $user->id), 403, 'Invalid permissions for this action');
  3140. AccountService::setLastActive($user->id);
  3141. $status = Status::whereScope('public')->findOrFail($id);
  3142. if (intval($status->profile_id) !== intval($user->profile_id)) {
  3143. if ($status->scope == 'private') {
  3144. abort_if(! FollowerService::follows($user->profile_id, $status->profile_id), 403);
  3145. } else {
  3146. abort_if(! in_array($status->scope, ['public', 'unlisted']), 403);
  3147. }
  3148. }
  3149. $reblog = Status::whereProfileId($user->profile_id)
  3150. ->whereReblogOfId($status->id)
  3151. ->first();
  3152. if (! $reblog) {
  3153. $res = StatusService::getMastodon($status->id);
  3154. $res['reblogged'] = false;
  3155. return $this->json($res);
  3156. }
  3157. UndoSharePipeline::dispatch($reblog)->onQueue('low');
  3158. ReblogService::del($user->profile_id, $status->id);
  3159. $res = StatusService::getMastodon($status->id);
  3160. $res['reblogged'] = false;
  3161. return $this->json($res);
  3162. }
  3163. /**
  3164. * GET /api/v1/timelines/tag/{hashtag}
  3165. *
  3166. * @param string $hashtag
  3167. * @return StatusTransformer
  3168. */
  3169. public function timelineHashtag(Request $request, $hashtag)
  3170. {
  3171. abort_if(! $request->user() || ! $request->user()->token(), 403);
  3172. abort_unless($request->user()->tokenCan('read'), 403);
  3173. $this->validate($request, [
  3174. 'page' => 'nullable|integer|max:40',
  3175. 'min_id' => 'nullable|integer|min:0|max:'.PHP_INT_MAX,
  3176. 'max_id' => 'nullable|integer|min:0|max:'.PHP_INT_MAX,
  3177. 'limit' => 'sometimes|integer|min:1',
  3178. 'only_media' => 'sometimes',
  3179. '_pe' => 'sometimes',
  3180. ]);
  3181. $user = $request->user();
  3182. abort_if(
  3183. $user->has_roles && ! UserRoleService::can('can-view-hashtag-feed', $user->id),
  3184. 403,
  3185. 'Invalid permissions for this action'
  3186. );
  3187. if (config('database.default') === 'pgsql') {
  3188. $tag = Hashtag::where('name', 'ilike', $hashtag)
  3189. ->orWhere('slug', 'ilike', $hashtag)
  3190. ->first();
  3191. } else {
  3192. $tag = Hashtag::whereName($hashtag)
  3193. ->orWhere('slug', $hashtag)
  3194. ->first();
  3195. }
  3196. if (! $tag) {
  3197. return response()->json([]);
  3198. }
  3199. if ($tag->is_banned == true) {
  3200. return $this->json([]);
  3201. }
  3202. $min = $request->input('min_id');
  3203. $max = $request->input('max_id');
  3204. $limit = $request->input('limit', 20);
  3205. if ($limit > 40) {
  3206. $limit = 40;
  3207. }
  3208. $onlyMedia = $request->boolean('only_media', true);
  3209. $pe = $request->has(self::PF_API_ENTITY_KEY);
  3210. $pid = $request->user()->profile_id;
  3211. if ($min || $max) {
  3212. $minMax = SnowflakeService::byDate(now()->subMonths(6));
  3213. if ($min && intval($min) < $minMax) {
  3214. return [];
  3215. }
  3216. if ($max && intval($max) < $minMax) {
  3217. return [];
  3218. }
  3219. }
  3220. $filters = UserFilterService::filters($pid);
  3221. $domainBlocks = UserFilterService::domainBlocks($pid);
  3222. if (! $min && ! $max) {
  3223. $id = 1;
  3224. $dir = '>';
  3225. } else {
  3226. $dir = $min ? '>' : '<';
  3227. $id = $min ?? $max;
  3228. }
  3229. $res = StatusHashtag::whereHashtagId($tag->id)
  3230. ->where('status_id', $dir, $id)
  3231. ->orderBy('status_id', 'desc')
  3232. ->limit(100)
  3233. ->pluck('status_id')
  3234. ->map(function ($i) use ($pe) {
  3235. return $pe ? StatusService::get($i, false) : StatusService::getMastodon($i, false);
  3236. })
  3237. ->filter(function ($i) use ($onlyMedia, $pid) {
  3238. if (! $i || ! isset($i['account'], $i['account']['id'])) {
  3239. return false;
  3240. }
  3241. if ($i['visibility'] === 'unlisted') {
  3242. if ((int) $i['account']['id'] !== $pid) {
  3243. return false;
  3244. }
  3245. }
  3246. if ($i['visibility'] === 'private') {
  3247. if ((int) $i['account']['id'] !== $pid) {
  3248. return FollowerService::follows($pid, $i['account']['id'], true);
  3249. }
  3250. }
  3251. if ($onlyMedia == true) {
  3252. if (! isset($i['media_attachments']) || ! count($i['media_attachments'])) {
  3253. return false;
  3254. }
  3255. }
  3256. return $i && isset($i['account'], $i['url']);
  3257. })
  3258. ->filter(function ($i) use ($filters, $domainBlocks) {
  3259. $domain = strtolower(parse_url($i['url'], PHP_URL_HOST));
  3260. return ! in_array($i['account']['id'], $filters) && ! in_array($domain, $domainBlocks);
  3261. })
  3262. ->take($limit)
  3263. ->values()
  3264. ->toArray();
  3265. return $this->json($res);
  3266. }
  3267. /**
  3268. * GET /api/v1/bookmarks
  3269. *
  3270. *
  3271. *
  3272. * @return StatusTransformer
  3273. */
  3274. public function bookmarks(Request $request)
  3275. {
  3276. abort_if(! $request->user() || ! $request->user()->token(), 403);
  3277. abort_unless($request->user()->tokenCan('read'), 403);
  3278. $this->validate($request, [
  3279. 'limit' => 'sometimes|integer|min:1',
  3280. 'max_id' => 'nullable|integer|min:0',
  3281. 'since_id' => 'nullable|integer|min:0',
  3282. 'min_id' => 'nullable|integer|min:0',
  3283. ]);
  3284. $pe = $request->has('_pe');
  3285. $pid = $request->user()->profile_id;
  3286. $limit = $request->input('limit') ?? 20;
  3287. if ($limit > 40) {
  3288. $limit = 40;
  3289. }
  3290. $max_id = $request->input('max_id');
  3291. $since_id = $request->input('since_id');
  3292. $min_id = $request->input('min_id');
  3293. $dir = $min_id ? '>' : '<';
  3294. $id = $min_id ?? $max_id;
  3295. $bookmarkQuery = Bookmark::whereProfileId($pid)
  3296. ->orderByDesc('id')
  3297. ->cursorPaginate($limit);
  3298. $bookmarks = $bookmarkQuery->map(function ($bookmark) use ($pid, $pe) {
  3299. $status = $pe ? StatusService::get($bookmark->status_id, false) : StatusService::getMastodon($bookmark->status_id, false);
  3300. if ($status) {
  3301. $status['bookmarked'] = true;
  3302. $status['favourited'] = LikeService::liked($pid, $status['id']);
  3303. $status['reblogged'] = ReblogService::get($pid, $status['id']);
  3304. }
  3305. return $status;
  3306. })
  3307. ->filter()
  3308. ->values()
  3309. ->toArray();
  3310. $links = null;
  3311. $headers = [];
  3312. if ($bookmarkQuery->nextCursor()) {
  3313. $links .= '<'.$bookmarkQuery->nextPageUrl().'&limit='.$limit.'>; rel="next"';
  3314. }
  3315. if ($bookmarkQuery->previousCursor()) {
  3316. if ($links != null) {
  3317. $links .= ', ';
  3318. }
  3319. $links .= '<'.$bookmarkQuery->previousPageUrl().'&limit='.$limit.'>; rel="prev"';
  3320. }
  3321. if ($links) {
  3322. $headers = ['Link' => $links];
  3323. }
  3324. return $this->json($bookmarks, 200, $headers);
  3325. }
  3326. /**
  3327. * POST /api/v1/statuses/{id}/bookmark
  3328. *
  3329. *
  3330. *
  3331. * @return StatusTransformer
  3332. */
  3333. public function bookmarkStatus(Request $request, $id)
  3334. {
  3335. abort_if(! $request->user() || ! $request->user()->token(), 403);
  3336. abort_unless($request->user()->tokenCan('write'), 403);
  3337. $status = Status::findOrFail($id);
  3338. $pid = $request->user()->profile_id;
  3339. abort_if($user->has_roles && ! UserRoleService::can('can-bookmark', $user->id), 403, 'Invalid permissions for this action');
  3340. abort_if($status->in_reply_to_id || $status->reblog_of_id, 404);
  3341. abort_if(! in_array($status->scope, ['public', 'unlisted', 'private']), 404);
  3342. abort_if(! in_array($status->type, ['photo', 'photo:album', 'video', 'video:album', 'photo:video:album']), 404);
  3343. if ($status->scope == 'private') {
  3344. abort_if(
  3345. $pid !== $status->profile_id && ! FollowerService::follows($pid, $status->profile_id),
  3346. 404,
  3347. 'Error: You cannot bookmark private posts from accounts you do not follow.'
  3348. );
  3349. }
  3350. Bookmark::firstOrCreate([
  3351. 'status_id' => $status->id,
  3352. 'profile_id' => $pid,
  3353. ]);
  3354. BookmarkService::add($pid, $status->id);
  3355. $res = StatusService::getMastodon($status->id, false);
  3356. $res['bookmarked'] = true;
  3357. return $this->json($res);
  3358. }
  3359. /**
  3360. * POST /api/v1/statuses/{id}/unbookmark
  3361. *
  3362. *
  3363. *
  3364. * @return StatusTransformer
  3365. */
  3366. public function unbookmarkStatus(Request $request, $id)
  3367. {
  3368. abort_if(! $request->user() || ! $request->user()->token(), 403);
  3369. abort_unless($request->user()->tokenCan('write'), 403);
  3370. $status = Status::findOrFail($id);
  3371. $pid = $request->user()->profile_id;
  3372. abort_if($user->has_roles && ! UserRoleService::can('can-bookmark', $user->id), 403, 'Invalid permissions for this action');
  3373. abort_if($status->in_reply_to_id || $status->reblog_of_id, 404);
  3374. abort_if(! in_array($status->scope, ['public', 'unlisted', 'private']), 404);
  3375. abort_if(! in_array($status->type, ['photo', 'photo:album', 'video', 'video:album', 'photo:video:album']), 404);
  3376. $bookmark = Bookmark::whereStatusId($status->id)
  3377. ->whereProfileId($pid)
  3378. ->first();
  3379. if ($bookmark) {
  3380. BookmarkService::del($pid, $status->id);
  3381. $bookmark->delete();
  3382. }
  3383. $res = StatusService::getMastodon($status->id, false);
  3384. $res['bookmarked'] = false;
  3385. return $this->json($res);
  3386. }
  3387. /**
  3388. * GET /api/v1/discover/posts
  3389. *
  3390. *
  3391. * @return array
  3392. */
  3393. public function discoverPosts(Request $request)
  3394. {
  3395. abort_if(! $request->user() || ! $request->user()->token(), 403);
  3396. abort_unless($request->user()->tokenCan('read'), 403);
  3397. $this->validate($request, [
  3398. 'limit' => 'integer|min:1|max:40',
  3399. ]);
  3400. $limit = $request->input('limit', 40);
  3401. $pid = $request->user()->profile_id;
  3402. $filters = UserFilterService::filters($pid);
  3403. $forYou = DiscoverService::getForYou();
  3404. $posts = $forYou->take(50)->map(function ($post) {
  3405. return StatusService::getMastodon($post);
  3406. })
  3407. ->filter(function ($post) use ($filters) {
  3408. return $post &&
  3409. isset($post['account']) &&
  3410. isset($post['account']['id']) &&
  3411. ! in_array($post['account']['id'], $filters);
  3412. })
  3413. ->take(12)
  3414. ->values();
  3415. return $this->json(compact('posts'));
  3416. }
  3417. /**
  3418. * GET /api/v2/statuses/{id}/replies
  3419. *
  3420. *
  3421. * @return array
  3422. */
  3423. public function statusReplies(Request $request, $id)
  3424. {
  3425. abort_if(! $request->user(), 403);
  3426. $this->validate($request, [
  3427. 'limit' => 'sometimes|integer|min:1',
  3428. 'sort' => 'in:all,newest,popular',
  3429. ]);
  3430. $limit = $request->input('limit', 3);
  3431. if ($limit > 10) {
  3432. $limit = 10;
  3433. }
  3434. $pid = $request->user()->profile_id;
  3435. $status = StatusService::getMastodon($id, false);
  3436. abort_if(! $status, 404);
  3437. if ($status['visibility'] == 'private') {
  3438. if ($pid != $status['account']['id']) {
  3439. abort_unless(FollowerService::follows($pid, $status['account']['id']), 404);
  3440. }
  3441. }
  3442. $sortBy = $request->input('sort', 'all');
  3443. if ($sortBy == 'all' && isset($status['replies_count']) && $status['replies_count'] && $request->has('refresh_cache')) {
  3444. if (! Cache::has('status:replies:all-rc:'.$id)) {
  3445. Cache::forget('status:replies:all:'.$id);
  3446. Cache::put('status:replies:all-rc:'.$id, true, 300);
  3447. }
  3448. }
  3449. if ($sortBy == 'all' && ! $request->has('cursor')) {
  3450. $ids = Cache::remember('status:replies:all:'.$id, 3600, function () use ($id) {
  3451. return DB::table('statuses')
  3452. ->where('in_reply_to_id', $id)
  3453. ->orderBy('id')
  3454. ->cursorPaginate(3);
  3455. });
  3456. } else {
  3457. $ids = DB::table('statuses')
  3458. ->where('in_reply_to_id', $id)
  3459. ->when($sortBy, function ($q, $sortBy) {
  3460. if ($sortBy === 'all') {
  3461. return $q->orderBy('id');
  3462. }
  3463. if ($sortBy === 'newest') {
  3464. return $q->orderByDesc('created_at');
  3465. }
  3466. if ($sortBy === 'popular') {
  3467. return $q->orderByDesc('likes_count');
  3468. }
  3469. })
  3470. ->cursorPaginate($limit);
  3471. }
  3472. $filters = UserFilterService::filters($pid);
  3473. $data = $ids->filter(function ($post) use ($filters) {
  3474. return ! in_array($post->profile_id, $filters);
  3475. })
  3476. ->map(function ($post) use ($pid) {
  3477. $status = StatusService::get($post->id, false);
  3478. if (! $status || ! isset($status['id'])) {
  3479. return false;
  3480. }
  3481. $status['favourited'] = LikeService::liked($pid, $post->id);
  3482. return $status;
  3483. })
  3484. ->map(function ($post) {
  3485. if (isset($post['account']) && isset($post['account']['id'])) {
  3486. $account = AccountService::get($post['account']['id'], true);
  3487. $post['account'] = $account;
  3488. }
  3489. return $post;
  3490. })
  3491. ->filter(function ($post) {
  3492. return $post && isset($post['id']) && isset($post['account']) && isset($post['account']['id']);
  3493. })
  3494. ->values();
  3495. $res = [
  3496. 'data' => $data,
  3497. 'next' => $ids->nextPageUrl(),
  3498. ];
  3499. return $this->json($res);
  3500. }
  3501. /**
  3502. * GET /api/v2/statuses/{id}/state
  3503. *
  3504. *
  3505. * @return array
  3506. */
  3507. public function statusState(Request $request, $id)
  3508. {
  3509. abort_if(! $request->user(), 403);
  3510. $status = Status::findOrFail($id);
  3511. $pid = $request->user()->profile_id;
  3512. abort_if(! in_array($status->scope, ['public', 'unlisted', 'private']), 404);
  3513. return $this->json(StatusService::getState($status->id, $pid));
  3514. }
  3515. /**
  3516. * GET /api/v1.1/discover/accounts/popular
  3517. *
  3518. *
  3519. * @return array
  3520. */
  3521. public function discoverAccountsPopular(Request $request)
  3522. {
  3523. abort_if(! $request->user() || ! $request->user()->token(), 403);
  3524. abort_unless($request->user()->tokenCan('read'), 403);
  3525. $pid = $request->user()->profile_id;
  3526. $ids = Cache::remember('api:v1.1:discover:accounts:popular', 14400, function () {
  3527. return DB::table('profiles')
  3528. ->where('is_private', false)
  3529. ->whereNull('status')
  3530. ->orderByDesc('profiles.followers_count')
  3531. ->limit(30)
  3532. ->get();
  3533. });
  3534. $filters = UserFilterService::filters($pid);
  3535. $asf = AdminShadowFilterService::getHideFromPublicFeedsList();
  3536. $ids = $ids->map(function ($profile) {
  3537. return AccountService::get($profile->id, true);
  3538. })
  3539. ->filter(function ($profile) {
  3540. return $profile && isset($profile['id'], $profile['locked']) && ! $profile['locked'];
  3541. })
  3542. ->filter(function ($profile) use ($pid) {
  3543. return $profile['id'] != $pid;
  3544. })
  3545. ->filter(function ($profile) use ($pid) {
  3546. return ! FollowerService::follows($pid, $profile['id'], true);
  3547. })
  3548. ->filter(function ($profile) use ($asf) {
  3549. return ! in_array($profile['id'], $asf);
  3550. })
  3551. ->filter(function ($profile) use ($filters) {
  3552. return ! in_array($profile['id'], $filters);
  3553. })
  3554. ->take(16)
  3555. ->values();
  3556. return $this->json($ids);
  3557. }
  3558. /**
  3559. * GET /api/v1/preferences
  3560. *
  3561. *
  3562. * @return array
  3563. */
  3564. public function getPreferences(Request $request)
  3565. {
  3566. abort_if(! $request->user() || ! $request->user()->token(), 403);
  3567. abort_unless($request->user()->tokenCan('read'), 403);
  3568. $pid = $request->user()->profile_id;
  3569. $account = AccountService::get($pid);
  3570. return $this->json([
  3571. 'posting:default:visibility' => $account['locked'] ? 'private' : 'public',
  3572. 'posting:default:sensitive' => false,
  3573. 'posting:default:language' => null,
  3574. 'reading:expand:media' => 'default',
  3575. 'reading:expand:spoilers' => false,
  3576. ]);
  3577. }
  3578. /**
  3579. * GET /api/v1/trends
  3580. *
  3581. *
  3582. * @return array
  3583. */
  3584. public function getTrends(Request $request)
  3585. {
  3586. abort_if(! $request->user() || ! $request->user()->token(), 403);
  3587. abort_unless($request->user()->tokenCan('read'), 403);
  3588. return $this->json([]);
  3589. }
  3590. /**
  3591. * GET /api/v1/announcements
  3592. *
  3593. *
  3594. * @return array
  3595. */
  3596. public function getAnnouncements(Request $request)
  3597. {
  3598. abort_if(! $request->user() || ! $request->user()->token(), 403);
  3599. abort_unless($request->user()->tokenCan('read'), 403);
  3600. return $this->json([]);
  3601. }
  3602. /**
  3603. * GET /api/v1/markers
  3604. *
  3605. *
  3606. * @return array
  3607. */
  3608. public function getMarkers(Request $request)
  3609. {
  3610. abort_if(! $request->user() || ! $request->user()->token(), 403);
  3611. abort_unless($request->user()->tokenCan('read'), 403);
  3612. $type = $request->input('timeline');
  3613. if (is_array($type)) {
  3614. $type = $type[0];
  3615. }
  3616. if (! $type || ! in_array($type, ['home', 'notifications'])) {
  3617. return $this->json([]);
  3618. }
  3619. $pid = $request->user()->profile_id;
  3620. return $this->json(MarkerService::get($pid, $type));
  3621. }
  3622. /**
  3623. * POST /api/v1/markers
  3624. *
  3625. *
  3626. * @return array
  3627. */
  3628. public function setMarkers(Request $request)
  3629. {
  3630. abort_if(! $request->user() || ! $request->user()->token(), 403);
  3631. abort_unless($request->user()->tokenCan('write'), 403);
  3632. $pid = $request->user()->profile_id;
  3633. $home = $request->input('home[last_read_id]');
  3634. $notifications = $request->input('notifications[last_read_id]');
  3635. if ($home) {
  3636. return $this->json(MarkerService::set($pid, 'home', $home));
  3637. }
  3638. if ($notifications) {
  3639. return $this->json(MarkerService::set($pid, 'notifications', $notifications));
  3640. }
  3641. return $this->json([]);
  3642. }
  3643. /**
  3644. * GET /api/v1/instance/peers
  3645. *
  3646. *
  3647. * @return array
  3648. */
  3649. public function instancePeers(Request $request)
  3650. {
  3651. if ((bool) config('instance.show_peers') == false) {
  3652. return $this->json([]);
  3653. }
  3654. return $this->json(
  3655. Cache::remember(InstanceService::CACHE_KEY_API_PEERS_LIST, now()->addHours(24), function () {
  3656. return Instance::whereNotNull('nodeinfo_last_fetched')
  3657. ->whereBanned(false)
  3658. ->where('nodeinfo_last_fetched', '>', now()->subDays(8))
  3659. ->pluck('domain');
  3660. })
  3661. );
  3662. }
  3663. }