ApiV1Controller.php 138 KB

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