ApiV1Controller.php 94 KB

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