ApiV1Controller.php 149 KB

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