ApiV1Controller.php 145 KB

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