ApiV1Controller.php 146 KB

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