ApiV1Controller.php 99 KB

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