ApiV1Controller.php 140 KB

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