1
0

ApiV1Controller.php 94 KB

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